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:com.mymita.vaadlets.JAXBUtils.java

private static final Vaadlets unmarshal(final Reader aReader, final Resource theSchemaResource) {
    try {//from ww w  .j  a v  a  2 s.  com
        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.indivica.olis.Driver.java

public static void readResponseFromXML(HttpServletRequest request, String olisResponse) {

    olisResponse = olisResponse.replaceAll("<Content", "<Content xmlns=\"\" ");
    olisResponse = olisResponse.replaceAll("<Errors", "<Errors xmlns=\"\" ");

    try {//from   w  ww .ja  va  2 s .c  o m
        DocumentBuilderFactory.newInstance().newDocumentBuilder();
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        Source schemaFile = new StreamSource(
                new File(OscarProperties.getInstance().getProperty("olis_response_schema")));
        factory.newSchema(schemaFile);

        JAXBContext jc = JAXBContext.newInstance("ca.ssha._2005.hial");
        Unmarshaller u = jc.createUnmarshaller();
        @SuppressWarnings("unchecked")
        Response root = ((JAXBElement<Response>) u.unmarshal(new InputSource(new StringReader(olisResponse))))
                .getValue();

        if (root.getErrors() != null) {
            List<String> errorStringList = new LinkedList<String>();

            // Read all the errors
            ArrayOfError errors = root.getErrors();
            List<ca.ssha._2005.hial.Error> errorList = errors.getError();

            for (ca.ssha._2005.hial.Error error : errorList) {
                String errorString = "";
                errorString += "ERROR " + error.getNumber() + " (" + error.getSeverity() + ") : "
                        + error.getMessage();
                MiscUtils.getLogger().debug(errorString);

                ArrayOfString details = error.getDetails();
                if (details != null) {
                    List<String> detailList = details.getString();
                    for (String detail : detailList) {
                        errorString += "\n" + detail;
                    }
                }

                errorStringList.add(errorString);
            }
            if (request != null)
                request.setAttribute("errors", errorStringList);
        } else if (root.getContent() != null) {
            if (request != null)
                request.setAttribute("olisResponseContent", root.getContent());
        }
    } catch (Exception e) {
        MiscUtils.getLogger().error("Couldn't read XML from OLIS response.", e);

        LoggedInInfo loggedInInfo = LoggedInInfo.getLoggedInInfoFromSession(request);
        notifyOlisError(loggedInInfo.getLoggedInProvider(), "Couldn't read XML from OLIS response." + "\n" + e);
    }
}

From source file:cz.strmik.cmmitool.cmmi.DefaultRatingScalesProvider.java

private void validateScalesDocument(Document document) throws SAXException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source schemaFile = new StreamSource(getClass().getClassLoader().getResourceAsStream(SCALES_XSD));
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(document));
}

