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:nl.ordina.bag.etl.xml.XMLMessageBuilder.java

@SuppressWarnings("unchecked")
public <U> U handle(Schema schema, XMLStreamReader r, Class<U> clazz) throws JAXBException {
    if (r == null)
        return null;
    Unmarshaller unmarshaller = context.createUnmarshaller();
    if (schema != null)
        unmarshaller.setSchema(schema);
    Object o = clazz == null ? unmarshaller.unmarshal(r) : unmarshaller.unmarshal(r, clazz);
    if (o instanceof JAXBElement<?>)
        return ((JAXBElement<U>) o).getValue();
    else/*from  ww w . ja  v  a2 s . c o  m*/
        return (U) o;
}

From source file:nl.ordina.bag.etl.xml.XMLMessageBuilder.java

@SuppressWarnings("unchecked")
public T handle(Schema schema, Node n) throws JAXBException {
    if (n == null)
        return null;
    Unmarshaller unmarshaller = context.createUnmarshaller();
    if (schema != null)
        unmarshaller.setSchema(schema);
    Object o = unmarshaller.unmarshal(n);
    if (o instanceof JAXBElement<?>)
        return ((JAXBElement<T>) o).getValue();
    else/*  ww w .  j  a  v a2s  . c om*/
        return (T) o;
}

From source file:no.digipost.api.client.representations.XsdValidationTest.java

public <T> T marshallValidateAndUnmarshall(T element, boolean log) {
    InputStream in = null;/*from   w w w . j  av  a 2  s  .co m*/
    try (ByteArrayOutputStream resultXml = new ByteArrayOutputStream()) {
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setSchema(schema);
        marshaller.setProperty("jaxb.formatted.output", true);
        marshaller.marshal(element, new StreamResult(resultXml));
        resultXml.flush();
        byte[] xml = resultXml.toByteArray();
        if (log) {
            LOG.info("Marshalled XML:\n{}", new String(xml));
        }
        in = new ByteArrayInputStream(xml);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        @SuppressWarnings("unchecked")
        T unmarshalled = (T) unmarshaller.unmarshal(in);
        return unmarshalled;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        closeQuietly(in);
    }
}

From source file:org.alfresco.repo.audit.model.AuditModelRegistryImpl.java

/**
 * Unmarshalls the Audit model from a stream.
 *///from w w w.  ja  v  a 2 s .c  o  m
