Example usage for javax.xml.bind Unmarshaller unmarshal

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

Introduction

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

Prototype

public Object unmarshal(javax.xml.stream.XMLEventReader reader) throws JAXBException;

Source Link

Document

Unmarshal XML data from the specified pull parser and return the resulting content tree.

Usage

From source file:com.jkoolcloud.tnt4j.streams.configure.state.AbstractFileStreamStateHandler.java

/**
 * Loads XML persisted streamed files access state.
 *
 * @param stateFile//  www  . j ava 2 s  .c o m
 *            XML file of persisted streamed files access state
 *
 * @return loaded streamed files access state
 *
 * @throws JAXBException
 *             if state unmarshaling fails
 */
private static FileAccessState unmarshal(File stateFile) throws JAXBException {
    JAXBContext jaxb = JAXBContext.newInstance(FileAccessState.class);
    final Unmarshaller unmarshaller = jaxb.createUnmarshaller();
    return (FileAccessState) unmarshaller.unmarshal(stateFile);
}

From source file:cz.lbenda.dataman.db.DbStructureFactory.java

public static void loadDatabaseStructureFromXML(InputStream dbStructure, DbConfig dbConfig) {
    try {/*  w w w .  j a  va  2  s .c o m*/
        JAXBContext jc = JAXBContext.newInstance(cz.lbenda.dataman.schema.dbstructure.ObjectFactory.class);
        Unmarshaller um = jc.createUnmarshaller();
        Object ob = um.unmarshal(dbStructure);
        if (ob instanceof JAXBElement && ((JAXBElement) ob).getValue() instanceof DatabaseStructureType) {
            //noinspection unchecked
            loadDatabaseStructureFromXML(((JAXBElement<DatabaseStructureType>) ob).getValue(), dbConfig);
        } else {
            throw new RuntimeException(
                    "The file with database structure not contains XML with cached database structure.");
        }
    } catch (JAXBException e) {
        LOG.error("Problem with read cached database structure configuration: " + e.toString(), e);
        throw new RuntimeException("Problem with read cached database structure configuration: " + e.toString(),
                e);
    }
}

From source file:scott.barleydb.test.TestBase.java

private static DefinitionsSpec loadDefinitions(String path, String namespace) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(SpecRegistry.class, StructureType.class, SyntaxType.class,
            EtlSpec.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    SpecRegistry registry = (SpecRegistry) unmarshaller.unmarshal(new File(path));
    DefinitionsSpec spec = registry.getDefinitionsSpec(namespace);
    if (spec == null) {
        throw new IllegalStateException("Could not load definitions " + namespace);
    }/*w  w w.  j  a  v a 2 s  .co m*/

    if (db instanceof MySqlDbTest) {
        spec = MySqlSpecConverter.convertSpec(spec);
    }
    return spec;
}

From source file:com.bitplan.w3ccheck.W3CValidator.java

/**
 * create a W3CValidator result for the given url with the given html
 * /*  w  w w. j av a 2s . c o  m*/
 * @param url - the url of the validator e.g. "http://validator.w3.org/check"
 * @param html - the html code to be checked
 * @return - a W3CValidator response according to the SOAP response format or null if the
 * http response status of the Validation service is other than 200
 * explained at response http://validator.w3.org/docs/api.html#requestformat 
 * @throws JAXBException if there is something wrong with the response message so that it
 * can not be unmarshalled
 */
public static W3CValidator check(String url, String html) throws JAXBException {
    // initialize the return value
    W3CValidator result = null;

    // create a WebResource to access the given url
    WebResource resource = Client.create().resource(url);

    // prepare form data for posting
    FormDataMultiPart form = new FormDataMultiPart();

    // set the output format to soap12
    // triggers the various outputs formats of the validator. If unset, the usual Web format will be sent. 
    // If set to soap12, 
    // the SOAP1.2 interface will be triggered. See the SOAP 1.2 response format description at
    //  http://validator.w3.org/docs/api.html#requestformat
    form.field("output", "soap12");

    // make sure Unicode 0x0 chars are removed from html (if any)
    // see https://github.com/WolfgangFahl/w3cValidator/issues/1
    Pattern pattern = Pattern.compile("[\\000]*");
    Matcher matcher = pattern.matcher(html);
    if (matcher.find()) {
        html = matcher.replaceAll("");
    }

    // The document to validate, POSTed as multipart/form-data
    FormDataBodyPart fdp = new FormDataBodyPart("uploaded_file", IOUtils.toInputStream(html),
            // new FileInputStream(tmpHtml),
            MediaType.APPLICATION_OCTET_STREAM_TYPE);

    // attach the inputstream as upload info to the form
    form.bodyPart(fdp);

    // now post the form via the Internet/Intranet
    ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    // in debug mode show the response status
    if (debug)
        LOGGER.log(Level.INFO, "response status for '" + url + "'=" + response.getStatus());
    // if the http Status is ok
    if (response.getStatus() == 200) {
        // get the XML encoded SOAP 1.2 response format
        String responseXml = response.getEntity(String.class);
        // in debug mode show the full xml 
        if (debug)
            LOGGER.log(Level.INFO, responseXml);
        // unmarshal the xml message to the format to a W3CValidator Java object
        JAXBContext context = JAXBContext.newInstance(W3CValidator.class);
        Unmarshaller u = context.createUnmarshaller();
        StringReader xmlReader = new StringReader(responseXml);
        // this step will convert from xml text to Java Object
        result = (W3CValidator) u.unmarshal(xmlReader);
    }
    // return the result which might be null if the response status was other than 200
    return result;

}

