Example usage for javax.xml.bind Unmarshaller setSchema

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

Introduction

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

Prototype

public void setSchema(javax.xml.validation.Schema schema);

Source Link

Document

Specify the JAXP 1.3 javax.xml.validation.Schema Schema object that should be used to validate subsequent unmarshal operations against.

Usage

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   www.  ja v a2  s. c  o m*/
    }
    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

/**
 * Get a JAXB unmarshaller for the given object.  If no JAXBContext is provided,
 * JAXBUtils will create and cache a context for the given object.
 * @param obj The object type to be unmarshaled.
 * @param jaxbContext An optional JAXB context to create the unmarshaller from.
 * @param validate TODO/*from www .  j  av  a 2s.  c  om*/
 * @return an Unmarshaller
 */
public static Unmarshaller getUnmarshallerFor(final Object obj, final JAXBContext jaxbContext,
        boolean validate) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());

    Unmarshaller unmarshaller = null;

    Map<Class<?>, Unmarshaller> unmarshallers = m_unMarshallers.get();
    if (jaxbContext == null) {
        if (unmarshallers == null) {
            unmarshallers = new WeakHashMap<Class<?>, Unmarshaller>();
            m_unMarshallers.set(unmarshallers);
        }
        if (unmarshallers.containsKey(clazz)) {
            LOG.trace("found unmarshaller for {}", clazz);
            unmarshaller = unmarshallers.get(clazz);
        }
    }

    if (unmarshaller == null) {
        try {
            final JAXBContext context;
            if (jaxbContext == null) {
                context = getContextFor(clazz);
            } else {
                context = jaxbContext;
            }
            unmarshaller = context.createUnmarshaller();
        } catch (final JAXBException e) {
            throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
        }
    }

    LOG.trace("created unmarshaller for {}", clazz);

    if (validate) {
        final Schema schema = getValidatorFor(clazz);
        if (schema == null) {
            LOG.trace("Validation is enabled, but no XSD found for class {}", clazz.getSimpleName());
        }
        unmarshaller.setSchema(schema);
    }
    if (jaxbContext == null)
        unmarshallers.put(clazz, unmarshaller);

    return unmarshaller;
}

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

/**
 * <p>getUnmarshaller</p>/* w  w  w .  ja  va 2s .c  om*/
 *
 * @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.opentravel.schemacompiler.repository.RepositoryFileManager.java

/**
 * Loads the JAXB representation of the XML content from the specified file location.
 * /*from  w  ww . j a  v  a2 s .  c  o m*/
 * @param file
 *            the repository file to load
 * @param findings
 *            the validation findings encountered during the load process
 * @return ProjectType
 * @throws RepositoryException
 *             thrown if the file cannot be loaded
 */
protected Object loadFile(File file) throws RepositoryException {
    try {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(repositoryValidationSchema);

        JAXBElement<?> documentElement = (JAXBElement<?>) unmarshaller.unmarshal(file);
        return documentElement.getValue();

    } catch (JAXBException e) {
        throw new RepositoryException("Unrecognized file format.", e);

    } catch (Throwable t) {
        throw new RepositoryException("Unknown error while repository file.", t);
    }
}

From source file:org.opentravel.schemacompiler.security.impl.AbstractAuthenticationProvider.java

/**
 * Refreshes the memory-resident user registry if necessary.  If the refresh was
 * peformed, this method returns true; false if the memory-resident cache was already
 * up-to-date./*ww  w .j  av  a 2s  .c  o  m*/
 * 
 * @return boolean
 */
@SuppressWarnings("unchecked")
protected synchronized boolean refreshRegistry() {
    RepositoryFileManager fileManager = repositoryManager.getFileManager();
    File registryFile = new File(fileManager.getRepositoryLocation(), REPOSITORY_USERS_FILE);
    boolean refreshPerformed = false;

    if (userRegistry == null) {
        userRegistry = new HashMap<>();
    }

    if (registryFile.exists()) {
        long lastModified = registryFile.lastModified();

        if (lastModified > userFileLastModified) {
            try {
                Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                unmarshaller.setSchema(validationSchema);

                JAXBElement<RepositoryUsers> documentElement = (JAXBElement<RepositoryUsers>) unmarshaller
                        .unmarshal(registryFile);
                RepositoryUsers repoUsers = documentElement.getValue();

                userRegistry.clear();

                for (UserInfo userInfo : repoUsers.getUser()) {
                    userRegistry.put(userInfo.getUserId(), userInfo);
                }
                userFileLastModified = lastModified;
                refreshPerformed = true;

            } catch (JAXBException e) {
                log.error("Repository user file is unreadable.", e);
            }
        }
    }
    return refreshPerformed;
}

From source file:org.perfclipse.core.scenario.ScenarioManager.java

/**
 * Creates {@link ScenarioModel} object representation of the scenario
 * specified in XML file at scenarioURL parameter.
 * @param scenarioURL - URL to scenario XML definition
 * @return {@link ScenarioModel} of given XML definition
 * @throws ScenarioException//w w  w .  jav a  2s  . c  om
 */
public ScenarioModel createModel(URL scenarioURL) throws ScenarioException {

    org.perfcake.model.Scenario model;

    if (scenarioURL == null) {
        log.error("URL to scenario is null");
        throw new IllegalArgumentException("URL to scenario is null.");
    }

    try {

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = SchemaScanner.getSchema();
        Schema schema = schemaFactory.newSchema(schemaUrl);

        JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        model = (org.perfcake.model.Scenario) unmarshaller.unmarshal(scenarioURL);
        return new ScenarioModel(model);
    } catch (JAXBException e) {
        throw new ScenarioException(e);
    } catch (IOException e) {
        throw new ScenarioException(e);
    } catch (SAXException e) {
        throw new ScenarioException(e);
    }

}

From source file:org.plasma.common.bind.ValidatingUnmarshaler.java

private Unmarshaller createUnmarshaler(URL url, JAXBContext context) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    // adds a custom object factory
    // u.setProperty("com.sun.xml.bind.ObjectFactory",new
    // ObjectFactoryEx());
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    Schema schemaGrammar = schemaFactory.newSchema(url);
    u.setSchema(schemaGrammar);

    return u;/*from   w  ww  .j a va 2  s. c  om*/
}

From source file:org.plasma.common.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and sream. Loads only
 * the given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * /* w ww.ja  v  a  2s .c o m*/
 * @param stream
 *            the Schema stream
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(InputStream[] streams, JAXBContext context, Handler handler,
        Resolver resolver) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    StreamSource[] sources = new StreamSource[streams.length];
    for (int i = 0; i < streams.length; i++) {
        sources[i] = new StreamSource(streams[i]);
        //FIXME: will not resolve relative URI's (included schemas) without this
        //sources[i].setSystemId(systemId)
    }
    Schema schemaGrammar = schemaFactory.newSchema(sources);
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

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

/**
 * Parses a descriptor from InputStream without a validator.
 * @param is input to check/*from  ww w . j a  v  a  2  s  .  c  om*/
 * @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);//from  w  w w  .  ja v  a  2  s.com

    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() + "}");
    }

    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;
}