Example usage for javax.xml.validation Validator setProperty

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

Introduction

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

Prototype

public void setProperty(String name, Object object) throws SAXNotRecognizedException, SAXNotSupportedException 

Source Link

Document

Set the value of a property.

Usage

From source file:ca.uhn.fhir.validation.SchemaBaseValidator.java

private void doValidate(IValidationContext<?> theContext, String schemaName) {
    Schema schema = loadSchema("dstu", schemaName);

    try {/*from   w  ww . j av  a2 s.  c om*/
        Validator validator = schema.newValidator();
        MyErrorHandler handler = new MyErrorHandler(theContext);
        validator.setErrorHandler(handler);
        String encodedResource;
        if (theContext.getResourceAsStringEncoding() == EncodingEnum.XML) {
            encodedResource = theContext.getResourceAsString();
        } else {
            encodedResource = theContext.getFhirContext().newXmlParser()
                    .encodeResourceToString((IBaseResource) theContext.getResource());
        }

        try {
            /*
             * See https://github.com/jamesagnew/hapi-fhir/issues/339
             * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
             */
            validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
            validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
        } catch (SAXNotRecognizedException ex) {
            ourLog.warn("Jaxp 1.5 Support not found.", ex);
        }

        validator.validate(new StreamSource(new StringReader(encodedResource)));
    } catch (SAXParseException e) {
        SingleValidationMessage message = new SingleValidationMessage();
        message.setLocationLine(e.getLineNumber());
        message.setLocationCol(e.getColumnNumber());
        message.setMessage(e.getLocalizedMessage());
        message.setSeverity(ResultSeverityEnum.FATAL);
        theContext.addValidationMessage(message);
    } catch (SAXException e) {
        // Catch all
        throw new ConfigurationException("Could not load/parse schema file", e);
    } catch (IOException e) {
        // Catch all
        throw new ConfigurationException("Could not load/parse schema file", e);
    }
}

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 a va 2 s. com*/
    }

    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:org.mule.module.xml.filters.SchemaValidationFilter.java

/**
 * Create a validator.//from  www  .j a  v a 2 s.co  m
 * 
 * @return The validator.
 */
public Validator createValidator() throws SAXException {
    Validator validator = getSchemaObject().newValidator();

    if (this.validatorFeatures != null) {
        for (Map.Entry<String, Boolean> feature : this.validatorFeatures.entrySet()) {
            validator.setFeature(feature.getKey(), feature.getValue());
        }
    }

    if (this.validatorProperties != null) {
        for (Map.Entry<String, Object> validatorProperty : this.validatorProperties.entrySet()) {
            validator.setProperty(validatorProperty.getKey(), validatorProperty.getValue());
        }
    }

    return validator;
}