Example usage for javax.xml.validation Validator validate

List of usage examples for javax.xml.validation Validator validate

Introduction

In this page you can find the example usage for javax.xml.validation Validator validate.

Prototype

public void validate(Source source) throws SAXException, IOException 

Source Link

Document

Validates the specified input.

Usage

From source file:nl.b3p.wms.capabilities.WMSCapabilitiesReader.java

/** Private method which validates a XML document at a given location.
 *
 * @param location String representing the location where the document can be found.
 *
 * @throws IOException/*from   w  w w  .ja  va  2 s . co  m*/
 * @throws SAXException
 */
// <editor-fold defaultstate="" desc="validate(String location) method.">
private void validate(String location) throws IOException, SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(SCHEMA_FACTORY);
    File schemaLocation = new File(SCHEMA_FILE);
    Schema schema = factory.newSchema(schemaLocation);
    Validator validator = schema.newValidator();

    Source source = new StreamSource(new File(location));
    validator.validate(source);
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.ELTSchemaGridWidget.java

private boolean validateXML(InputStream xml, InputStream xsd) {
    try {/*from  www . ja  v  a2 s  . c om*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();

        validator.validate(new StreamSource(xml));
        return true;
    } catch (SAXException | IOException ex) {
        //MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
        MessageBox dialog = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_ERROR | SWT.OK);
        dialog.setText(Messages.ERROR);
        dialog.setMessage(Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
        logger.error(Messages.IMPORT_XML_FORMAT_ERROR);
        return false;
    }
}

From source file:de.escidoc.core.common.util.xml.XmlUtility.java

/**
 * Validates the provided XML data using the specified schema.<br> The provided {@code ByteArrayInputStream} is
 * reset after validation./*from  w w  w . j  av  a  2s .  com*/
 *
 * @param byteArrayInputStream The XML data to validate in an {@code ByteArrayInputStream}.<br> This input
 *                             stream is reset after the validation.
 * @param schemaUri            The URL identifying the schema that shall be used for validation.
 * @throws XmlCorruptedException        Thrown if the XML data cannot be parsed.
 * @throws XmlSchemaValidationException Thrown if both validation fail or only one validation is executed and fails
 * @throws WebserverSystemException     Thrown in any other case.
 */
public void validate(final ByteArrayInputStream byteArrayInputStream, final String schemaUri)
        throws XmlCorruptedException, XmlSchemaValidationException, WebserverSystemException {

    try {
        final Validator validator = getSchema(schemaUri).newValidator();
        validator.validate(new SAXSource(new InputSource(byteArrayInputStream)));
    } catch (final SAXParseException e) {
        final String errorMsg = "Error in line " + e.getLineNumber() + ", column " + e.getColumnNumber() + ". "
                + e.getMessage();
        if (e.getMessage().startsWith("cvc")) {
            throw new XmlSchemaValidationException(errorMsg, e);
        } else {
            throw new XmlCorruptedException(errorMsg, e);
        }
    } catch (final Exception e) {
        throw new WebserverSystemException(e.getMessage(), e);
    } finally {
        if (byteArrayInputStream != null) {
            byteArrayInputStream.reset();
        }
    }
}

From source file:module.signature.util.XAdESValidator.java

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature/*from  w ww.  java 2  s  . c  o  m*/
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java

private static boolean validateXML(File configFile, InputStream xsdFile) throws IOException {
    Source schemaFile = new StreamSource(xsdFile);
    Source xmlFile = new StreamSource(configFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    try {//w  ww  .j  av a2 s . c om

        Schema schema = schemaFactory.newSchema(schemaFile);
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
        return true;
        //System.out.println(xmlFile.getSystemId() + " is valid");
    } catch (SAXException e) {
        //System.out.println(xmlFile.getSystemId() + " is NOT valid");
        //System.out.println("Reason: " + e.getLocalizedMessage());
        return false;
    }
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Assert the provided XML data is valid against the provided schema.
 * /*from www .j  ava 2 s  .  co m*/
 * @param xmlData
 *            The xml data to be asserted.
 * @param schema
 *            The schema.
 * @throws Exception
 *             If anything fails.
 */
public static void assertXmlValid(final String xmlData, final Schema schema) throws Exception {

    assertNotNull("No Xml data. ", xmlData);
    try {
        Validator validator = schema.newValidator();
        InputStream in = new ByteArrayInputStream(xmlData.getBytes(DEFAULT_CHARSET));
        validator.validate(new SAXSource(new InputSource(in)));
    } catch (final Exception e) {
        final StringBuffer errorMsg = new StringBuffer("XML invalid. ");
        errorMsg.append(e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            errorMsg.append(xmlData);
            errorMsg.append("============ End of invalid xml ============\n");
        }
        fail(errorMsg.toString());
    }
    assertXmlPrefixNotDeclared(xmlData);
}

From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java

private void executeRequest(WebApp webApp, HttpServletRequest req, HttpServletResponse resp,
        OutputStream respOs) throws Exception {
    boolean developmentMode = webApp.getDevelopmentMode();

    String requestXML = (String) req.getAttribute(Definitions.ATTRNAME_REQUESTXML);

    PipelineHandler pipelineHandler = (PipelineHandler) req.getAttribute(Definitions.ATTRNAME_PIPELINEHANDLER);

    ErrorListener errorListener = new TransformationErrorListener(resp, developmentMode);
    MessageWarner messageWarner = new MessageWarner();

    List<PipelineStep> steps = pipelineHandler.getPipelineSteps();
    if (steps == null || steps.isEmpty()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found");
        return;//w ww.j  ava  2s.  c  om
    }

    OutputStream os = (developmentMode) ? new ByteArrayOutputStream() : respOs;

    Properties outputProperties = getOutputProperties(webApp, errorListener, steps);

    Map<QName, XdmValue> baseStylesheetParameters = XSLWebUtils.getStylesheetParameters(webApp, req, resp,
            homeDir);

    addResponseTransformationStep(steps);

    Map<QName, XdmValue> extraStylesheetParameters = null;
    Source source = new StreamSource(new StringReader(requestXML));
    Destination destination = null;

    for (int i = 0; i < steps.size(); i++) {
        PipelineStep step = steps.get(i);
        if (step instanceof SerializerStep) {
            break;
        }
        PipelineStep nextStep = (i < steps.size() - 1) ? steps.get(i + 1) : null;
        if (step instanceof TransformerStep) {
            String xslPath = null;
            if (step instanceof SystemTransformerStep) {
                xslPath = new File(homeDir, "common/xsl/" + ((TransformerStep) step).getXslPath())
                        .getAbsolutePath();
            } else {
                xslPath = ((TransformerStep) step).getXslPath();
            }
            XsltExecutable templates = webApp.getTemplates(xslPath, errorListener);
            Xslt30Transformer transformer = templates.load30();
            transformer.getUnderlyingController().setMessageEmitter(messageWarner);
            transformer.setErrorListener(errorListener);
            Map<QName, XdmValue> stylesheetParameters = new HashMap<QName, XdmValue>();
            stylesheetParameters.putAll(baseStylesheetParameters);
            XSLWebUtils.addStylesheetParameters(stylesheetParameters, ((TransformerStep) step).getParameters());
            if (extraStylesheetParameters != null) {
                stylesheetParameters.putAll(extraStylesheetParameters);
                extraStylesheetParameters.clear();
            }
            transformer.setStylesheetParameters(stylesheetParameters);
            destination = getDestination(webApp, req, resp, os, outputProperties, step, nextStep);
            transformer.applyTemplates(source, destination);
        } else if (step instanceof SchemaValidatorStep) {
            SchemaValidatorStep svStep = (SchemaValidatorStep) step;
            List<String> schemaPaths = svStep.getSchemaPaths();
            Schema schema = webApp.getSchema(schemaPaths, errorListener);

            source = makeNodeInfoSource(source, webApp, errorListener);
            destination = null;

            Serializer serializer = webApp.getProcessor().newSerializer();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            serializer.setOutputStream(outputStream);
            serializer.setOutputProperty(Property.INDENT, "yes");
            serializer.serializeNode(new XdmNode((NodeInfo) source));
            Source validationSource = new StreamSource(new ByteArrayInputStream(outputStream.toByteArray()));

            Validator validator = schema.newValidator();
            ValidatorErrorHandler errorHandler = new ValidatorErrorHandler(
                    "Step: " + ((step.getName() != null) ? step.getName() : "noname"));
            validator.setErrorHandler(errorHandler);

            Properties properties = svStep.getProperties();
            if (properties != null) {
                @SuppressWarnings("rawtypes")
                Enumeration names = properties.propertyNames();
                while (names.hasMoreElements()) {
                    String name = (String) names.nextElement();
                    validator.setProperty(name, properties.getProperty(name));
                }
            }

            Properties features = svStep.getProperties();
            if (features != null) {
                @SuppressWarnings("rawtypes")
                Enumeration names = features.propertyNames();
                while (names.hasMoreElements()) {
                    String name = (String) names.nextElement();
                    validator.setProperty(name, features.getProperty(name));
                }
            }

            validator.validate(validationSource);

            Source resultsSource = errorHandler.getValidationResults();
            if (resultsSource != null) {
                NodeInfo resultsNodeInfo = webApp.getConfiguration().buildDocumentTree(resultsSource)
                        .getRootNode();
                String xslParamName = svStep.getXslParamName();
                if (xslParamName != null) {
                    if (extraStylesheetParameters == null) {
                        extraStylesheetParameters = new HashMap<QName, XdmValue>();
                    }
                    extraStylesheetParameters.put(new QName(svStep.getXslParamNamespace(), xslParamName),
                            new XdmNode(resultsNodeInfo));
                }
            }
        } else if (step instanceof SchematronValidatorStep) {
            SchematronValidatorStep svStep = (SchematronValidatorStep) step;

            source = makeNodeInfoSource(source, webApp, errorListener);
            destination = null;

            /* Execute schematron validation */
            XsltExecutable templates = webApp.getSchematron(svStep.getSchematronPath(), svStep.getPhase(),
                    errorListener);
            Xslt30Transformer transformer = templates.load30();
            transformer.getUnderlyingController().setMessageEmitter(messageWarner);
            transformer.setErrorListener(errorListener);
            XdmDestination svrlDest = new XdmDestination();

            transformer.applyTemplates(source, svrlDest);

            String xslParamName = svStep.getXslParamName();
            if (xslParamName != null) {
                if (extraStylesheetParameters == null) {
                    extraStylesheetParameters = new HashMap<QName, XdmValue>();
                }
                extraStylesheetParameters.put(new QName(svStep.getXslParamNamespace(), xslParamName),
                        svrlDest.getXdmNode());
            }
        } else if (step instanceof ResponseStep) {
            source = new StreamSource(new StringReader(((ResponseStep) step).getResponse()));
            continue;
        }

        if (destination instanceof SourceDestination) {
            /* Set source for next pipeline step: */
            source = ((SourceDestination) destination).asSource();
        }
    }

    if (developmentMode) {
        byte[] body = ((ByteArrayOutputStream) os).toByteArray();
        IOUtils.copy(new ByteArrayInputStream(body), respOs);
    }
}

From source file:nl.clockwork.mule.common.filter.AbstractXSDValidationFilter.java

@Override
public boolean accept(MuleMessage message) {
    try {//from   w ww .j  av  a  2s. c o  m
        String content = getContent(message);
        Validator validator = schema.newValidator();
        //quick fix for synchronization problem with validate() method
        synchronized (this) {
            //validator.validate(new SAXSource(new InputSource(new StringReader(content))));
            validator.validate(new StreamSource(new StringReader(content)));
        }
        return true;
    } catch (SAXException e) {
        logger.info("", e);
        return false;
    } catch (IOException e) {
        logger.error("", e);
        return false;
    } catch (Exception e) {
        logger.warn("", e);
        return false;
    }
}

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

public void validateModel(InputStreamProvider inputStreamProvider) throws Exception {
    Schema schema = createSchema();

    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(inputStreamProvider.getInputStream()));
}

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

public void validateModel(XMLStreamReader xmlStreamReader) throws Exception {
    Schema schema = createSchema();

    Validator validator = schema.newValidator();
    validator.validate(new StAXSource(xmlStreamReader));
}