Example usage for javax.xml.validation SchemaFactory setErrorHandler

List of usage examples for javax.xml.validation SchemaFactory setErrorHandler

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory setErrorHandler.

Prototype

public abstract void setErrorHandler(ErrorHandler errorHandler);

Source Link

Document

Sets the ErrorHandler to receive errors encountered during the newSchema method invocation.

Usage

From source file:TypeInfoWriter.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from   w  ww.java2 s.  c  o  m
        System.exit(1);
    }

    // variables
    XMLReader parser = null;
    Vector schemas = null;
    Vector instances = null;
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;

    // process arguments
    for (int i = 0; i < argv.length; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                    continue;
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                        System.exit(1);
                    }
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: schema documents
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    // use default parser?
    if (parser == null) {
        // create parser
        try {
            parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
        } catch (Exception e) {
            System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
            e.printStackTrace(System.err);
            System.exit(1);
        }
    }

    try {
        // Create writer
        TypeInfoWriter writer = new TypeInfoWriter();
        writer.setOutput(System.out, "UTF8");

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(writer);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        if (schemas != null && schemas.size() > 0) {
            final int length = schemas.size();
            StreamSource[] sources = new StreamSource[length];
            for (int j = 0; j < length; ++j) {
                sources[j] = new StreamSource((String) schemas.elementAt(j));
            }
            schema = factory.newSchema(sources);
        } else {
            schema = factory.newSchema();
        }

        // Setup validator and parser
        ValidatorHandler validator = schema.newValidatorHandler();
        parser.setContentHandler(validator);
        if (validator instanceof DTDHandler) {
            parser.setDTDHandler((DTDHandler) validator);
        }
        parser.setErrorHandler(writer);
        validator.setContentHandler(writer);
        validator.setErrorHandler(writer);
        writer.setTypeInfoProvider(validator.getTypeInfoProvider());

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents and print type information
        if (instances != null && instances.size() > 0) {
            final int length = instances.size();
            for (int j = 0; j < length; ++j) {
                parser.parse((String) instances.elementAt(j));
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:InlineSchemaValidator.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();// w  ww. j  a va  2  s . c  o  m
        System.exit(1);
    }

    // variables
    Vector schemas = null;
    Vector instances = null;
    HashMap prefixMappings = null;
    HashMap uriMappings = null;
    String docURI = argv[argv.length - 1];
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    int repetition = DEFAULT_REPETITION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean memoryUsage = DEFAULT_MEMORY_USAGE;

    // process arguments
    for (int i = 0; i < argv.length - 1; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: xpath expressions for schemas
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: xpath expressions for instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-nm")) {
                String prefix;
                String uri;
                while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-")
                        && !(uri = argv[i + 2]).startsWith("-")) {
                    if (prefixMappings == null) {
                        prefixMappings = new HashMap();
                        uriMappings = new HashMap();
                    }
                    prefixMappings.put(prefix, uri);
                    HashSet prefixes = (HashSet) uriMappings.get(uri);
                    if (prefixes == null) {
                        prefixes = new HashSet();
                        uriMappings.put(uri, prefixes);
                    }
                    prefixes.add(prefix);
                    i += 2;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("m")) {
                memoryUsage = option.equals("m");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    try {
        // Create new instance of inline schema validator.
        InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings);

        // Parse document containing schemas and validation roots
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(inlineSchemaValidator);
        Document doc = db.parse(docURI);

        // Create XPath factory for selecting schema and validation roots
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        xpath.setNamespaceContext(inlineSchemaValidator);

        // Select schema roots from the DOM
        NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0];
        for (int i = 0; i < schemaNodes.length; ++i) {
            XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i));
            schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET);
        }

        // Select validation roots from the DOM
        NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0];
        for (int i = 0; i < instanceNodes.length; ++i) {
            XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i));
            instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET);
        }

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(inlineSchemaValidator);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        {
            DOMSource[] sources;
            int size = 0;
            for (int i = 0; i < schemaNodes.length; ++i) {
                size += schemaNodes[i].getLength();
            }
            sources = new DOMSource[size];
            if (size == 0) {
                schema = factory.newSchema();
            } else {
                int count = 0;
                for (int i = 0; i < schemaNodes.length; ++i) {
                    NodeList nodeList = schemaNodes[i];
                    int nodeListLength = nodeList.getLength();
                    for (int j = 0; j < nodeListLength; ++j) {
                        sources[count++] = new DOMSource(nodeList.item(j));
                    }
                }
                schema = factory.newSchema(sources);
            }
        }

        // Setup validator and input source.
        Validator validator = schema.newValidator();
        validator.setErrorHandler(inlineSchemaValidator);

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents
        for (int i = 0; i < instanceNodes.length; ++i) {
            NodeList nodeList = instanceNodes[i];
            int nodeListLength = nodeList.getLength();
            for (int j = 0; j < nodeListLength; ++j) {
                DOMSource source = new DOMSource(nodeList.item(j));
                source.setSystemId(docURI);
                inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage);
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:edu.lternet.pasta.common.XmlUtility.java

/**
 * Returns the provided XML string as a schema.
 *
 * @param xmlString an XML schema./*from  w  ww .j  a v a  2s .c  o m*/
 *
 * @return a schema object that corresponds to the provided string.
 */
public static Schema xmlStringToSchema(String xmlString) {

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setErrorHandler(new XmlParsingErrorHandler(xmlString));

    StreamSource source = new StreamSource(new StringReader(xmlString));

    try {
        return factory.newSchema(source);
    } catch (SAXException e) {
        throw new IllegalStateException(e); // shouldn't be reached
    }
}

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

/**
 * Validate xml.//www. ja  va 2 s. c  om
 * 
 * @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:nl.armatiek.xslweb.configuration.WebApp.java

public Schema trySchemaCache(Collection<String> schemaPaths, ErrorListener errorListener) throws Exception {
    String key = StringUtils.join(schemaPaths, ";");
    Schema schema = schemaCache.get(key);
    if (schema == null) {
        logger.info("Compiling and caching schema(s) \"" + key + "\" ...");
        try {/*from  ww w .  j a  va 2  s .co m*/
            ArrayList<Source> schemaSources = new ArrayList<Source>();
            for (String path : schemaPaths) {
                File file = new File(path);
                if (!file.isFile()) {
                    throw new FileNotFoundException(
                            "XML Schema file \"" + file.getAbsolutePath() + "\" not found");
                }
                schemaSources.add(new StreamSource(file));
            }
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setErrorHandler(new ValidatorErrorHandler("Schema file(s)"));
            schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        } catch (Exception e) {
            logger.error("Error compiling schema(s) \"" + key + "\"", e);
            throw e;
        }
        if (!developmentMode) {
            schemaCache.put(key, schema);
        }
    }
    return schema;
}

