Example usage for javax.xml.validation SchemaFactory newInstance

List of usage examples for javax.xml.validation SchemaFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newInstance.

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

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

/**
 * Load.//from  w w w .  j ava2  s. co  m
 * 
 * @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.xml.SchemaUtils.java

/**
 * Load schema./*from   w  w w. jav  a  2  s . c o m*/
 * 
 * @param resourcePath
 *          the schema location
 * @param bundle
 *          the bundle
 * 
 * @return the schema
 * 
 * @throws SAXException
 *           the SAX exception
 */
public static Schema loadSchema(final Bundle bundle, final String resourcePath) throws SAXException {
    // TODO: remove it when DS will work ok
    final ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(SchemaUtils.class.getClassLoader());
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(bundle.getEntry(resourcePath));
    Thread.currentThread().setContextClassLoader(oldCL);
    return schema;
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.DescriptionHelper.java

/**
 * Validates <code>*.wbp-component.xml</code> against its schema.
 *//*  w w  w.  ja v  a 2 s  .  c o  m*/
public static synchronized void validateComponentDescription(ResourceInfo resource) throws Exception {
    // validate on developers computers
    if (EnvironmentUtils.isTestingTime()) {
        // prepare Schema
        if (m_wbpComponentSchema == null) {
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            InputStream schemaStream = DesignerPlugin.getFile("schema/wbp-component.xsd");
            m_wbpComponentSchema = factory.newSchema(new StreamSource(schemaStream));
        }
        // validate
        InputStream contents = resource.getURL().openStream();
        try {
            Validator validator = m_wbpComponentSchema.newValidator();
            validator.validate(new StreamSource(contents));
        } catch (Throwable e) {
            throw new Exception("Exception during validation " + resource.getURL(), e);
        } finally {
            contents.close();
        }
    }
}

From source file:org.eurekastreams.server.action.validation.gallery.UrlXmlValidator.java

/**
 * Validates xml from given Url returning true if it passes validation, false otherwise.
 *
 * @param inActionContext// w w  w  .java2  s  .  co  m
 *            the action context
 * @throws ValidationException
 *             on error
 */
@Override
@SuppressWarnings("unchecked")
public void validate(final ServiceActionContext inActionContext) throws ValidationException {
    InputStream schemaStream = null;
    Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams();
    String galleryItemUrl = (String) fields.get(URL_KEY);
    try {
        schemaStream = this.getClass().getResourceAsStream(xsdPath);
        log.debug("Attempt to validate xml at: " + galleryItemUrl + "with xsd at: " + xsdPath);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaString);
        Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));

        Validator validator = schema.newValidator();

        // TODO: stuff the input stream into the context for execute()
        InputStream galleryItemInputStream = xmlFetcher.getInputStream(galleryItemUrl);

        validator.validate(new StreamSource(galleryItemInputStream));

        log.debug("Success validating xml at: " + galleryItemUrl);
    } catch (Exception e) {
        log.error("Validation for gadget definition failed.", e);
        ValidationException ve = new ValidationException();
        ve.addError(URL_KEY, "Valid url is required");
        throw ve;
    } finally {
        try {
            if (schemaStream != null) {
                schemaStream.close();
            }
        } catch (IOException ex) {
            log.error("Error closing stream, already closed.", ex);
        }
    }
}

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

private static Project getProject(File current, InputStream stream) {
    try {//from www .  j  av  a2s. c  om
        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

public static Schema getSchema(final URL url) {
    Schema schema = null;//from  w  w w .java2 s. co  m
    try {
        schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(url);
    } catch (SAXException e) {
        LOG.warn(e.getMessage(), e);
    }

    return schema;
}

From source file:org.flowable.cmmn.converter.CmmnXmlConverter.java

protected Schema createSchema() throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;/*from ww w.  ja va2 s .  c om*/
    if (classloader != null) {
        schema = factory.newSchema(classloader.getResource(XSD_LOCATION));
    }

    if (schema == null) {
        schema = factory.newSchema(this.getClass().getClassLoader().getResource(XSD_LOCATION));
    }

    if (schema == null) {
        throw new CmmnXMLException("CMND XSD could not be found");
    }
    return schema;
}

From source file:org.forgerock.maven.plugins.LinkTester.java

@Override()
public void execute() throws MojoExecutionException, MojoFailureException {
    if (outputFile != null) {
        if (!outputFile.isAbsolute()) {
            outputFile = new File(project.getBasedir(), outputFile.getPath());
        }/*from  w  w  w . j  a  v a  2s  . c  o m*/
        if (outputFile.exists()) {
            debug("Deleting existing outputFile: " + outputFile);
            outputFile.delete();
        }
        try {
            outputFile.createNewFile();
            fileWriter = new FileWriter(outputFile);
        } catch (IOException ioe) {
            error("Error while creating output file", ioe);
        }
    }
    initializeSkipUrlPatterns();

    //Initialize XML parsers and XPath expressions
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setExpandEntityReferences(false);
    dbf.setXIncludeAware(xIncludeAware);

    if (validating) {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            Schema schema = sf.newSchema(new URL(DOCBOOK_XSD));
            dbf.setSchema(schema);
        } catch (MalformedURLException murle) {
            error("Invalid URL provided as schema source", murle);
        } catch (SAXException saxe) {
            error("Parsing error occurred while constructing schema for validation", saxe);
        }
    }
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        db.setErrorHandler(new LoggingErrorHandler(this));
    } catch (ParserConfigurationException pce) {
        throw new MojoExecutionException("Unable to create new DocumentBuilder", pce);
    }

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new XmlNamespaceContext());
    XPathExpression expr;
    try {
        expr = xpath.compile("//@xml:id");
    } catch (XPathExpressionException xpee) {
        throw new MojoExecutionException("Unable to compile Xpath expression", xpee);
    }

    if (docSources != null) {
        for (DocSource docSource : docSources) {
            processDocSource(docSource, db, expr);
        }
    }

    try {
        if (!skipOlinks) {
            //we can only check olinks after going through all the documents, otherwise we would see false
            //positives, because of the not yet processed files
            for (Map.Entry<String, Collection<String>> entry : (Set<Map.Entry<String, Collection<String>>>) olinks
                    .entrySet()) {
                for (String val : entry.getValue()) {
                    checkOlink(entry.getKey(), val);
                }
            }
        }
        if (!failedUrls.isEmpty()) {
            error("The following files had invalid URLs:\n" + failedUrls.toString());
        }
        if (!timedOutUrls.isEmpty()) {
            warn("The following files had unavailable URLs (connection or read timed out):\n"
                    + timedOutUrls.toString());
        }
        if (failedUrls.isEmpty() && timedOutUrls.isEmpty() && !failure) {
            //there are no failed URLs and the parser didn't encounter any errors either
            info("DocBook links successfully tested, no errors reported.");
        }
    } finally {
        flushReport();
    }
    if (failOnError) {
        if (failure || !failedUrls.isEmpty()) {
            throw new MojoFailureException("One or more error occurred during plugin execution");
        }
    }
}

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

protected void checkValidationErorrs(Document dom, String schemaLocation) throws SAXException, IOException {
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new File(schemaLocation));
    checkValidationErrors(dom, schema);//from  ww w  .  j  a va2 s. c o m
}

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

public void loadMetaData() {

    try {//from   w w  w .  j  ava 2s. com
        // 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);
    }

}