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:nl.nn.adapterframework.align.Json2Xml.java

public static String translate(JsonStructure json, URL schemaURL, boolean compactJsonArrays, String rootElement,
        boolean strictSyntax, boolean deepSearch, String targetNamespace, Map<String, Object> overrideValues)
        throws SAXException, IOException {

    // create the ValidatorHandler
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(schemaURL);
    ValidatorHandler validatorHandler = schema.newValidatorHandler();

    // create the XSModel
    XMLSchemaLoader xsLoader = new XMLSchemaLoader();
    XSModel xsModel = xsLoader.loadURI(schemaURL.toExternalForm());
    List<XSModel> schemaInformation = new LinkedList<XSModel>();
    schemaInformation.add(xsModel);//from  www  .j ava 2s  . c o  m

    // create the validator, setup the chain
    Json2Xml j2x = new Json2Xml(validatorHandler, schemaInformation, compactJsonArrays, rootElement,
            strictSyntax);
    if (overrideValues != null) {
        j2x.setOverrideValues(overrideValues);
    }
    if (targetNamespace != null) {
        //if (DEBUG) System.out.println("setting targetNamespace ["+targetNamespace+"]");
        j2x.setTargetNamespace(targetNamespace);
    }
    j2x.setDeepSearch(deepSearch);
    Source source = j2x.asSource(json);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    String xml = null;
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(source, result);
        writer.flush();
        xml = writer.toString();
    } catch (TransformerConfigurationException e) {
        SAXException se = new SAXException(e);
        se.initCause(e);
        throw se;
    } catch (TransformerException e) {
        SAXException se = new SAXException(e);
        se.initCause(e);
        throw se;
    }
    return xml;
}

From source file:nl.nn.adapterframework.align.XmlTo.java

public static void translate(String xml, URL schemaURL, DocumentContainer documentContainer)
        throws SAXException, IOException {

    // create the ValidatorHandler
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(schemaURL);
    ValidatorHandler validatorHandler = schema.newValidatorHandler();

    // create the parser, setup the chain
    XMLReader parser = new SAXParser();
    XmlAligner aligner = new XmlAligner(validatorHandler);
    XmlTo<DocumentContainer> xml2object = new XmlTo<DocumentContainer>(aligner, documentContainer);
    parser.setContentHandler(validatorHandler);
    aligner.setContentHandler(xml2object);

    // start translating
    InputSource is = new InputSource(new StringReader(xml));
    parser.parse(is);//from  w w w.ja  v  a 2 s.co  m
}

From source file:nl.nn.adapterframework.validation.JavaxXmlValidator.java

/**
 * Returns the {@link Schema} associated with this validator. This is an XSD schema containing knowledge about the
 * schema source as returned by {@link #getSchemaSources(List)}
 *//*from  w w  w.  j a v a2s.  com*/
protected synchronized Schema getSchemaObject(String schemasId,
        List<nl.nn.adapterframework.validation.Schema> schemas) throws ConfigurationException {
    Schema schema = javaxSchemas.get(schemasId);
    if (schema == null) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new LSResourceResolver() {
            public LSInput resolveResource(String s, String s1, String s2, String s3, String s4) {
                return null;
            }
        });
        try {
            Collection<Source> sources = getSchemaSources(schemas);
            schema = factory.newSchema(sources.toArray(new Source[sources.size()]));
            javaxSchemas.put(schemasId, schema);
        } catch (Exception e) {
            throw new ConfigurationException("cannot read schema's [" + schemasId + "]", e);
        }
    }
    return schema;
}

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

public BatchExtractParser() {
    try {//from   w  w  w. ja va2  s .  c  o m
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = schemaFactory.newSchema(new StreamSource(SchemaValidator.class.getResourceAsStream(XSD_FILE),
                SchemaValidator.class.getResource(XSD_FILE).toString()));
        objectBuilder = XMLMessageBuilder.getInstance(BAGExtractDeelbestandLVC.class);
    } catch (Exception e) {
        throw new ParserException(e);
    }
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsModule.java

/**
 * Initializes the EPCIS schema used for validating incoming capture
 * requests. Loads the WSDL and XSD files from the classpath (the schema is
 * bundled with epcis-commons.jar).//from w ww  .ja  va2  s . com
 * 
 * @return An instantiated schema validation object.
 */
private Schema initEpcisSchema(String xsdFile) {
    InputStream is = this.getClass().getResourceAsStream(xsdFile);
    if (is != null) {
        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Source schemaSrc = new StreamSource(is);
            schemaSrc.setSystemId(CaptureOperationsServlet.class.getResource(xsdFile).toString());
            Schema schema = schemaFactory.newSchema(schemaSrc);
            LOG.debug("EPCIS schema file initialized and loaded successfully");
            return schema;
        } catch (Exception e) {
            LOG.warn("Unable to load or parse the EPCIS schema", e);
        }
    } else {
        LOG.error("Unable to load the EPCIS schema file from classpath: cannot find resource " + xsdFile);
    }
    LOG.warn("Schema validation will not be available!");
    return null;
}

From source file:org.activiti.bpmn.converter.BpmnXMLConverter.java

protected Schema createSchema() throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;/* w w w  .  j av a 2 s  .com*/
    if (classloader != null) {
        schema = factory.newSchema(classloader.getResource(BPMN_XSD));
    }

    if (schema == null) {
        schema = factory.newSchema(BpmnXMLConverter.class.getClassLoader().getResource(BPMN_XSD));
    }

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

From source file:org.activiti.dmn.xml.converter.DmnXMLConverter.java

protected Schema createSchema() throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;// w w w .  ja v  a2 s  . co  m
    if (classloader != null) {
        schema = factory.newSchema(classloader.getResource(DMN_XSD));
    }

    if (schema == null) {
        schema = factory.newSchema(DmnXMLConverter.class.getClassLoader().getResource(DMN_XSD));
    }

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

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

/**
 * Unmarshalls the Audit model from a stream.
 */// ww w.  j a  v  a  2 s .co 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.ValidationParser.java

static Schema getSchema(final String xsd) {
    final Schema schema = SCHEMA_CACHE.get(xsd);
    if (schema != null) {
        return schema;
    }//from   w w  w  . j  av a 2  s .  com

    final ClassLoader loader = Reflection.getClassLoader(ValidationParser.class);
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final URL schemaUrl = loader.getResource(xsd);
    try {
        Schema s = sf.newSchema(schemaUrl);
        final Schema old = SCHEMA_CACHE.putIfAbsent(xsd, s);
        if (old != null) {
            s = old;
        }
        return s;
    } catch (SAXException e) {
        log.log(Level.WARNING, String.format("Unable to parse schema: %s", xsd), e);
        return null;
    }
}

From source file:org.apache.maven.plugin.changes.schema.DefaultChangesSchemaValidator.java

/**
 * @param uriSchema/*from   w  ww. j a va 2 s  .co m*/
 * @return Schema
 * @throws Exception
 */
private Schema compileJAXPSchema(String uriSchema) throws SAXException, NullPointerException {

    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(uriSchema);

    if (is == null) {
        throw new NullPointerException(" impossible to load schema with path " + uriSchema);
    }

    try {
        //newInstance de SchemaFactory not ThreadSafe
        return SchemaFactory.newInstance(W3C_XML_SCHEMA).newSchema(new StreamSource(is));
    } finally {
        IOUtil.close(is);
    }
}