Example usage for javax.xml.bind Unmarshaller setEventHandler

List of usage examples for javax.xml.bind Unmarshaller setEventHandler

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller setEventHandler.

Prototype

public void setEventHandler(ValidationEventHandler handler) throws JAXBException;

Source Link

Document

Allow an application to register a ValidationEventHandler .

Usage

From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java

public static Definitions load(ModelerFile file, String definitionId) {
    File savedFile = file.getFile();
    Definitions definition_Load = null;/* w ww .j a v a 2s  .c o m*/
    boolean definitionExist = false;
    XMLStreamReader xsr = null;
    try {
        if (savedFile.length() != 0) {

            XMLInputFactory xif = XMLInputFactory.newFactory();
            StreamSource xml = new StreamSource(savedFile);
            xsr = xif.createXMLStreamReader(xml);
            xsr.nextTag();
            if (definitionId == null) {
                while (xsr.hasNext() && !definitionExist) {
                    if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT
                            && xsr.getLocalName().equals("definitions")
                            && xsr.getAttributeValue(null, "id") == null) {
                        definitionExist = true;
                    } else {
                        xsr.next();
                    }
                }
            } else {
                while (xsr.hasNext() && !definitionExist) {
                    if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT
                            && xsr.getLocalName().equals("definitions")
                            && definitionId.equals(xsr.getAttributeValue(null, "id"))) {
                        definitionExist = true;
                    } else {
                        xsr.next();
                    }
                }
            }

        }
        JAXBContext jobContext;
        Unmarshaller jobUnmarshaller;
        //            if (jobContext == null) {
        jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class });
        //            }
        //            if (jobUnmarshaller == null) {
        jobUnmarshaller = jobContext.createUnmarshaller();
        jobUnmarshaller.setEventHandler(new ValidateJAXB());
        //            }
        if (definitionExist) {
            definition_Load = jobUnmarshaller.unmarshal(xsr, Definitions.class).getValue();//new StreamSource(savedFile)
        }
        if (xsr != null) {
            xsr.close();
        }

    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    } catch (JAXBException ex) {
        //            io.getOut().println("Exception: " + ex.toString());
        ex.printStackTrace();
        System.out.println("Document XML Not Exist");
    }
    return definition_Load;
}

From source file:org.openestate.io.casa_it.CasaItUtils.java

/**
 * Creates a {@link Unmarshaller} to read JAXB objects from XML.
 *
 * @return/*from www.j ava 2 s . c om*/
 * created unmarshaller
 *
 * @throws JAXBException
 * if a problem with JAXB occured
 */
public static Unmarshaller createUnmarshaller() throws JAXBException {
    Unmarshaller m = getContext().createUnmarshaller();
    m.setEventHandler(new XmlValidationHandler());
    return m;
}

From source file:org.opennms.core.test.xml.XmlTest.java

@Test
public void validateJaxbXmlAgainstSchema() throws Exception {
    final String schemaFile = getSchemaFile();
    if (schemaFile == null) {
        LOG.warn("Skipping validation.");
        return;/*from  ww w .  j  a  va2  s .c  om*/
    }
    LOG.debug("Validating against XSD: {}", schemaFile);
    javax.xml.bind.Unmarshaller unmarshaller = JaxbUtils.getUnmarshallerFor(getSampleClass(), null, true);
    final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final Schema schema = factory.newSchema(new StreamSource(schemaFile));
    unmarshaller.setSchema(schema);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override
        public boolean handleEvent(final ValidationEvent event) {
            LOG.warn("Received validation event: {}", event, event.getLinkedException());
            return false;
        }
    });
    try {
        final InputSource inputSource = new InputSource(getSampleXmlInputStream());
        final XMLFilter filter = JaxbUtils.getXMLFilterForClass(getSampleClass());
        final SAXSource source = new SAXSource(filter, inputSource);
        @SuppressWarnings("unchecked")
        T obj = (T) unmarshaller.unmarshal(source);
        assertNotNull(obj);
    } finally {
        unmarshaller.setSchema(null);
    }
}

From source file:org.opennms.core.xml.JaxbUtils.java

