Example usage for javax.xml.bind ValidationEvent getLinkedException

List of usage examples for javax.xml.bind ValidationEvent getLinkedException

Introduction

In this page you can find the example usage for javax.xml.bind ValidationEvent getLinkedException.

Prototype

public Throwable getLinkedException();

Source Link

Document

Retrieve the linked exception for this warning/error.

Usage

From source file:Main.java

@SuppressWarnings("rawtypes")
public static void marshal(Object object, Writer w) throws JAXBException {
    Class clazz = object.getClass();
    JAXBContext context = s_contexts.get(clazz);
    if (context == null) {
        context = JAXBContext.newInstance(clazz);
        s_contexts.put(clazz, context);//from   w  w  w .  jav a  2 s .  c  o m
    }

    ValidationEventCollector valEventHndlr = new ValidationEventCollector();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setSchema(null);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setEventHandler(valEventHndlr);

    try {
        marshaller.marshal(object, w);
    } catch (Exception e) {
        if (e instanceof JAXBException) {
            throw (JAXBException) e;
        } else {
            throw new MarshalException(e.getMessage(), e);
        }
    }
    if (valEventHndlr.hasEvents()) {
        for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
            if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                // throw a new Marshall Exception if there is a parsing error
                throw new MarshalException(valEvent.getMessage(), valEvent.getLinkedException());
            }
        }
    }
}

From source file:ee.ria.xroad.opmonitordaemon.QueryRequestHandler.java

private static boolean validationFailed(ValidationEvent event) {
    if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {
        return false;
    }/*w  ww .ja va2 s .co  m*/

    if (event.getSeverity() == ValidationEvent.ERROR && event.getLinkedException() instanceof AccessorException
            && event.getLinkedException().getCause() instanceof CodedException) {
        return false;
    }

    return true;
}

From source file:Main.java

public static <T> T unmarshal(Reader r, Class<T> clazz)
        throws JAXBException, XMLStreamException, FactoryConfigurationError {
    JAXBContext context = s_contexts.get(clazz);
    if (context == null) {
        context = JAXBContext.newInstance(clazz);
        s_contexts.put(clazz, context);/* w ww. j av  a 2 s .  co  m*/
    }

    ValidationEventCollector valEventHndlr = new ValidationEventCollector();
    XMLStreamReader xmlsr = XMLInputFactory.newFactory().createXMLStreamReader(r);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null);
    unmarshaller.setEventHandler(valEventHndlr);

    JAXBElement<T> elem = null;
    try {
        elem = unmarshaller.unmarshal(xmlsr, clazz);
    } catch (Exception e) {
        if (e instanceof JAXBException) {
            throw (JAXBException) e;
        } else {
            throw new UnmarshalException(e.getMessage(), e);
        }
    }

    if (valEventHndlr.hasEvents()) {
        for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
            if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                // throw a new Unmarshall Exception if there is a parsing error
                String msg = MessageFormat.format("Line {0}, Col: {1}: {2}",
                        valEvent.getLocator().getLineNumber(), valEvent.getLocator().getColumnNumber(),
                        valEvent.getLinkedException().getMessage());
                throw new UnmarshalException(msg, valEvent.getLinkedException());
            }
        }
    }
    return elem.getValue();
}

From source file:org.openwms.core.configuration.file.ApplicationPreferenceTest.java

/**
 * Just test to validate the given XML file against the schema declaration. If the XML file is not compliant with the schema, the test
 * will fail.//from  www  . j  a  va  2s.c  om
 *
 * @throws Exception any error
 */
@Test
public void testReadPreferences() throws Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(ResourceUtils.getFile("classpath:preferences.xsd"));
    // Schema schema = schemaFactory.newSchema(new
    // URL("http://www.openwms.org/schema/preferences.xsd"));
    JAXBContext ctx = JAXBContext.newInstance("org.openwms.core.configuration.file");
    Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setSchema(schema);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override
        public boolean handleEvent(ValidationEvent event) {
            RuntimeException ex = new RuntimeException(event.getMessage(), event.getLinkedException());
            LOGGER.error(ex.getMessage());
            throw ex;
        }
    });

    Preferences prefs = Preferences.class.cast(unmarshaller
            .unmarshal(ResourceUtils.getFile("classpath:org/openwms/core/configuration/file/preferences.xml")));
    for (AbstractPreference pref : prefs.getApplications()) {
        LOGGER.info(pref.toString());
    }
    for (AbstractPreference pref : prefs.getModules()) {
        LOGGER.info(pref.toString());
    }
    for (AbstractPreference pref : prefs.getUsers()) {
        LOGGER.info(pref.toString());
    }
}