private static Audit unmarshallModel(InputStream is, final String source) {
    final Schema schema;
    final JAXBContext jaxbCtx;
    final Unmarshaller jaxbUnmarshaller;
    try {
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = sf.newSchema(ResourceUtils.getURL(AUDIT_SCHEMA_LOCATION));
        jaxbCtx = JAXBContext.newInstance("org.alfresco.repo.audit.model._3");
        jaxbUnmarshaller = jaxbCtx.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        jaxbUnmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent ve) {
                if (ve.getSeverity() == ValidationEvent.FATAL_ERROR
                        || ve.getSeverity() == ValidationEvent.ERROR) {
                    ValidationEventLocator locator = ve.getLocator();
                    logger.error("Invalid Audit XML: \n" + "   Source:   " + source + "\n"
                            + "   Location: Line " + locator.getLineNumber() + " column "
                            + locator.getColumnNumber() + "\n" + "   Error:    " + ve.getMessage());
                }
                return false;
            }
        });
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Failed to load Alfresco Audit Schema from " + AUDIT_SCHEMA_LOCATION,
                e);
    }
    try {
        // Unmarshall with validation
        @SuppressWarnings("unchecked")
        JAXBElement<Audit> auditElement = (JAXBElement<Audit>) jaxbUnmarshaller.unmarshal(is);

        Audit audit = auditElement.getValue();
        // Done
        return audit;
    } catch (Throwable e) {
        // Dig out a SAXParseException, if there is one
        Throwable saxError = ExceptionStackUtil.getCause(e, SAXParseException.class);
        if (saxError != null) {
            e = saxError;
        }
        throw new AuditModelException("Failed to read Audit model XML: \n" + "   Source: " + source + "\n"
                + "   Error:  " + e.getMessage());
    } finally {
        try {
            is.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.apache.bval.jsr.xml.ValidationMappingParser.java

/** @param in XML stream to parse using the validation-mapping-1.0.xsd */
private ConstraintMappingsType parseXmlMappings(final InputStream in) {
    ConstraintMappingsType mappings;//from  w  ww . j  av a  2s  .  co  m
    try {
        final JAXBContext jc = JAXBContext.newInstance(ConstraintMappingsType.class);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(getSchema());
        final StreamSource stream = new StreamSource(in);
        final JAXBElement<ConstraintMappingsType> root = unmarshaller.unmarshal(stream,
                ConstraintMappingsType.class);
        mappings = root.getValue();
    } catch (final JAXBException e) {
        throw new ValidationException("Failed to parse XML deployment descriptor file.", e);
    } finally {
        IOs.closeQuietly(in);
        try {
            in.reset(); // can be read several times + we ensured it was re-readable in addMapping()
        } catch (final IOException e) {
            // no-op
        }
    }
    return mappings;
}

From source file:org.apache.bval.jsr.xml.ValidationParser.java

@Privileged
private static ValidationConfigType parseXmlConfig(final String validationXmlFile) {
    InputStream inputStream = null;
    try {//from  w w w. java 2 s. c  o m
        inputStream = getInputStream(getValidationXmlFile(validationXmlFile));
        if (inputStream == null) {
            log.log(Level.FINEST, String.format("No %s found. Using annotation based configuration only.",
                    validationXmlFile));
            return null;
        }

        log.log(Level.FINEST, String.format("%s found.", validationXmlFile));

        Schema schema = getSchema();
        JAXBContext jc = JAXBContext.newInstance(ValidationConfigType.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        StreamSource stream = new StreamSource(inputStream);
        JAXBElement<ValidationConfigType> root = unmarshaller.unmarshal(stream, ValidationConfigType.class);
        return root.getValue();
    } catch (JAXBException e) {
        throw new ValidationException("Unable to parse " + validationXmlFile, e);
    } catch (IOException e) {
        throw new ValidationException("Unable to parse " + validationXmlFile, e);
    } finally {
        IOs.closeQuietly(inputStream);
    }
}

From source file:org.apache.falcon.extensions.util.ExtensionProcessBuilderUtils.java

private static org.apache.falcon.entity.v0.process.Process bindAttributesInTemplate(
        final String processTemplate, final Properties extensionProperties, final String extensionName,
        final String wfPath, final String wfLibPath) throws FalconException {
    if (StringUtils.isBlank(processTemplate) || extensionProperties == null) {
        throw new FalconException("Process template or properties cannot be null");
    }/*from   w  w w  . j a v a 2 s.c o  m*/

    org.apache.falcon.entity.v0.process.Process process;
    try {
        Unmarshaller unmarshaller = EntityType.PROCESS.getUnmarshaller();
        // Validation can be skipped for unmarshalling as we want to bind template with the properties.
        // Vaildation is handled as part of marshalling
        unmarshaller.setSchema(null);
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent validationEvent) {
                return true;
            }
        });
        process = (org.apache.falcon.entity.v0.process.Process) unmarshaller
                .unmarshal(new StringReader(processTemplate));
    } catch (Exception e) {
        throw new FalconException(e);
    }

    /* For optional properties user might directly set them in the process xml and might not set it in properties
       file. Before doing the submission validation is done to confirm process xml doesn't have
       EXTENSION_VAR_PATTERN
    */

    String processName = extensionProperties.getProperty(ExtensionProperties.JOB_NAME.getName());
    if (StringUtils.isNotEmpty(processName)) {
        process.setName(processName);
    }

    // DR process template has only one cluster
    bindClusterProperties(process.getClusters().getClusters().get(0), extensionProperties);

    // bind scheduling properties
    String processFrequency = extensionProperties.getProperty(ExtensionProperties.FREQUENCY.getName());
    if (StringUtils.isNotEmpty(processFrequency)) {
        process.setFrequency(Frequency.fromString(processFrequency));
    }

    String zone = extensionProperties.getProperty(ExtensionProperties.TIMEZONE.getName());
    if (StringUtils.isNotBlank(zone)) {
        process.setTimezone(TimeZone.getTimeZone(zone));
    } else {
        process.setTimezone(TimeZone.getTimeZone("UTC"));
    }

    bindWorkflowProperties(process.getWorkflow(), extensionName, wfPath, wfLibPath);
    bindRetryProperties(process.getRetry(), extensionProperties);
    bindNotificationProperties(process.getNotification(), extensionProperties);
    bindACLProperties(process.getACL(), extensionProperties);
    bindTagsProperties(process, extensionProperties);
    bindCustomProperties(process.getProperties(), extensionProperties);

    return process;
}

