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:Main.java

/**
 * Unmarshal XML data from XML file path using XSD from file path and return the resulting JAXB content tree
 *
 * @param dummyCtxObject//  ww w.  j av a 2  s . c  om
 *            Dummy contect object for creating related JAXB context
 * @param strXMLFilePath
 *            XML file path
 * @param strXSDFilePath
 *            XSD file path
 * @return resulting JAXB content tree
 * @throws Exception
 *             in error case
 */
public static Object doUnmarshallingFromFiles(Object dummyCtxObject, String strXMLFilePath,
        String strXSDFilePath) throws Exception {
    if (dummyCtxObject == null) {
        throw new RuntimeException("No dummy context object (null)!");
    }
    if (strXMLFilePath == null) {
        throw new RuntimeException("No XML file path (null)!");
    }
    if (strXSDFilePath == null) {
        throw new RuntimeException("No XSD file path (null)!");
    }

    Object unmarshalledObject = null;

    FileInputStream fis = null;
    try {
        JAXBContext jaxbCtx = JAXBContext.newInstance(dummyCtxObject.getClass().getPackage().getName());
        Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
        // unmarshaller.setValidating(true);
        javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory
                .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new java.io.File(strXSDFilePath));
        unmarshaller.setSchema(schema); // register schema for validation

        fis = new FileInputStream(strXMLFilePath);
        unmarshalledObject = unmarshaller.unmarshal(fis);
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error);
        throw e;
    } finally {
        if (fis != null) {
            fis.close();
            fis = null;
        }
    }

    return unmarshalledObject;
}

From source file:Main.java

/**
 * Unmarshal XML data from XML string using XSD string and return the resulting JAXB content tree
 *
 * @param dummyCtxObject// w w  w.j  a v a  2 s.  co  m
 *            Dummy contect object for creating related JAXB context
 * @param strXML
 *            XML
 * @param strXSD
 *            XSD
 * @return resulting JAXB content tree
 * @throws Exception
 *             in error case
 */
public static Object doUnmarshalling(Object dummyCtxObject, String strXML, String strXSD) throws Exception {
    if (dummyCtxObject == null) {
        throw new RuntimeException("No dummy context objekt (null)!");
    }
    if (strXML == null) {
        throw new RuntimeException("No XML document (null)!");
    }
    if (strXSD == null) {
        throw new RuntimeException("No XSD document (null)!");
    }

    Object unmarshalledObject = null;
    StringReader readerXSD = null;
    StringReader readerXML = null;

    try {
        JAXBContext jaxbCtx = JAXBContext.newInstance(dummyCtxObject.getClass().getPackage().getName());
        Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
        readerXSD = new StringReader(strXSD);
        readerXML = new StringReader(strXML);

        javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory
                .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(readerXSD));
        unmarshaller.setSchema(schema);

        unmarshalledObject = unmarshaller.unmarshal(new StreamSource(readerXML));
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error);
        throw e;
    } finally {
        if (readerXSD != null) {
            readerXSD.close();
            readerXSD = null;
        }
        if (readerXML != null) {
            readerXML.close();
            readerXML = null;
        }
    }

    return unmarshalledObject;
}

From source file:energy.usef.core.util.XMLUtil.java

/**
 * Converts xml to an object after optional validation against the xsd.
 *
 * @param xml xml string//  ww  w . j  ava 2s .c  o  m
 * @param validate true when the xml needs to be validated
 * @return object corresponding to this xml
 */
public static Object xmlToMessage(String xml, boolean validate) {
    try (InputStream is = IOUtils.toInputStream(xml, UTF_8)) {
        Unmarshaller unmarshaller = CONTEXT.createUnmarshaller();

        if (validate) {
            // setup xsd validation
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(XMLUtil.class.getClassLoader().getResource(MESSAGING_XSD_FILE));

            unmarshaller.setSchema(schema);
        }

        return unmarshaller.unmarshal(is);
    } catch (JAXBException | IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new TechnicalException("Invalid XML content: " + e.getMessage(), e);
    } catch (SAXException e) {
        LOGGER.error(e.getMessage(), e);
        throw new TechnicalException("Unable to read XSD schema", e);
    }
}

From source file:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(URL xmlUrl, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;
    ValidationResult result;/*from  ww  w.ja va2s.c  om*/
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlUrl);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}

From source file:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(FileInputStream xmlPath, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;
    ValidationResult result;// w  ww.  j a  va 2s. c  o m
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlPath);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}

From source file:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(InputStream xmlStream, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;
    ValidationResult result;/*from  w  ww. j a  v  a2  s . com*/
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlStream);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}

From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java

/**
 * Standard test for XSD examples.//from  ww w .j  a  v  a  2s .co m
 * 
 * @param testName
 *            the prototype of XSD file name / package name
 * @param extraXewOptions
 *            to be passed to plugin
 * @param generateEpisode
 *            generate episode file and check the list of classes included into it
 * @param classesToCheck
 *            expected classes/files in target directory; these files content is checked if it is present in
 *            resources directory; {@code ObjectFactory.java} is automatically included
 */