From source file:org.cleverbus.core.common.asynch.TraceHeaderProcessor.java

private ValidationEventHandler getValidationEventHandler() {
    return new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent event) {
            if (event.getSeverity() == ValidationEvent.WARNING) {
                Log.warn("Ignored {}", event, event.getLinkedException());
                return true; // handled - ignore as WARNING does not prevent unmarshalling
            } else {
                return false; // not handled - ERROR and FATAL_ERROR prevent successful unmarshalling
            }/*from   w  w  w  . j av  a 2  s . com*/
        }
    };
}

From source file:at.gv.egiz.slbinding.SLUnmarshaller.java

/**
 * @param source a StreamSource wrapping a Reader (!) for the marshalled Object
 * @return the unmarshalled Object/*w ww .ja  va2  s  .  c om*/
 * @throws XMLStreamException
 * @throws JAXBException
 */
public Object unmarshal(StreamSource source) throws XMLStreamException, JAXBException {
    Reader inputReader = source.getReader();

    /* Validate XML against XXE, XEE, and SSRF
     * 
     * This pre-validation step is required because com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library does not 
     * support all XML parser features to prevent these types of attacks  
     */
    if (inputReader instanceof InputStreamReader) {
        try {
            //create copy of input stream
            InputStreamReader isReader = (InputStreamReader) inputReader;
            String encoding = isReader.getEncoding();
            byte[] backup = IOUtils.toByteArray(isReader, encoding);

            //validate input stream
            DOMUtils.validateXMLAgainstXXEAndSSRFAttacks(new ByteArrayInputStream(backup));

            //create new inputStreamReader for reak processing
            inputReader = new InputStreamReader(new ByteArrayInputStream(backup), encoding);

        } catch (XMLStreamException e) {
            log.error("XML data validation FAILED with msg: " + e.getMessage(), e);
            throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e);

        } catch (IOException e) {
            log.error("XML data validation FAILED with msg: " + e.getMessage(), e);
            throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e);

        }

    } else {
        log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        log.error(
                "Reader is not of type InputStreamReader -> can not make a copy of the InputStream --> extended XML validation is not possible!!! ");
        log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

    }

    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     * parse XML with original functionality
     * 
     * This code implements the the original mocca XML processing by using 
     *  com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library. Currently, this library is required to get full 
     *  security-layer specific XML processing. However, this lib does not fully support XXE, XEE and SSRF
     *  prevention mechanisms (e.g.: XMLInputFactory.SUPPORT_DTD flag is not used)    
     * 
     * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     */
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();

    //disallow DTD and external entities
    inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    inputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);

    XMLEventReader eventReader = inputFactory.createXMLEventReader(inputReader);
    RedirectEventFilter redirectEventFilter = new RedirectEventFilter();
    XMLEventReader filteredReader = inputFactory.createFilteredReader(eventReader, redirectEventFilter);

    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    ReportingValidationEventHandler validationEventHandler = new ReportingValidationEventHandler();
    unmarshaller.setEventHandler(validationEventHandler);

    unmarshaller.setListener(new RedirectUnmarshallerListener(redirectEventFilter));
    unmarshaller.setSchema(slSchema);

    Object object;
    try {
        log.trace("Before unmarshal().");
        object = unmarshaller.unmarshal(filteredReader);
        log.trace("After unmarshal().");
    } catch (UnmarshalException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to unmarshal security layer message.", e);
        } else {
            log.info("Failed to unmarshal security layer message."
                    + (e.getMessage() != null ? " " + e.getMessage() : ""));
        }

        if (validationEventHandler.getErrorEvent() != null) {
            ValidationEvent errorEvent = validationEventHandler.getErrorEvent();
            if (e.getLinkedException() == null) {
                e.setLinkedException(errorEvent.getLinkedException());
            }
        }
        throw e;
    }

    return object;

}