From source file:org.apache.falcon.recipe.util.RecipeProcessBuilderUtils.java

private static org.apache.falcon.entity.v0.process.Process bindAttributesInTemplate(final String templateFile,
        final Properties recipeProperties) throws Exception {
    if (templateFile == null || recipeProperties == null) {
        throw new IllegalArgumentException("Invalid arguments passed");
    }/* ww  w. j a  v a  2 s.c o  m*/

    Unmarshaller unmarshaller = EntityType.PROCESS.getUnmarshaller();
    // Validation can be skipped for unmarshalling as we want to bind tempalte with the properties. Vaildation is
    // hanles as part of marshalling
    unmarshaller.setSchema(null);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent validationEvent) {
            return true;
        }
    });

    URL processResourceUrl = new File(templateFile).toURI().toURL();
    org.apache.falcon.entity.v0.process.Process process = (org.apache.falcon.entity.v0.process.Process) unmarshaller
            .unmarshal(processResourceUrl);

    /* For optional properties user might directly set them in the process xml and might not set it in properties
       file. Before doing the submission validation is done to confirm process xml doesn't have RECIPE_VAR_PATTERN
    */

    String processName = recipeProperties.getProperty(RecipeToolOptions.RECIPE_NAME.getName());
    if (StringUtils.isNotEmpty(processName)) {
        process.setName(processName);
    }

    // DR process template has only one cluster
    bindClusterProperties(process.getClusters().getClusters().get(0), recipeProperties);

    // bind scheduling properties
    String processFrequency = recipeProperties.getProperty(RecipeToolOptions.PROCESS_FREQUENCY.getName());
    if (StringUtils.isNotEmpty(processFrequency)) {
        process.setFrequency(Frequency.fromString(processFrequency));
    }

    bindWorkflowProperties(process.getWorkflow(), recipeProperties);
    bindRetryProperties(process.getRetry(), recipeProperties);
    bindNotificationProperties(process.getNotification(), recipeProperties);
    bindACLProperties(process.getACL(), recipeProperties);
    bindTagsProperties(process, recipeProperties);
    bindCustomProperties(process.getProperties(), recipeProperties);

    return process;
}

From source file:org.apache.nifi.authorization.AuthorityProviderFactoryBean.java

private AuthorityProviders loadAuthorityProvidersConfiguration() throws Exception {
    final File authorityProvidersConfigurationFile = properties.getAuthorityProviderConfiguraitonFile();

    // load the users from the specified file
    if (authorityProvidersConfigurationFile.exists()) {
        try {//w w  w  . j  a va 2s .co m
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory
                    .newSchema(AuthorityProviders.class.getResource(AUTHORITY_PROVIDERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<AuthorityProviders> element = unmarshaller
                    .unmarshal(new StreamSource(authorityProvidersConfigurationFile), AuthorityProviders.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the authority provider configuration file at: "
                    + authorityProvidersConfigurationFile.getAbsolutePath());
        }
    } else {
        throw new Exception("Unable to find the authority provider configuration file at "
                + authorityProvidersConfigurationFile.getAbsolutePath());
    }
}

From source file:org.apache.nifi.authorization.AuthorizerFactoryBean.java

private Authorizers loadAuthorizersConfiguration() throws Exception {
    final File authorizersConfigurationFile = properties.getAuthorizerConfigurationFile();

    // load the authorizers from the specified file
    if (authorizersConfigurationFile.exists()) {
        try {//from   www  .  j a v  a 2 s.c  o m
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory.newSchema(Authorizers.class.getResource(AUTHORIZERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<Authorizers> element = unmarshaller
                    .unmarshal(new StreamSource(authorizersConfigurationFile), Authorizers.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the authorizer configuration file at: "
                    + authorizersConfigurationFile.getAbsolutePath(), e);
        }
    } else {
        throw new Exception("Unable to find the authorizer configuration file at "
                + authorizersConfigurationFile.getAbsolutePath());
    }
}