static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode,
        String... classesToCheck) throws Exception {
    String resourceXsd = testName + ".xsd";
    String packageName = testName.replace('-', '_');

    // Force plugin to reinitialize the logger:
    System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY);

    URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd);

    File targetDir = new File(GENERATED_SOURCES_PREFIX);

    targetDir.mkdirs();

    PrintStream loggingPrintStream = new PrintStream(
            new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] "));

    String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d",
            targetDir.getPath(), xsdUrl.getFile());

    String episodeFile = new File(targetDir, "episode.xml").getPath();

    // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6
    if (generateEpisode) {
        opts = ArrayUtils.addAll(opts, "-episode", episodeFile);
    }

    assertTrue("XJC compilation failed. Checked console for more info.",
            Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0);

    if (generateEpisode) {
        // FIXME: Episode file actually contains only value objects
        Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile);

        if (Arrays.asList(classesToCheck).contains("package-info")) {
            classReferences.add(packageName + ".package-info");
        }

        assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size());

        for (String className : classesToCheck) {
            assertTrue(className + " class is missing in episode file;",
                    classReferences.contains(packageName + "." + className));
        }
    }

    targetDir = new File(targetDir, packageName);

    Collection<String> generatedJavaSources = new HashSet<String>();

    // *.properties files are ignored:
    for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) {
        // This is effectively the path of targetFile relative to targetDir:
        generatedJavaSources
                .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/'));
    }

    // This class is added and checked by default:
    classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory");

    assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length,
            generatedJavaSources.size());

    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className));
    }

    // Check the contents for those files which exist in resources:
    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className);

        if (sourceFile.exists()) {
            // To avoid CR/LF conflicts:
            assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""),
                    FileUtils.readFileToString(new File(targetDir, className)).replace("\r", ""));
        }
    }

    JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources);

    URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml");

    if (xmlTestFile != null) {
        StringWriter writer = new StringWriter();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl));

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        Object bean = unmarshaller.unmarshal(xmlTestFile);
        marshaller.marshal(bean, writer);

        XMLUnit.setIgnoreComments(true);
        XMLUnit.setIgnoreWhitespace(true);
        Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString());

        assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true);
    }
}

From source file:eu.scape_project.tool.toolwrapper.data.tool_spec.utils.Utils.java

private static void setSchemaTo(Unmarshaller unmarshaller) throws IOException, SAXException {
    // copy XML Schema from resources to a temporary location
    File schemaFile = File.createTempFile("schema", null);
    FileUtils.copyInputStreamToFile(Utils.class.getResourceAsStream(TOOLSPEC_FILENAME_IN_RESOURCES),
            schemaFile);/*  w  w w .j  a va2 s.  c o m*/
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);

    // validate provided toolspec against XML Schema
    unmarshaller.setSchema(schema);
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final Vaadlets unmarshal(final Reader aReader, final Resource theSchemaResource) {
    try {//from   w  w  w.ja v a  2  s  . c  o m
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            unmarshaller.setSchema(schema);
        }
        return unmarshaller
                .unmarshal(XMLInputFactory.newInstance().createXMLStreamReader(aReader), Vaadlets.class)
                .getValue();
    } catch (final JAXBException | SAXException | XMLStreamException | FactoryConfigurationError
            | IOException e) {
        throw new RuntimeException("Can't unmarschal", e);
    }
}

From source file:com.threeglav.sh.bauk.main.StreamHorizonEngine.java

private static final BaukConfiguration findConfiguration() {
    LOG.info(/*from   w ww.  ja  va 2 s .c o  m*/
            "Trying to find configuration file. First if specified as {} system property and then as {} in classpath",
            CONFIG_FILE_PROP_NAME, DEFAULT_CONFIG_FILE_NAME);
    final String configFile = System.getProperty(CONFIG_FILE_PROP_NAME);
    InputStream is = null;
    if (StringUtil.isEmpty(configFile)) {
        LOG.info(
                "Was not able to find system property {}. Trying to find default configuration {} in classpath",
                CONFIG_FILE_PROP_NAME, DEFAULT_CONFIG_FILE_NAME);
        is = StreamHorizonEngine.class.getClassLoader().getResourceAsStream(DEFAULT_CONFIG_FILE_NAME);
        if (is == null) {
            LOG.error("Was not able to find file {} in the classpath. Unable to start application",
                    DEFAULT_CONFIG_FILE_NAME);
            return null;
        }
        LOG.info("Found configuration file {} in classpath", DEFAULT_CONFIG_FILE_NAME);
    } else {
        LOG.info("Found system property {}={}. Will try to load it as configuration...", CONFIG_FILE_PROP_NAME,
                configFile);
        final File cFile = new File(configFile);
        try {
            if (cFile.exists() && cFile.isFile()) {
                LOG.debug("Loading config file [{}] from file system", configFile);
                is = new FileInputStream(configFile);
            } else {
                LOG.debug("Loading config file [{}] from classpath", configFile);
                is = StreamHorizonEngine.class.getClass().getResourceAsStream(configFile);
            }
            LOG.info("Successfully found configuration [{}] on file system", configFile);
        } catch (final FileNotFoundException fnfe) {
            LOG.error("Was not able to find file {}. Use full, absolute path.", configFile);
            return null;
        }
    }
    if (is == null) {
        return null;
    }
    try {
        LOG.debug("Trying to load configuration from xml file");
        final JAXBContext jaxbContext = JAXBContext.newInstance(BaukConfiguration.class);
        final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory
                .newSchema(StreamHorizonEngine.class.getResource("/bauk_config.xsd"));
        jaxbUnmarshaller.setSchema(schema);
        final BaukConfiguration config = (BaukConfiguration) jaxbUnmarshaller.unmarshal(is);
        LOG.info("Successfully loaded configuration");
        return config;
    } catch (final Exception exc) {
        LOG.error("Exception while loading configuration", exc);
        exc.printStackTrace();
        return null;
    } finally {
        IOUtils.closeQuietly(is);
    }
}