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.echocat.jability.configuration.ConfigurationMarshaller.java

@Nonnull
protected static Unmarshaller unmarshallerFor(@Nullable Object element) {
    final Unmarshaller unmarshaller;
    try {// w  ww . j  ava2  s. c o m
        unmarshaller = JAXB_CONTEXT.createUnmarshaller();
        unmarshaller.setSchema(SCHEMA);
    } catch (JAXBException e) {
        throw new ConfigurationException("Could not create unmarshaller to unmarshal " + element + ".", e);
    }
    return unmarshaller;
}

From source file:org.echocat.jemoni.carbon.jmx.configuration.RulesMarshaller.java

@Nonnull
protected static Unmarshaller unmarshallerFor(@Nullable Object element) {
    final Unmarshaller unmarshaller;
    try {/*from w w w.j  a  va2s.c  o  m*/
        unmarshaller = JAXB_CONTEXT.createUnmarshaller();
        unmarshaller.setSchema(SCHEMA);
    } catch (JAXBException e) {
        throw new RuntimeException("Could not create unmarshaller to unmarshall " + element + ".", e);
    }
    return unmarshaller;
}

From source file:org.eclipse.smila.connectivity.framework.schema.internal.JaxbPluginContext.java

/**
 * Creates the validating unmarshaller.//  w w w .j a va2s  .c om
 * 
 * @return the unmarshaller
 * 
 * @throws JAXBException
 *           the JAXB exception
 * @throws SchemaNotFoundException
 *           the index order schema not found exception
 */
public Unmarshaller createValidatingUnmarshaller() throws JAXBException, SchemaNotFoundException {
    initilize();
    assertNotNull(_context);
    final Unmarshaller unmarshaller = _context.createUnmarshaller();
    final SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    try {
        sf.setResourceResolver(new XSDContextURIResolver(sf.getResourceResolver()));
        final javax.xml.validation.Schema schema = sf
                .newSchema(Platform.getBundle(_id).getEntry(_plugIn.getSchemaLocation()));
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(final ValidationEvent ve) {
                if (ve.getSeverity() != ValidationEvent.WARNING) {
                    final ValidationEventLocator vel = ve.getLocator();
                    _log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                    return false;
                }
                return true;
            }
        });
    } catch (final org.xml.sax.SAXException se) {
        throw new SchemaRuntimeException("Unable to validate due to following error.", se);
    }
    return unmarshaller;
}

From source file:org.eclipse.smila.management.jmx.client.helpers.ConfigLoader.java

/**
 * Load./*from w  w w .  j a v  a 2  s .com*/
 * 
 * @param is
 *          the is
 * 
 * @return the cmd config type
 * 
 * @throws ConfigurationLoadException
 *           the configuration load exception
 */
public static JmxClientConfigType load(final InputStream is) throws ConfigurationLoadException {
    try {
        final JAXBContext context = JAXBContext.newInstance("org.eclipse.smila.management.jmx.client.config");
        final SchemaFactory schemaFactory = SchemaFactory
                .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory.newSchema(new File("schemas/jmxclient.xsd"));
        final Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(createValidationEventHandler());
        Object result = unmarshaller.unmarshal(is);
        if (result != null) {
            if (result instanceof JAXBElement) {
                result = ((JAXBElement) result).getValue();
            }
        }
        return (JmxClientConfigType) result;
    } catch (final Throwable e) {
        throw new ConfigurationLoadException("Unable to load configuration", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (final Throwable e) {
                ;// nothing
            }
        }
    }
}

From source file:org.eclipse.smila.utils.jaxb.JaxbUtils.java

/**
 * Creates the validating unmarshaller.//from   w w  w.  j a  v a2 s .  c o  m
 * 
 * @param context
 *          the context
 * @param schema
 *          the schema
 * 
 * @return the unmarshaller
 * 
 * @throws JAXBException
 *           the JAXB exception
 */
public static Unmarshaller createValidatingUnmarshaller(final JAXBContext context, final Schema schema)
        throws JAXBException {
    if (schema == null) {
        throw new IllegalArgumentException("Schema is not found!");
    }
    final Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(schema);
    unmarshaller.setEventHandler(createValidationEventHandler());
    return unmarshaller;
}