From source file:org.apache.synapse.mediators.validate.ValidateMediator.java

/**
 * Perform actual initialization of this validate mediator instance - if required
 *///from w ww . j a v a  2  s .  c  om
private void initialize(MessageContext msgCtx) {

    // flag to check if we need to initialize/re-initialize the schema Validator
    boolean reCreate = false;

    // if any of the schemas are not loaded or expired, load or re-load them
    Iterator iter = schemaKeys.iterator();
    while (iter.hasNext()) {
        String propKey = (String) iter.next();
        Property dp = msgCtx.getConfiguration().getPropertyObject(propKey);
        if (dp != null && dp.isDynamic()) {
            if (!dp.isCached() || dp.isExpired()) {
                reCreate = true; // request re-initialization of Validator
            }
        }
    }

    // do not re-initialize Validator unless required
    if (!reCreate && validator != null) {
        return;
    }

    try {
        // Create SchemaFactory and configure for the default schema language - XMLSchema
        SchemaFactory factory = SchemaFactory.newInstance(DEFAULT_SCHEMA_LANGUAGE);
        factory.setErrorHandler(errorHandler);

        // set any features on/off as requested
        iter = properties.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String value = (String) entry.getValue();
            factory.setFeature((String) entry.getKey(), value != null && "true".equals(value));
        }

        Schema schema = null;

        StreamSource[] sources = new StreamSource[schemaKeys.size()];
        iter = schemaKeys.iterator();
        int i = 0;
        while (iter.hasNext()) {
            String propName = (String) iter.next();
            sources[i++] = Util.getStreamSource(msgCtx.getConfiguration().getProperty(propName));
        }
        schema = factory.newSchema(sources);

        // Setup validator and input source
        // Features set for the SchemaFactory get propagated to Schema and Validator (JAXP 1.4)
        validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);

    } catch (SAXException e) {
        handleException("Error creating Validator", e);
    }
}

From source file:org.jboss.cdi.tck.test.shrinkwrap.descriptors.ejb.EjbJarDescriptorBuilderTest.java

@Test
public void testDescriptorIsValid()
        throws ParserConfigurationException, SAXException, DescriptorExportException, IOException {

    EjbJarDescriptor ejbJarDescriptor = new EjbJarDescriptorBuilder().messageDrivenBeans(
            newMessageDriven("TestQueue", QueueMessageDrivenBean.class.getName())
                    .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge")
                    .addActivationConfigProperty("destinationType", "javax.jms.Queue")
                    .addActivationConfigProperty("destinationLookup", "test_queue"),
            newMessageDriven("TestTopic", TopicMessageDrivenBean.class.getName())
                    .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge")
                    .addActivationConfigProperty("destinationType", "javax.jms.Topic")
                    .addActivationConfigProperty("destinationLookup", "test_topic"))
            .build();//from  w w w.ja  va2  s  .c o  m

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LSResourceResolver() {

        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            try {
                if (systemId.startsWith("http")) {
                    // Ugly workaround for xml.xsd
                    systemId = StringUtils.substringAfterLast(systemId, "/");
                }
                return new Input(publicId, systemId,
                        new FileInputStream(new File("src/test/resources/xsd", systemId)));
            } catch (FileNotFoundException e) {
                throw new IllegalStateException();
            }
        }
    });
    schemaFactory.setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            throw exception;
        }
    });

    Source schemaFile = new StreamSource(
            new FileInputStream(new File("src/test/resources/xsd", "ejb-jar_3_1.xsd")));
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator
            .validate(new StreamSource(new ByteArrayInputStream(ejbJarDescriptor.exportAsString().getBytes())));
}

