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 abstract void validate(Source source, Result result) throws SAXException, IOException;

Source Link

Document

Validates the specified input and send the augmented validation result to the specified output.

Usage

From source file:ValidateStax.java

/**
 * @param args/*from   w w w .  j  ava  2  s.c om*/
 *          the command line arguments
 */
public static void main(String[] args) {
    try {
        // TODO code application logic here
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        System.out.println("schema factory instance obtained is " + sf);

        Schema schema = sf.newSchema(new File(args[0]));
        System.out.println("schema obtained is = " + schema);
        // Get a Validator which can be used to validate instance document against
        // this grammar.
        Validator validator = schema.newValidator();

        // Validate this instance document against the Instance document supplied
        String fileName = args[1].toString();
        String fileName2 = args[2].toString();
        javax.xml.transform.Result xmlResult = new javax.xml.transform.stax.StAXResult(
                XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(fileName2)));
        javax.xml.transform.Source xmlSource = new javax.xml.transform.stax.StAXSource(
                getXMLEventReader(fileName));
        // validator.validate(new StreamSource(args[1]));
        validator.validate(xmlSource, xmlResult);
    } catch (Exception ex) {
        ex.printStackTrace();
        System.out.println("GET CAUSE");
        ex.getCause().fillInStackTrace();
    }
}

From source file:Main.java

public static String validate(String xsdPath, String xmlPath) {
    String response = "OK";

    try {/*from   w ww  .  j a v a2  s  .  co  m*/
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File schemaLocation = new File(xsdPath);
        Schema schema = factory.newSchema(schemaLocation);
        Validator validator = schema.newValidator();
        Source source = new StreamSource(xmlPath);
        Result result = null;
        validator.validate(source, result);
    } catch (Exception e) {
        response = e.getMessage();
    }

    return response;
}

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

/**
 * Implements the EPCIS capture operation. Takes an input stream, extracts
 * the payload into an XML document, validates the document against the
 * EPCIS schema, and captures the EPCIS events given in the document.
 * /*from  w  w w. java 2  s  .  c  o m*/
 * @throws IOException
 *             If an error occurred while validating the request or writing
 *             the response.
 * @throws ParserConfigurationException
 * @throws SAXException
 *             If the XML document is malformed or invalid
 * @throws InvalidFormatException
 */
public void doCapture(InputStream in, Principal principal)
        throws SAXException, IOException, InvalidFormatException {

    // parse the payload as XML document
    Document document;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(in);
        LOG.debug("Payload successfully parsed as XML document");
        if (LOG.isDebugEnabled()) {
            try {
                TransformerFactory tfFactory = TransformerFactory.newInstance();
                Transformer transformer = tfFactory.newTransformer();
                StringWriter writer = new StringWriter();
                transformer.transform(new DOMSource(document), new StreamResult(writer));
                String xml = writer.toString();
                if (xml.length() > 100 * 1024) {
                    // too large, do not log
                    xml = null;
                } else {
                    LOG.debug("Incoming contents:\n\n" + writer.toString() + "\n");
                }
            } catch (Exception e) {
                // never mind ... do not log
            }
        }

        // validate the XML document against the EPCISDocument schema
        if (schema != null) {
            Validator validator = schema.newValidator();
            try {
                validator.validate(new DOMSource(document), null);
            } catch (SAXParseException e) {
                // TODO: we need to ignore XML element order, the following
                // is only a hack to pass some of the conformance tests
                if (e.getMessage().contains("parentID")) {
                    LOG.warn("Ignoring XML validation exception: " + e.getMessage());
                } else {
                    throw e;
                }
            }
            LOG.info("Incoming capture request was successfully validated against the EPCISDocument schema");
        } else {
            LOG.warn("Schema validator unavailable. Unable to validate EPCIS capture event against schema!");
        }

    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    }

    // handle the capture operation
    Session session = null;
    try {
        session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            LOG.debug("DB connection opened.");
            handleDocument(session, document);
            tx.commit();
            // return OK
            LOG.info("EPCIS Capture Interface request succeeded");
        } catch (SAXException e) {
            LOG.error("EPCIS Capture Interface request failed: " + e.toString());
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } catch (InvalidFormatException e) {
            LOG.error("EPCIS Capture Interface request failed: " + e.toString());
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } catch (Exception e) {
            // Hibernate throws RuntimeExceptions, so don't let them
            // (or anything else) escape without clean up
            LOG.error("EPCIS Capture Interface request failed: " + e.toString(), e);
            if (tx != null) {
                tx.rollback();
            }
            throw new IOException(e.toString());
        }
    } finally {
        if (session != null) {
            session.close();
        }
        // sessionFactory.getStatistics().logSummary();
        LOG.debug("DB connection closed");
    }
}