From source file:com.panet.imeta.job.entries.xsdvalidator.JobEntryXSDValidator.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);/*from   www  .j  av a 2s. co  m*/

    String realxmlfilename = getRealxmlfilename();
    String realxsdfilename = getRealxsdfilename();

    FileObject xmlfile = null;
    FileObject xsdfile = null;

    try

    {

        if (xmlfilename != null && xsdfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);
            xsdfile = KettleVFS.getFileObject(realxsdfilename);

            if (xmlfile.exists() && xsdfile.exists()) {

                SchemaFactory factorytXSDValidator_1 = SchemaFactory
                        .newInstance("http://www.w3.org/2001/XMLSchema");

                // Get XSD File
                File XSDFile = new File(KettleVFS.getFilename(xsdfile));
                Schema SchematXSD = factorytXSDValidator_1.newSchema(XSDFile);

                Validator XSDValidator = SchematXSD.newValidator();

                // Get XML File
                File xmlfiletXSDValidator_1 = new File(KettleVFS.getFilename(xmlfile));

                Source sourcetXSDValidator_1 = new StreamSource(xmlfiletXSDValidator_1);

                XSDValidator.validate(sourcetXSDValidator_1);

                // Everything is OK
                result.setResult(true);

            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryXSDValidator.FileDoesNotExist1.Label") + realxmlfilename
                                    + Messages.getString("JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                if (!xsdfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryXSDValidator.FileDoesNotExist1.Label") + realxsdfilename
                                    + Messages.getString("JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryXSDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (SAXException ex) {
        log.logError(toString(), "Error :" + ex.getMessage());
    } catch (Exception e) {

        log.logError(toString(),
                Messages.getString("JobEntryXSDValidator.ErrorXSDValidator.Label")
                        + Messages.getString("JobEntryXSDValidator.ErrorXML1.Label") + realxmlfilename
                        + Messages.getString("JobEntryXSDValidator.ErrorXML2.Label")
                        + Messages.getString("JobEntryXSDValidator.ErrorXSD1.Label") + realxsdfilename
                        + Messages.getString("JobEntryXSDValidator.ErrorXSD2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (xsdfile != null)
                xsdfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml.//from w w  w.j  a v  a 2  s .  c o m
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(InputStream[] inSchemas, InputStream inXml, String schemaLanguage)
        throws MotuException {
    // parse an XML document into a DOM tree
    Document document;
    // create a Validator instance, which can be used to validate an instance document
    Validator validator;
    XMLErrorHandler errorHandler = new XMLErrorHandler();

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        // documentBuilderFactory.setExpandEntityReferences(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        document = documentBuilder.parse(inXml);

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
        schemaFactory.setErrorHandler(errorHandler);

        // load a WXS schema, represented by a Schema instance

        Source[] schemaFiles = new Source[inSchemas.length];

        // InputStream inShema = null;
        int i = 0;
        for (InputStream inSchema : inSchemas) {
            schemaFiles[i] = new StreamSource(inSchema);
            i++;
        }

        Schema schema = schemaFactory.newSchema(schemaFiles);

        validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.validate(new DOMSource(document));

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

From source file:alter.vitro.vgw.service.query.SimpleQueryHandler.java

/**
 *
 * Init method. Required for handling AND responding to queries
 *//*from  w w w.  j  a v a 2  s.  c  o m*/
public void initInstance(String pPeerId, String pPeerName,
        GWCommandMQMessageConsumerProducer gwCommandMQMessageConsumerProducer, WsiAdapterCon myDCon) {
    myPeerId = pPeerId;
    myPeerName = pPeerName;
    myPipeDataProducer = gwCommandMQMessageConsumerProducer.getProducer();
    myPipeDataSession = gwCommandMQMessageConsumerProducer.getSession();

    this.myDCon = myDCon;
    if (schema == null) {
        try {
            schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File(
                    "src/main/java/alter/vitro/vgw/service/query/xmlmessages/aggrquery/PublicQueryAggrMsg.xsd"));
        } catch (SAXException saxEx) {
            logger.error("Exception while initializing schema from PublicQueryAggrMsg.xsd", saxEx);
        }
    }
    if (enDisFromVSPschema == null) {
        try {
            enDisFromVSPschema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                    .newSchema(new File(
                            "src/main/java/alter/vitro/vgw/service/query/xmlmessages/enablednodessynch/fromvsp/fromvsp.xsd"));
        } catch (SAXException saxEx) {
            logger.error("Exception while initializing schema  (enable synch) from fromvsp.xsd", saxEx);
        }
    }
    if (equivSynchFromVSPschema == null) {
        try {
            equivSynchFromVSPschema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                    .newSchema(new File(
                            "src/main/java/alter/vitro/vgw/service/query/xmlmessages/equivlistsynch/fromvsp/fromvsp.xsd"));
        } catch (SAXException saxEx) {
            logger.error("Exception while initializing schema (equiv list synch) from fromvsp.xsd", saxEx);
        }
    }
}

From source file:de.drv.dsrv.spoc.web.webservice.jax.ExtraSchemaValidationHandler.java

private void validateExtraRequest(final Node transportNode, final ServletContext servletContext)
        throws Exception {

    // Validator-Objekt mit eXTra-Schema als Basis erstellen
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = factory.newSchema(servletContext.getResource(SCHEMA_PATH));
    final Validator validator = schema.newValidator();

    try {/*from   w w w .j a  v  a2s .c om*/
        // Validiere Transport-Element gegen eXTra-Schema
        validator.validate(new DOMSource(transportNode));
    } catch (final SAXException e) {
        // Falls MTOM-Attachement, dann den Fehler bzgl. cid-Referenz
        // ignorieren
        if (!(e.getMessage().contains("cid:") && e.getMessage().contains("'base64Binary'"))) {
            LOG.warn("Fehler bei der XML-Validierung: " + e.getMessage());
            throw new InvalidExtraRequestException(e.getMessage());
        }
    }
}

From source file:admincommands.Reload.java

private Schema getSchema(String xml_schema) {
    Schema schema = null;/* w ww .  j  a  v a  2s.  co m*/
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    try {
        schema = sf.newSchema(new File(xml_schema));
    } catch (SAXException saxe) {
        throw new Error("Error while getting schema", saxe);
    }

    return schema;
}

From source file:cz.cas.lib.proarc.common.imports.TiffImporterTest.java

@Test
public void testConsume() throws Exception {
    temp.setDeleteOnExit(true);//ww w. j  av a2s  . c  o m
    File targetFolder = ImportProcess.createTargetFolder(temp.getRoot());
    assertTrue(targetFolder.exists());

    String mimetype = ImportProcess.findMimeType(tiff1);
    assertNotNull(mimetype);

    ImportOptions ctx = new ImportOptions(tiff1.getParentFile(), "scanner:scanner1", true, junit,
            config.getImportConfiguration());
    ctx.setTargetFolder(targetFolder);
    Batch batch = new Batch();
    batch.setId(1);
    batch.setFolder(ibm.relativizeBatchFile(tiff1.getParentFile()));
    ctx.setBatch(batch);
    FileSet fileSet = ImportFileScanner.getFileSets(Arrays.asList(tiff1, ocr1, alto1, ac1, uc1)).get(0);
    ctx.setJhoveContext(jhoveContext);

    TiffImporter instance = new TiffImporter(ibm);
    BatchItemObject result = instance.consume(fileSet, ctx);
    String pid = result.getPid();
    assertTrue(pid.startsWith("uuid"));

    assertEquals(ObjectState.LOADED, result.getState());

    File foxml = result.getFile();
    assertTrue(foxml.toString(), foxml.exists());

    File rootFoxml = new File(foxml.getParent(), ImportBatchManager.ROOT_ITEM_FILENAME);
    assertTrue(rootFoxml.toString(), rootFoxml.exists());

    File raw1 = new File(targetFolder, "img1.full.jpg");
    assertTrue(raw1.exists() && raw1.length() > 0);

    File preview1 = new File(targetFolder, "img1.preview.jpg");
    assertTrue(preview1.exists() && preview1.length() > 0);

    File thumb1 = new File(targetFolder, "img1.thumb.jpg");
    assertTrue(thumb1.exists() && thumb1.length() > 0);

    // validate FOXML
    SchemaFactory sfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL foxmlXsdUrl = ObjectFactory.class.getResource("/xsd/foxml/foxml1-1.xsd");
    assertNotNull(foxmlXsdUrl);
    Schema foxmlXsd = sfactory.newSchema(foxmlXsdUrl);
    foxmlXsd.newValidator().validate(new StreamSource(foxml));

    // check datastreams with xpath
    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("f", "info:fedora/fedora-system:def/foxml#");
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces));
    String foxmlSystemId = foxml.toURI().toASCIIString();
    XMLAssert.assertXpathExists(streamXPath(ModsStreamEditor.DATASTREAM_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(DcStreamEditor.DATASTREAM_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(StringEditor.OCR_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(AltoDatastream.ALTO_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(RelationEditor.DATASTREAM_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.FULL_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.PREVIEW_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.THUMB_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.RAW_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(MixEditor.RAW_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.NDK_ARCHIVAL_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.NDK_USER_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(MixEditor.NDK_ARCHIVAL_ID), new InputSource(foxmlSystemId));

    String rootSystemId = rootFoxml.toURI().toASCIIString();
    XMLAssert.assertXpathExists(streamXPath(RelationEditor.DATASTREAM_ID), new InputSource(rootSystemId));
    EasyMock.verify(toVerify.toArray());
}

From source file:org.ff4j.console.conf.XmlConfigurationParser.java

/**
 * Mthode permettant de crer le Unmarshaller pour le parsing du XML.
 * @param modelPackage/*from  www. j  av a2  s.co m*/
 *            nom du package qui contient les beans utilises pour le parsing du fichier.
 * @param schemafile
 *            le fichier XSD pour la validation du XML.
 * @return Unmarshaller
 * @throws JAXBException
 * @throws SAXException
 */
public Unmarshaller getUnmarshaller(String modelPackage, InputStream schemaStream)
        throws JAXBException, SAXException {
    JAXBContext jc = JAXBContext.newInstance(modelPackage);
    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new StreamSource(schemaStream));
    Unmarshaller u = jc.createUnmarshaller();
    u.setSchema(schema);
    u.setEventHandler(new XmlConfigurationErrorHandler());
    return u;
}