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.rhq.modules.plugins.jbossas7.AbstractConfigurationHandlingTest.java

void loadPluginDescriptor() throws Exception {
    try {//from   ww w  .  j  a v  a 2  s  .com
        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.modules.plugins.jbossas7.itest.nonpc.AbstractIntegrationTest.java

void loadPluginDescriptor() throws Exception {
    try {/*  w  ww  .j  av a2  s .  com*/
        //ClassLoader classLoader = this.getClass().getClassLoader();
        //URL descriptorUrl = classLoader.getResource("META-INF" + File.separator + DESCRIPTOR_FILENAME);
        File descriptorFile = new File("src/main/resources/META-INF/" + DESCRIPTOR_FILENAME);
        URL descriptorUrl = descriptorFile.toURI().toURL();
        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.modules.plugins.wildfly10.AbstractConfigurationHandlingTest.java

void loadPluginDescriptor() throws Exception {
    try {// w w w .  jav  a2  s  .c o m
        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.plugins.perftest.ScenarioManager.java

/**
 * Determines what scenario to load and loads the JAXB objects representing the scenario.
 *///from  w w w.jav a 2 s. com
private void loadScenario() {
    // Determine scenario
    String scenarioName = System.getProperty(SCENARIO_PROPERTY);

    if (scenarioName == null) {
        log.info("Cannot find scenario name. Make sure the system property " + SCENARIO_PROPERTY + " is set.");
        return;
    }

    log.info("Loading Performance Testing Scenario [" + scenarioName + "]...");

    ClassLoader loader = this.getClass().getClassLoader();
    URL scenarioUrl = loader.getResource(scenarioName + ".xml");

    // Load the JAXB stuff
    Class objectFactoryClass = null;
    try {
        objectFactoryClass = loader.loadClass("org.rhq.plugins.perftest.scenario.ObjectFactory");
    } catch (ClassNotFoundException e) {
        log.error("Error finding class ObjectFactory", e);
        return;
    }

    JAXBContext jaxbContext;
    try {
        jaxbContext = JAXBContext.newInstance(objectFactoryClass);
    } catch (JAXBException e) {
        log.error("Could not instantiate JAXB context", e);
        return;
    }

    // Load the scenario
    try {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        ValidationEventCollector vec = new ValidationEventCollector();
        unmarshaller.setEventHandler(vec);
        this.scenario = (Scenario) unmarshaller.unmarshal(scenarioUrl);
    } catch (JAXBException e) {
        log.error("Scenario [" + scenarioName + "] could not be loaded from [" + scenarioUrl + "].", e);
        return;
    }
}

From source file:org.silverpeas.core.importexport.control.ImportExport.java

/**
 * Mthode retournant l'arbre des objets mapps sur le fichier xml pass en paramtre.
 * @param xmlFileName le fichier xml interprt par JAXB
 * @return Un objet SilverPeasExchangeType contenant le mapping d'un fichier XML
 * @throws ImportExportException/* w w w  .  j a va 2  s  . c o m*/
 */
private SilverPeasExchangeType loadSilverpeasExchange(String xmlFileName) throws ImportExportException {
    try {
        File xmlInputSource = new File(xmlFileName);
        String xsdSystemId = settings.getString("xsdDefaultSystemId");

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new URL(xsdSystemId));

        // Unmarshall the import model
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ImportExportErrorHandler());
        SilverPeasExchangeType silverpeasExchange = (SilverPeasExchangeType) unmarshaller
                .unmarshal(xmlInputSource);

        return silverpeasExchange;

    } catch (JAXBException me) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_UNMARSHALLING_FAILED",
                "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me);
    } catch (MalformedURLException ue) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_UNMARSHALLING_FAILED",
                "XML Filename " + xmlFileName + ": " + ue.getLocalizedMessage(), ue);
    } catch (SAXException ve) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + ve.getLocalizedMessage(), ve);
    }
}

From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java

/**
 * Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
 * Gets called after creation of JAXB {@code Marshaller}, and after the respective properties have been set.
 * <p>The default implementation sets the {@link #setUnmarshallerProperties(Map) defined properties}, the {@link
 * #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[])
 * schemas}, {@link #setUnmarshallerListener(javax.xml.bind.Unmarshaller.Listener) listener}, and
 * {@link #setAdapters(XmlAdapter[]) adapters}.
 *//*ww w . j  a  va2  s. co  m*/
protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
    if (this.unmarshallerProperties != null) {
        for (String name : this.unmarshallerProperties.keySet()) {
            unmarshaller.setProperty(name, this.unmarshallerProperties.get(name));
        }
    }
    if (this.unmarshallerListener != null) {
        unmarshaller.setListener(this.unmarshallerListener);
    }
    if (this.validationEventHandler != null) {
        unmarshaller.setEventHandler(this.validationEventHandler);
    }
    if (this.adapters != null) {
        for (XmlAdapter<?, ?> adapter : this.adapters) {
            unmarshaller.setAdapter(adapter);
        }
    }
    if (this.schema != null) {
        unmarshaller.setSchema(this.schema);
    }
}

From source file:org.squidy.designer.model.ModelViewHandler.java