public static <T> T unmarshal(final Class<T> clazz, final InputSource inputSource,
        final JAXBContext jaxbContext, final boolean validate) {
    final Unmarshaller um = getUnmarshallerFor(clazz, jaxbContext, validate);

    LOG.trace("unmarshalling class {} from input source {} with unmarshaller {}", clazz.getSimpleName(),
            inputSource, um);/*from   w  w  w. ja v a 2s. c om*/
    try {
        final XMLFilter filter = getXMLFilterForClass(clazz);
        final SAXSource source = new SAXSource(filter, inputSource);

        um.setEventHandler(new LoggingValidationEventHandler());

        final JAXBElement<T> element = um.unmarshal(source, clazz);
        return element.getValue();
    } catch (final SAXException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating an XML reader object", e);
    } catch (final JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("unmarshalling an object (" + clazz.getSimpleName() + ")", e);
    }
}

From source file:org.opennms.sms.monitor.internal.config.SequenceConfigFactory.java

/**
 * <p>getUnmarshaller</p>/*from ww w .j av a2s  .com*/
 *
 * @return a {@link javax.xml.bind.Unmarshaller} object.
 * @throws javax.xml.bind.JAXBException if any.
 */
protected Unmarshaller getUnmarshaller() throws JAXBException {
    synchronized (m_context) {
        Unmarshaller u = m_context.createUnmarshaller();
        u.setSchema(null);
        u.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
        return u;
    }
}

From source file:org.rhq.core.clientapi.agent.metadata.test.ConfigurationMetadataParser2Test.java

@BeforeSuite
public void loadPluginDescriptor() throws Exception {
    try {/*from  w  ww  .  j a  va  2 s  .c om*/
        URL descriptorUrl = this.getClass().getClassLoader().getResource(DESCRIPTOR_FILENAME);
        LOG.info("Loading plugin descriptor at: " + descriptorUrl);

        JAXBContext jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        ValidationEventCollector vec = new ValidationEventCollector();
        unmarshaller.setEventHandler(vec);
        pluginDescriptor = (PluginDescriptor) unmarshaller.unmarshal(descriptorUrl.openStream());
    } catch (Throwable t) {
        // Catch RuntimeExceptions and Errors and dump their stack trace, because Surefire will completely swallow them
        // and throw a cryptic NPE (see http://jira.codehaus.org/browse/SUREFIRE-157)!
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}

From source file:org.rhq.core.clientapi.descriptor.AgentPluginDescriptorUtil.java

/**
 * Parses a descriptor from InputStream without a validator.
 * @param is input to check/*from   w w w .ja  va 2 s.  co  m*/
 * @return parsed PluginDescriptor
 * @throws PluginContainerException if validation fails
 */
public static PluginDescriptor parsePluginDescriptor(InputStream is,
        ValidationEventCollector validationEventCollector) throws PluginContainerException {
    JAXBContext jaxbContext;
    try {
        jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN);
    } catch (Exception e) {
        throw new PluginContainerException("Failed to create JAXB Context.", new WrappedRemotingException(e));
    }

    Unmarshaller unmarshaller;
    try {
        unmarshaller = jaxbContext.createUnmarshaller();
        // Enable schema validation
        URL pluginSchemaURL = AgentPluginDescriptorUtil.class.getClassLoader().getResource(PLUGIN_SCHEMA_PATH);
        Schema pluginSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(pluginSchemaURL);
        unmarshaller.setSchema(pluginSchema);
        unmarshaller.setEventHandler(validationEventCollector);

        PluginDescriptor pluginDescriptor = (PluginDescriptor) unmarshaller.unmarshal(is);
        return pluginDescriptor;
    } catch (JAXBException e) {
        throw new PluginContainerException(e);
    } catch (SAXException e) {
        throw new PluginContainerException(e);
    }
}

From source file:org.rhq.enterprise.server.plugins.url.XmlIndexParser.java