From source file:org.apache.falcon.regression.core.util.Util.java

/**
 * Converts service response to api result form.
 * @param response service response//from  w  w  w.  j  a  va2  s  . co m
 * @return api result
 * @throws JAXBException
 */
public static APIResult parseResponse(ServiceResponse response) throws JAXBException {
    if (!isXML(response.getMessage())) {
        return new APIResult(APIResult.Status.FAILED, response.getMessage());
    }
    JAXBContext jc = JAXBContext.newInstance(APIResult.class);
    Unmarshaller u = jc.createUnmarshaller();
    if (response.getMessage().contains("requestId")) {
        return (APIResult) u.unmarshal(new InputSource(new StringReader(response.getMessage())));
    } else {
        return new APIResult(response.getCode() == 200 ? APIResult.Status.SUCCEEDED : APIResult.Status.FAILED,
                response.getMessage());
    }
}

From source file:com.inamik.template.util.TemplateConfigUtil.java

/**
 * readTemplateLibConfig w/InputStream - Read a template library
 * xml configuration from an InputStream.
 *
 * @param stream The InputStream to read.
 * @return A template library configuration suitable for adding to a
 *         template engine configuration.
 * @throws TemplateException This method uses JAXB to parse the xml
 *         configuration.  If JAXB throws an exception, this method catches
 *         it and re-throws it as a wrapped TemplateException.
 * @throws NullPointerException if <code>stream == null</code>
 *
 * @see TemplateEngineConfig/*from w  w w  .j a  v  a  2 s .com*/
 */
public static TemplateLibConfig readTemplateLibConfig(final InputStream stream) throws TemplateException {
    TemplateLibConfig libConfig = new TemplateLibConfig();

    try {
        JAXBContext jc = JAXBContext.newInstance(JAXB_LIB_PACKAGE);

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        TemplateLib tl;

        tl = (TemplateLib) u.unmarshal(stream);

        List<Object> list = tl.getActionOrFunctionOrFilter();

        for (Object o : list) {
            // TemplateActionTag
            if (o instanceof TemplateLib.Action) {
                TemplateLib.Action a = (TemplateLib.Action) o;

                String name = a.getName();
                String clazz = a.getClazz();

                TemplateActionConfig.ParmType parmType = TemplateActionConfig.ParmType
                        .findByName(a.getParmType());
                TemplateActionConfig.BlockType blockType = TemplateActionConfig.BlockType
                        .findByName(a.getBlockType());
                TemplateActionConfig.BodyContent bodyType = TemplateActionConfig.BodyContent
                        .findByName(a.getBodyContent());

                TemplateActionConfig actionConfig = new TemplateActionConfig(name, clazz, parmType, blockType,
                        bodyType);

                libConfig.addAction(actionConfig);
            } else
            // TemplateFunctionTag
            if (o instanceof TemplateLib.Function) {
                TemplateLib.Function function = (TemplateLib.Function) o;

                String name = function.getName();
                String clazz = function.getClazz();

                TemplateFunctionConfig functionConfig = new TemplateFunctionConfig(name, clazz);

                libConfig.addFunction(functionConfig);
            } else
            // TemplateFilterTag
            if (o instanceof TemplateLib.Filter) {
                TemplateLib.Filter filter = (TemplateLib.Filter) o;

                String name = filter.getName();
                String clazz = filter.getClazz();

                TemplateFilterConfig filterConfig = new TemplateFilterConfig(name, clazz);

                libConfig.addFilter(filterConfig);
            } else {
                throw new RuntimeException("Unknown type" + o.getClass().getCanonicalName());
            }
        }
    } catch (JAXBException e) {
        throw new TemplateException(e);
    }

    return libConfig;
}

From source file:com.evolveum.midpoint.testing.model.client.sample.RunScript.java

private static <T> T unmarshallResouce(String path) throws JAXBException, FileNotFoundException {
    JAXBContext jc = getJaxbContext();
    Unmarshaller unmarshaller = jc.createUnmarshaller();

    InputStream is = null;//  w  ww.j a  va  2  s . c  o m
    JAXBElement<T> element = null;
    try {
        is = RunScript.class.getClassLoader().getResourceAsStream(path);
        if (is == null) {
            throw new FileNotFoundException("System resource " + path + " was not found");
        }
        element = (JAXBElement<T>) unmarshaller.unmarshal(is);
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
    }
    if (element == null) {
        return null;
    }
    return element.getValue();
}