/**
 * Parses a given input stream (should contain model and diagram code as xml
 * structure) and returns it as an object structure.
 * /*from  w  w w. j  a v  a  2 s .  c  o m*/
 * @param inputStream
 *            The input stream should contain model and diagram structure.
 * @return The parsed XMI document containing model and diagram in object
 *         representation.
 * @throws SquidyException
 */
public Data load(InputStream inputStream) throws SquidyException {
    try {
        Unmarshaller unmarshaller = getContext().createUnmarshaller();
        unmarshaller.setEventHandler(new ValidationEventHandler() {

            /* (non-Javadoc)
             * @see javax.xml.bind.ValidationEventHandler#handleEvent(javax.xml.bind.ValidationEvent)
             */
            public boolean handleEvent(ValidationEvent e) {
                ValidationEventLocator locator = e.getLocator();
                if (LOG.isErrorEnabled()) {
                    LOG.error("Error while reading input stream: \"" + e.getMessage() + "\" [line="
                            + locator.getLineNumber() + ", column=" + locator.getColumnNumber() + "]");
                }
                return true;
            }
        });

        return (Data) unmarshaller.unmarshal(inputStream);
    } catch (JAXBException e) {
        throw new SquidyException("Could not unmarshal input stream.", e);
    }
}

From source file:org.squidy.manager.parser.ModelHandler.java

/**
 * Parses a given input stream (should contain model and diagram code as xml
 * structure) and returns it as an object structure.
 * /*  www .j a  v  a 2  s  . c o m*/
 * @param inputStream
 *            The input stream should contain model and diagram structure.
 * @return The parsed XMI document containing model and diagram in object
 *         representation.
 */
@SuppressWarnings("restriction")
public Data load(InputStream inputStream) {
    try {
        Unmarshaller unmarshaller = getContext().createUnmarshaller();
        unmarshaller.setEventHandler(new ValidationEventHandler() {

            /*
             * (non-Javadoc)
             * 
             * @see
             * javax.xml.bind.ValidationEventHandler#handleEvent(javax.xml
             * .bind.ValidationEvent)
             */
            public boolean handleEvent(ValidationEvent e) {
                // Ignore this as workspace-shape is located in not
                // referenced squidy-designer module
                if (e.getMessage().startsWith("unexpected element (uri:\"\", local:\"workspace-shape\")")) {
                    return true;
                }

                ValidationEventLocator locator = e.getLocator();
                if (LOG.isErrorEnabled()) {
                    LOG.error("Error while reading input stream: \"" + e.getMessage() + "\" [line="
                            + locator.getLineNumber() + ", column=" + locator.getColumnNumber() + "]"
                            + e.getLinkedException());
                }
                return true;
            }
        });

        return (Data) unmarshaller.unmarshal(inputStream);
    } catch (JAXBException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }
}

From source file:org.wso2.carbon.device.mgt.etc.config.devicetype.DeviceTypeConfigurationManager.java

public synchronized void initConfig() throws DeviceManagementException {
    try {/*from   w  w  w  .j a  v  a 2 s.  co m*/
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(deviceMgtConfigXSDPath));

        File iotDeviceMgtConfig = new File(deviceMgtConfigXMLPath);
        Document doc = IotDeviceManagementUtil.convertToDocument(iotDeviceMgtConfig);
        JAXBContext iotDeviceMgmtContext = JAXBContext.newInstance(DeviceTypeConfigManager.class);
        Unmarshaller unmarshaller = iotDeviceMgmtContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new IotConfigValidationEventHandler());
        this.currentDeviceTypeConfig = (DeviceTypeConfigManager) unmarshaller.unmarshal(doc);

        List<DeviceTypeConfig> iotDeviceTypeConfigList = currentDeviceTypeConfig.getDeviceTypeConfigs();
        for (DeviceTypeConfig iotDeviceTypeConfig : iotDeviceTypeConfigList) {
            String applicationName = iotDeviceTypeConfig.getApiApplicationName();

            if (applicationName == null || applicationName.isEmpty()) {
                iotDeviceTypeConfig.setApiApplicationName(iotDeviceTypeConfig.getType());
            }
            deviceTypeConfigMap.put(iotDeviceTypeConfig.getType(), iotDeviceTypeConfig);
        }
        ApisAppClient.getInstance().setBase64EncodedConsumerKeyAndSecret(iotDeviceTypeConfigList);
    } catch (Exception e) {
        String error = "Error occurred while initializing device configurations";
        log.error(error, e);
    }
}

From source file:org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager.java

public void initConfig() throws DeviceControllerException {
    try {//from w w w.ja v a 2  s. co  m
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(XSDCONFIGS_FILE_LOCATION));

        File deviceCloudMgtConfig = new File(XMLCONFIGS_FILE_LOCATION);
        Document doc = IotDeviceManagementUtil.convertToDocument(deviceCloudMgtConfig);
        JAXBContext deviceCloudContext = JAXBContext.newInstance(DeviceCloudConfig.class);
        Unmarshaller unmarshaller = deviceCloudContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new IotConfigValidationEventHandler());
        this.currentDeviceCloudConfig = (DeviceCloudConfig) unmarshaller.unmarshal(doc);
    } catch (Exception e) {
        String error = "Error occurred while initializing DeviceController configurations";
        log.error(error);
        throw new DeviceControllerException(error, e);
    }
}