From source file:org.rimudb.configuration.AbstractXmlLoader.java

/**
 * @param document/*from w ww. jav  a 2  s  . com*/
 * @param compoundDbSchemaUrl
 * @return SAXParseException
 * @throws Exception 
 */
protected SAXParseException validate(Document document, String compoundDbSchemaUrl) throws Exception {
    // Compile a schema for the XSD
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // Look up the schema URL and find it's local resource file 
    URL schemaURL = null;
    String schemaPath = RimuDBNamespace.lookupInternalSchema(compoundDbSchemaUrl);
    if (schemaPath != null) {
        schemaURL = getClass().getClassLoader().getResource(schemaPath);
    } else {
        schemaURL = new URL(compoundDbSchemaUrl);
    }

    Schema schema = schemaFactory.newSchema(schemaURL);

    // Validate the document against the schema
    Validator validator = schema.newValidator();
    validator.setErrorHandler(new StrictErrorHandler());
    try {
        validator.validate(new DOMSource(document), new DOMResult());
    } catch (SAXParseException e) {
        return e;
    }

    return null;
}

From source file:org.wso2.carbon.identity.entitlement.EntitlementUtil.java

/**
 * Validates the given policy XML files against the standard XACML policies.
 *
 * @param policy Policy to validate/*from ww w  . j ava 2s. c o m*/
 * @return return false, If validation failed or XML parsing failed or any IOException occurs
 */
public static boolean validatePolicy(PolicyDTO policy) {
    try {

        if (!"true".equalsIgnoreCase((String) EntitlementServiceComponent.getEntitlementConfig()
                .getEngineProperties().get(EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION))) {
            return true;
        }

        // there may be cases where you only updated the policy meta data in PolicyDTO not the
        // actual XACML policy String
        if (policy.getPolicy() == null || policy.getPolicy().trim().length() < 1) {
            return true;
        }

        //get policy version
        String policyXMLNS = getPolicyVersion(policy.getPolicy());

        Map<String, Schema> schemaMap = EntitlementServiceComponent.getEntitlementConfig().getPolicySchemaMap();
        //load correct schema by version
        Schema schema = schemaMap.get(policyXMLNS);

        if (schema != null) {
            //build XML document
            DocumentBuilder documentBuilder = getSecuredDocumentBuilder(false);
            InputStream stream = new ByteArrayInputStream(policy.getPolicy().getBytes());
            Document doc = documentBuilder.parse(stream);
            //Do the DOM validation
            DOMSource domSource = new DOMSource(doc);
            DOMResult domResult = new DOMResult();
            Validator validator = schema.newValidator();
            validator.validate(domSource, domResult);
            if (log.isDebugEnabled()) {
                log.debug("XACML Policy validation succeeded with the Schema");
            }
            return true;
        } else {
            log.error("Invalid Namespace in policy");
        }
    } catch (SAXException e) {
        log.error("XACML policy is not valid according to the schema :" + e.getMessage());
    } catch (IOException e) {
        //ignore
    } catch (ParserConfigurationException e) {
        //ignore
    }
    return false;
}