From source file:com.inamik.template.util.TemplateConfigUtil.java

/**
 * readTemplateEngineConfig w/InputStream - Read a template engine
 * xml configuration from an InputStream.
 *
 * @param stream The InputStream to read.
 * @return A template engine configuration suitable for instantiating
 *         a TemplateEngine class.//from  www  . j  a v a2 s.com
 * @throws TemplateException This method uses JAXB to parse the xml
 *         configuration.  If JAXB throws an exception, this method catches
 *         it and re-throws it as a wrapped TemplateException.
 * @throws NullPointerException if <code>stream == null</code>
 */
public static TemplateEngineConfig readTemplateEngineConfig(final InputStream stream) throws TemplateException {
    if (stream == null) {
        throw new NullPointerException("stream");
    }

    TemplateEngineConfig engineConfig = new TemplateEngineConfig();

    try {
        JAXBContext jc = JAXBContext.newInstance(JAXB_CONFIG_PACKAGE);

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        TemplateConfig tc = (TemplateConfig) u.unmarshal(stream);

        if (tc.getApplicationRoot() != null) {
            engineConfig.setApplicationRoot(tc.getApplicationRoot());
        }

        engineConfig.setTemplateRoot(tc.getTemplateRoot());

        if (tc.getTagDelimeter() != null) {
            engineConfig.setTagDelimeter(tc.getTagDelimeter());
        }

        engineConfig.setUseDefaultLib(tc.isUseDefaultLib());

        engineConfig.setDebug(tc.isDebug());

        Cache cache = tc.getCache();

        if (cache != null) {
            TemplateCacheConfig cacheConfig = new TemplateCacheConfig();

            // Name
            cacheConfig.setName(cache.getName());

            // diskExpiryThreadIntervalSeconds
            if (cache.getDiskExpiryThreadIntervalSeconds() != null) {
                final int i = cache.getDiskExpiryThreadIntervalSeconds().intValue();
                cacheConfig.setDiskExpiryThreadIntervalSeconds(i);
            }

            // diskPersistent
            cacheConfig.setDiskPersistent(cache.isDiskPersistent());

            // diskRoot
            if (cache.getDiskRoot() != null) {
                cacheConfig.setDiskRoot(cache.getDiskRoot());
            }

            // eternal (required)
            cacheConfig.setEternal(cache.isEternal());

            // maxElementsInMemory
            if (cache.getMaxElementsInMemory() != null) {
                int i = cache.getMaxElementsInMemory().intValue();
                cacheConfig.setMaxElementsInMemory(i);
            }

            // memoryEvictionPolicy
            if (cache.getMemoryStoreEvictionPolicy() != null) {
                EvictionPolicy ep = EvictionPolicy.valueOf(cache.getMemoryStoreEvictionPolicy());
                cacheConfig.setMemoryStoreEvictionPolicy(ep);
            }

            // overflowToDisk (required)
            cacheConfig.setOverflowToDisk(cache.isOverflowToDisk());

            // timeToIdleSeconds
            if (cache.getTimeToIdleSeconds() != null) {
                int i = cache.getTimeToIdleSeconds().intValue();
                cacheConfig.setTimeToIdleSeconds(i);
            }

            // timeToLiveSeconds
            if (cache.getTimeToLiveSeconds() != null) {
                int i = cache.getTimeToLiveSeconds().intValue();
                cacheConfig.setTimeToLiveSeconds(i);
            }

            engineConfig.setCacheConfig(cacheConfig);
        }

        List<TemplateConfig.UseLib> useLibs = tc.getUseLib();

        // We can't resolve the use-libs now because the application-root
        // Has not been verified.  So we store them to be resolved later
        // by the TemplateEngine
        for (TemplateConfig.UseLib lib : useLibs) {
            TemplateEngineConfig.UseLib useLib = new TemplateEngineConfig.UseLib(lib.getFile(),
                    lib.getResource(), lib.getPrefix());

            engineConfig.addUseLib(useLib);
        }
    } catch (JAXBException e) {
        throw new TemplateException(e);
    }

    return engineConfig;
}

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

private static final BaukConfiguration findConfiguration() {
    LOG.info(//from  w ww  .java 2s.  c om
            "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);
    }
}

From source file:org.apache.lens.regression.util.Util.java

@SuppressWarnings("unchecked")
public static <T> Object getObject(String queryString, Class<T> c) throws IllegalAccessException {
    JAXBContext jaxbContext = null;
    Unmarshaller unmarshaller = null;
    StringReader reader = new StringReader(queryString);
    try {//from  w  w  w. j  a v  a 2  s  .  c  o  m
        jaxbContext = new LensJAXBContext(c);
        unmarshaller = jaxbContext.createUnmarshaller();
        return (T) unmarshaller.unmarshal(reader);
    } catch (JAXBException e) {
        System.out.println("Exception : " + e);
        return null;
    }
}