From source file:org.evosuite.continuous.persistency.StorageManager.java

private static Project getProject(File current, InputStream stream) {
    try {/*from  w  w w  .  j  a  v  a  2  s .  c o m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(Project.class);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(
                new StreamSource(StorageManager.class.getResourceAsStream("/xsd/ctg_project_report.xsd")));
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        return (Project) jaxbUnmarshaller.unmarshal(stream);
    } catch (Exception e) {
        String msg = "Error in reading " + current.getAbsolutePath() + " , " + e;
        logger.error(msg, e);
        throw new RuntimeException(msg);
    }
}

From source file:org.excalibur.core.util.JAXBContextFactory.java

protected Unmarshaller createUnmarshaller(String contextPath) throws JAXBException {

    final Unmarshaller unmarshaller = getContext(contextPath).createUnmarshaller();

    if (!(getSchema() == null)) {
        unmarshaller.setSchema(getSchema());
    }//from  ww w.j av  a  2  s . c o  m

    return unmarshaller;
}

From source file:org.icefaces.application.showcase.view.builder.ApplicationBuilder.java

public void loadMetaData() {

    try {/*from   w ww .j  ava  2  s. c  o  m*/
        // create a jab context
        JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_FACTORY_PACKAGE);

        // schema factory for data validation purposes
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(
                new StreamSource(getResourceStream(META_DATA_RESOURCE_PATH + "/" + SCHEMA_FILE_NAME)));

        // create an unmarshaller and set schema
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);

        // grab and assign the application object graph
        application = (Application) unmarshaller.unmarshal(
                new StreamSource(getResourceStream(META_DATA_RESOURCE_PATH + "/" + META_DATA_FILE_NAME)));

    } catch (JAXBException e) {
        logger.error("JAXB Exception during unmarshalling:", e);
        throw new IllegalStateException("Could not load/unmarshal Application Meta Data: ", e);
    } catch (SAXException e) {
        logger.error("SAX Exception during unmarshalling:", e);
        throw new IllegalStateException("Could not load/unmarshal Application Meta Data: ", e);
    }

}

From source file:org.intermine.install.project.source.SourceInfoLoader.java

/**
 * Initialise this object by creating the JAXB context and the XML validation
 * schema for loading source descriptors, then loading each available data source
 * metadata./*ww  w  .jav a  2  s .  c o  m*/
 * <p>This method should be called exactly once at application start up.</p>
 * 
 * @throws JAXBException if there is a problem preparing the JAXB system, or
 * reading any of the source descriptors.
 * @throws IOException if there is an I/O error while loading the configuration.
 * @throws IllegalStateException if this object has already been initialised.
 */
public synchronized void initialise() throws JAXBException, IOException {
    if (initialised) {
        throw new IllegalStateException("SourceInfoLoader already initialised");
    }

    SchemaFactory sfact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        schema = sfact.newSchema(new StreamSource(getClass().getResourceAsStream("/xsd/sourcedescriptor.xsd")));
    } catch (SAXException e) {
        throw new JAXBException("Could not parse sourcedescriptor.xsd", e);
    }
    jaxbContext = JAXBContext.newInstance("org.intermine.install.project.source");

    // Initialise known types list.

    knownTypes = new ArrayList<String>();

    String resourceName = RESOURCE_PATH + "sourcetypes.txt";
    InputStream in = getClass().getResourceAsStream(resourceName);
    if (in == null) {
        throw new FileNotFoundException(resourceName);
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            knownTypes.add(line.trim());
        }
    } finally {
        in.close();
    }

    knownTypes = Collections.unmodifiableList(knownTypes);

    // Initialise information for these known types. 

    for (String type : knownTypes) {
        String descriptorFile = RESOURCE_PATH + type + ".xml";
        InputStream descriptorStream = getClass().getResourceAsStream(descriptorFile);
        if (descriptorStream == null) {
            logger.warn("There is no source descriptor file for the type " + type);
            continue;
        }

        // Load the source descriptor.
        SourceDescriptor source;
        try {
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            unmarshaller.setSchema(schema);
            JAXBElement<?> result = (JAXBElement<?>) unmarshaller.unmarshal(descriptorStream);
            source = (SourceDescriptor) result.getValue();
        } finally {
            descriptorStream.close();
        }

        // Load default property values, if any are present.
        Properties defaults = new Properties();
        String defaultsFile = RESOURCE_PATH + type + "_defaults.properties";
        InputStream defaultsStream = getClass().getResourceAsStream(defaultsFile);
        if (defaultsStream != null) {
            try {
                defaults.load(defaultsStream);
            } finally {
                defaultsStream.close();
            }
        }

        SourceInfo info = new SourceInfo(type, source, defaults);
        knownSources.put(type, info);

        if (info.getSource().getDerivation() != null) {
            derivatedSources.put(info.getSource().getDerivation().getAntTask(), info);
        }
    }

    initialised = true;
}