From source file:org.mifos.framework.components.mifosmenu.MenuParser.java

/**
 * Method to parse xml and return crude menu
 *
 * @return array of crude Menu objects//from www.ja  v  a  2s . com
 */
public static Menu[] parse() throws SystemException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        SchemaFactory schfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schfactory.setErrorHandler(null);
        Schema schema = schfactory.newSchema(
                new StreamSource(MifosResourceUtil.getClassPathResourceAsStream(FilePaths.MENUSCHEMA)));
        factory.setNamespaceAware(false);
        factory.setValidating(false);
        factory.setSchema(schema);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(MifosResourceUtil.getClassPathResourceAsStream(FilePaths.MENUPATH));
        NodeList tabNodeList = document.getElementsByTagName(MenuConstants.TOPMENUTAB);
        Menu leftMenus[] = new Menu[tabNodeList.getLength()];
        for (int i = 0; i < tabNodeList.getLength(); i++) {
            leftMenus[i] = new Menu();
            leftMenus[i].setTopMenuTabName(((Element) tabNodeList.item(i)).getAttribute(MenuConstants.NAME));
            leftMenus[i].setMenuGroups(createMenuGroup(tabNodeList.item(i)));
            String menuHeading = ((Element) tabNodeList.item(i))
                    .getElementsByTagName(MenuConstants.LEFTMENULABEL).item(0).getFirstChild().getTextContent()
                    .trim();
            leftMenus[i].setMenuHeading(menuHeading);
        }
        return leftMenus;
    } catch (SAXParseException spe) {
        throw new MenuParseException(spe);
    } catch (SAXException sxe) {
        throw new MenuParseException(sxe);
    } catch (ParserConfigurationException pce) {
        throw new MenuParseException(pce);
    } catch (IOException ioe) {
        throw new MenuParseException(ioe);
    }
}

From source file:org.mule.module.xml.filters.SchemaValidationFilter.java

public void initialise() throws InitialisationException {
    super.initialise();

    if (getSchemaObject() == null) {
        if (schemaLocations == null) {
            throw new InitialisationException(CoreMessages.objectIsNull("schemaLocations"), this);
        }//  w  w w.  j av a2 s  .  c om

        String[] split = StringUtils.splitAndTrim(schemaLocations, ",");
        Source[] schemas = new Source[split.length];
        for (int i = 0; i < split.length; i++) {
            String loc = split[i];
            InputStream schemaStream;
            try {
                schemaStream = loadSchemaStream(loc);
            } catch (IOException e) {
                throw new InitialisationException(e, this);
            }

            if (schemaStream == null) {
                throw new InitialisationException(CoreMessages.failedToLoad(loc), this);
            }

            schemas[i] = new StreamSource(schemaStream);
        }

        SchemaFactory schemaFactory = SchemaFactory.newInstance(getSchemaLanguage());

        if (logger.isInfoEnabled()) {
            logger.info("Schema factory implementation: " + schemaFactory);
        }

        if (this.errorHandler != null) {
            schemaFactory.setErrorHandler(this.errorHandler);
        }

        if (this.resourceResolver != null) {
            schemaFactory.setResourceResolver(this.resourceResolver);
        }

        Schema schema;
        try {
            schema = schemaFactory.newSchema(schemas);
        } catch (SAXException e) {
            throw new InitialisationException(e, this);
        }

        setSchemaObject(schema);
    }

    if (getSchemaObject() == null) {
        throw new InitialisationException(CoreMessages.objectIsNull("schemaObject"), this);
    }
}

From source file:org.tinygroup.jspengine.xmlparser.ParserUtils.java

private static Schema getSchema(String schemaPublicId) throws SAXException {

    Schema schema = schemaCache.get(schemaPublicId);
    if (schema == null) {
        synchronized (schemaCache) {
            schema = schemaCache.get(schemaPublicId);
            if (schema == null) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                schemaFactory.setResourceResolver(new MyLSResourceResolver());
                schemaFactory.setErrorHandler(new MyErrorHandler());
                schema = schemaFactory.newSchema(new StreamSource(
                        ParserUtils.class.getResourceAsStream(schemaResourcePrefix + schemaPublicId)));
                schemaCache.put(schemaPublicId, schema);
            }//from   w  w  w.jav a  2s .c om
        }
    }

    return schema;
}