From source file:org.dkpro.core.io.xces.XcesBasicXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {

    Resource res = nextFile();//from w ww. j  a  v a2 s .  c o  m
    initCas(aJCas, res);

    InputStream is = null;

    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReaderBasic = xmlInputFactory.createXMLEventReader(is);

        //JAXB context for XCES body with basic type
        JAXBContext contextBasic = JAXBContext.newInstance(XcesBodyBasic.class);
        Unmarshaller unmarshallerBasic = contextBasic.createUnmarshaller();

        unmarshallerBasic.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
                throw new RuntimeException(event.getMessage(), event.getLinkedException());
            }
        });

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent eBasic = null;
        while ((eBasic = xmlEventReaderBasic.peek()) != null) {
            if (isStartElement(eBasic, "body")) {
                try {
                    XcesBodyBasic parasBasic = (XcesBodyBasic) unmarshallerBasic
                            .unmarshal(xmlEventReaderBasic, XcesBodyBasic.class).getValue();
                    readPara(jb, parasBasic);
                } catch (RuntimeException ex) {
                    getLogger().warn("Input is not in basic xces format.");
                }
            } else {
                xmlEventReaderBasic.next();
            }

        }
        jb.close();

    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException e1) {
        throw new IOException(e1);
    } finally {
        closeQuietly(is);
    }

}

From source file:org.dkpro.core.io.xces.XcesXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {

    Resource res = nextFile();//from  w  ww  . ja  v  a 2 s.c om
    initCas(aJCas, res);

    InputStream is = null;

    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);

        JAXBContext context = JAXBContext.newInstance(XcesBody.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
                throw new RuntimeException(event.getMessage(), event.getLinkedException());
            }
        });

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent e = null;
        while ((e = xmlEventReader.peek()) != null) {

            if (isStartElement(e, "body")) {
                try {
                    XcesBody paras = (XcesBody) unmarshaller.unmarshal(xmlEventReader, XcesBody.class)
                            .getValue();
                    readPara(jb, paras);
                } catch (RuntimeException ex) {
                    System.out.println("Unable to parse XCES format: " + ex);
                }
            } else {
                xmlEventReader.next();
            }

        }
        jb.close();

    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException e1) {
        throw new IOException(e1);
    } finally {
        closeQuietly(is);
    }

}

From source file:org.fuin.units4j.Units4JUtils.java

/**
 * Unmarshals the given data using a given context. A <code>null</code> XML
 * data argument returns <code>null</code>.
 * /*from  ww w  .  ja va 2  s .  c o  m*/
 * @param ctx
 *            Context to use.
 * @param xmlData
 *            XML data or <code>null</code>.
 * @param adapters
 *            Adapters to associate with the unmarshaller or
 *            <code>null</code>.
 * 
 * @return Data or <code>null</code>.
 * 
 * @param <T>
 *            Type of the expected data.
 */
@SuppressWarnings("unchecked")
public static <T> T unmarshal(@NotNull final JAXBContext ctx, final String xmlData,
        final XmlAdapter<?, ?>[] adapters) {
    if (xmlData == null) {
        return null;
    }
    try {
        final Unmarshaller unmarshaller = ctx.createUnmarshaller();
        if (adapters != null) {
            for (XmlAdapter<?, ?> adapter : adapters) {
                unmarshaller.setAdapter(adapter);
            }
        }
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            @Override
            public boolean handleEvent(final ValidationEvent event) {
                if (event.getSeverity() > 0) {
                    if (event.getLinkedException() == null) {
                        throw new RuntimeException("Error unmarshalling the data: " + event.getMessage());
                    }
                    throw new RuntimeException("Error unmarshalling the data", event.getLinkedException());
                }
                return true;
            }
        });
        return (T) unmarshaller.unmarshal(new StringReader(xmlData));
    } catch (final JAXBException ex) {
        throw new RuntimeException("Error unmarshalling test data", ex);
    }
}

From source file:org.onebusaway.transit_data_federation.siri.SiriXmlSerializerV2.java

public String getXml(Siri siri) throws Exception {
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
    marshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent event) {
            _log.error(event.getMessage(), event.getLinkedException());
            throw new RuntimeException(event.getMessage(), event.getLinkedException());
        }//  w  ww .  jav a  2 s. c  om
    });

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    Writer output = new StringWriter();
    marshaller.marshal(siri, output);

    // FIXME: strip off ns6 namespaces on siri root namespace. super hack, please fix me!
    String outputAsString = output.toString();

    /*outputAsString = outputAsString.replaceAll("<ns6:", "<");
    outputAsString = outputAsString.replaceAll("</ns6:", "</");
    outputAsString = outputAsString.replaceAll("xmlns:ns6", "xmlns");
    */

    String[] searchList = { "<siriExtensionWrapper>", "</siriExtensionWrapper>",
            "<siriUpcomingServiceExtension>", "</siriUpcomingServiceExtension>", "<siriPolyLinesExtension>",
            "</siriPolyLinesExtension>" };

    String[] replacementList = { "", "", "", "", "", "" };

    outputAsString = StringUtils.replaceEach(outputAsString, searchList, replacementList);

    return outputAsString;
}