From source file:org.jts.eclipse.ui.actions.importbinding.Util.java

/**
  * Filter jsidl files, unmarshal and place in a Map.
  * @param fileList list of JSIDL XML files containing service sets
  * @return A Map from service set ID/version strings to JAXB instances representing those service sets.
 * @throws JAXBException //from ww  w.  j av  a2s  .c  o m
 * @throws SAXException 
  */
public static Map getObjectMapFromFile(List<File> fileList, List<ServiceDef> tmp)
        throws JAXBException, SAXException {
    Map objMap = new HashMap();
    Document doc = null;
    DocumentBuilder db = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Unmarshaller um = null;

    // Set up the unmarshaller with the schema included with the code
    // generator.
    try {
        JAXBContext jc = JAXBContext.newInstance("org.jts.jsidl.binding");
        um = jc.createUnmarshaller();
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Bundle bundle = CjsidlActivator.getInstance().getBundle();
        String schema_loc;
        if (new File(SCHEMA_PATH).exists()) {
            schema_loc = SCHEMA_PATH;
        } else if (new File(JTS_SCHEMA_PATH).exists()) {
            schema_loc = JTS_SCHEMA_PATH;
        } else if (new File(DEPLOYED_SCHEMA_PATH).exists()) {
            schema_loc = DEPLOYED_SCHEMA_PATH;
        } else {
            throw new Exception("Unable to find the schema path for jsidl_plus.xsd: "
                    + (new File(SCHEMA_PATH).getAbsolutePath()) + "\n\t"
                    + (new File(JTS_SCHEMA_PATH).getAbsolutePath()) + "\n\t"
                    + (new File(DEPLOYED_SCHEMA_PATH).getAbsolutePath()));
        }
        //         IPath path = new Path(schema_loc);
        //         URL schemaUrl = FileLocator.find(bundle, path,
        //               Collections.EMPTY_MAP);
        //         File schemaFile = new File(FileLocator.toFileURL(schemaUrl).toURI());
        File schemaFile = new File(schema_loc);
        Schema schema = sf.newSchema(schemaFile);
        um.setSchema(schema);

        // Try parsing each file.

        db = dbf.newDocumentBuilder();

        for (int ii = 0; ii < fileList.size(); ii++) {
            File file = fileList.get(ii);
            final String fileName = file.toString();

            doc = db.parse(file);

            Element root = doc.getDocumentElement();

            if (root.getAttribute("xmlns").equals("urn:jaus:jsidl:1.0")) {

                Object o = um.unmarshal(file);
                objMap.put(root.getAttribute("id") + "-" + root.getAttribute("version"), o);
                if (o instanceof ServiceDef) {
                    tmp.add((ServiceDef) o);
                }

            }
        }
    } catch (JAXBException jaxbe) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, jaxbe.getMessage(), jaxbe);
        throw jaxbe;
    } catch (SAXException saxe) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, saxe.getMessage(), saxe);
        throw saxe;
    } catch (URISyntaxException e) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (Exception e) {
        Logger.getLogger(ImportServiceSet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    }
    return objMap;
}