@SuppressWarnings("unchecked")
protected Map<String, RemotePackageInfo> jaxbParse(InputStream indexStream, URL indexUrl, String rootUrlString)
        throws Exception {

    JAXBContext jaxbContext = JAXBContext.newInstance(XmlSchemas.PKG_CONTENTSOURCE_PACKAGEDETAILS);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    // Enable schema validation
    URL pluginSchemaURL = XmlIndexParser.class.getClassLoader().getResource(PLUGIN_SCHEMA_PATH);
    Schema pluginSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(pluginSchemaURL);
    unmarshaller.setSchema(pluginSchema);

    ValidationEventCollector vec = new ValidationEventCollector();
    unmarshaller.setEventHandler(vec);

    BufferedReader reader = new BufferedReader(new InputStreamReader(indexStream));
    JAXBElement<PackageType> packagesXml = (JAXBElement<PackageType>) unmarshaller.unmarshal(reader);

    for (ValidationEvent event : vec.getEvents()) {
        log.debug("URL content source index [" + indexUrl + "] message {Severity: " + event.getSeverity()
                + ", Message: " + event.getMessage() + ", Exception: " + event.getLinkedException() + "}");
    }// ww  w  .j av a2s  . c o  m

    Map<String, RemotePackageInfo> fileList = new HashMap<String, RemotePackageInfo>();

    List<PackageDetailsType> allPackages = packagesXml.getValue().getPackage();
    for (PackageDetailsType pkg : allPackages) {
        URL locationUrl = new URL(rootUrlString + pkg.getLocation());
        ContentProviderPackageDetails details = translateXmlToDomain(pkg);
        FullRemotePackageInfo rpi = new FullRemotePackageInfo(locationUrl, details);
        fileList.put(stripLeadingSlash(rpi.getLocation()), rpi);
    }

    return fileList;
}

From source file:org.rhq.enterprise.server.xmlschema.ServerPluginDescriptorUtil.java

/**
 * This will return a JAXB unmarshaller that will enable the caller to parse a server plugin
 * descriptor. The returned unmarshaller will have a {@link ValidationEventCollector}
 * installed as an {@link Unmarshaller#getEventHandler() event handler} which can be used
 * to obtain error messages if the unmarshaller fails to parse an XML document.
 * /*from  ww w. j av a  2s.c o m*/
 * @return a JAXB unmarshaller enabling the caller to parse server plugin descriptors
 * 
 * @throws Exception if an unmarshaller could not be created
 */
public static Unmarshaller getServerPluginDescriptorUnmarshaller() throws Exception {

    // create the JAXB context with all the generated plugin packages in it
    JAXBContext jaxbContext;
    try {
        jaxbContext = JAXBContext.newInstance(PLUGIN_CONTEXT_PATH);
    } catch (Exception e) {
        throw new Exception("Failed to create JAXB Context.", e);
    }

    // create the unmarshaller that can be used to parse XML documents containing server plugin descriptors
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    // enable schema validation to ensure the XML documents parsed by the unmarshaller are valid descriptors
    ClassLoader cl = ServerPluginDescriptorUtil.class.getClassLoader();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    StreamSource[] schemaSources = new StreamSource[PLUGIN_SCHEMA_PACKAGES.size()];
    int i = 0;
    for (String schemaPath : PLUGIN_SCHEMA_PACKAGES.keySet()) {
        URL schemaURL = cl.getResource(schemaPath);
        schemaSources[i++] = new StreamSource(schemaURL.toExternalForm());
    }

    Schema pluginSchema = schemaFactory.newSchema(schemaSources);
    unmarshaller.setSchema(pluginSchema);

    ValidationEventCollector vec = new ValidationEventCollector();
    unmarshaller.setEventHandler(vec);

    return unmarshaller;
}

From source file:org.rhq.modules.integrationTests.jbossas7plugin.AbstractIntegrationTest.java

void loadPluginDescriptor() throws Exception {
    try {// w  ww  .j  a  v a 2  s . co  m
        ClassLoader classLoader = this.getClass().getClassLoader();
        URL descriptorUrl = classLoader.getResource("META-INF" + File.separator + DESCRIPTOR_FILENAME);
        log.info("Loading plugin descriptor at: " + descriptorUrl);

        JAXBContext jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        ValidationEventCollector vec = new ValidationEventCollector();
        unmarshaller.setEventHandler(vec);
        pluginDescriptor = (PluginDescriptor) unmarshaller.unmarshal(descriptorUrl.openStream());
    } catch (Throwable t) {
        // Catch RuntimeExceptions and Errors and dump their stack trace, because Surefire will completely swallow them
        // and throw a cryptic NPE (see http://jira.codehaus.org/browse/SUREFIRE-157)!
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}