Example usage for org.xml.sax InputSource setSystemId

List of usage examples for org.xml.sax InputSource setSystemId

Introduction

In this page you can find the example usage for org.xml.sax InputSource setSystemId.

Prototype

public void setSystemId(String systemId) 

Source Link

Document

Set the system identifier for this input source.

Usage

From source file:cl.utfsm.cdbChecker.CDBChecker.java

/**
 * This method validates the XSD files./*from   w  ww. j av  a2s.  c o m*/
 * 
 * @param xsdFilenames names with absolute path of the XSD file to validate.
 */
protected void validateSchemas(Vector<String> xsdFilenames) {

    System.out.println("*** Will verify XSD files in: " + this.XSDPath);

    // We share the resolver, to benefit more from its cache.
    CDBSchemasResolver resolver = new CDBSchemasResolver(this, schemaFolder + File.pathSeparator + XSDPath);
    ErrorHandler errorHandler = new CDBErrorHandler(this);

    for (String xsdFilename : xsdFilenames) {
        final File xsdFile = new File(xsdFilename);
        if (xsdFile.length() != 0) {
            if (verbose) {
                System.out.print("    " + xsdFilename);
            }
            try {
                validateFileEncoding(xsdFilename);
                SP.reset();
                resolver.setResolveOnlyHttp(true); // not sure why, but this is the legacy behavior
                SP.setEntityResolver(resolver);
                SP.setFeature("http://xml.org/sax/features/validation", true);
                SP.setFeature("http://apache.org/xml/features/validation/schema", true);
                SP.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
                SP.setFeature("http://xml.org/sax/features/namespaces", true);
                SP.setErrorHandler(errorHandler);
                SP.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                        "http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd");

                FileInputStream fis = new FileInputStream(xsdFile);
                InputSource inputSource = new InputSource(fis);
                inputSource.setSystemId("file:///" + xsdFile.getAbsolutePath());
                SP.parse(inputSource);
                fis.close();
                try {
                    // Now we know that the schema is technically valid (well, it does not seem to check xsd imports...)
                    // Still we have to check special requirements for CharacteristicComponent XSDs.
                    // This second check probably includes the first check's functionality, so that the
                    // first check could be removed once we have verified XSOM's xsd error reporting
                    // and hooked up the shared error handler in BaciSchemaChecker.
                    resolver.setResolveOnlyHttp(false); // here we want to resolve all schemas
                    BaciSchemaChecker baciChecker = new BaciSchemaChecker(xsdFile, resolver, errorHandler,
                            logger);
                    List<BaciPropertyLocator> badProps = baciChecker.findBaciPropsOutsideCharacteristicComp();
                    if (!badProps.isEmpty()) {
                        // Reduce the available error output to show only xsd element(s), not the individual baci properties
                        Set<String> badXsdElementNames = new HashSet<String>();
                        for (BaciPropertyLocator badProp : badProps) {
                            badXsdElementNames.add(badProp.elementName);
                        }
                        System.out.println(xsdFilename
                                + ": illegal use of baci properties in xsd elements that are not derived from baci:CharacteristicComponent. "
                                + "Offending element(s): " + StringUtils.join(badXsdElementNames, ' '));
                        errorFlag = true;
                        globalErrorFlag = true;
                    }
                } catch (SAXException ex) {
                    // ignore SAXException coming from BaciSchemaChecker, because we don't want to report errors
                    // twice when the xsd file is really messed up. 
                    // There are cases where xerces reports a normal error but XSOM reports a fatal error and throws this exception.
                }
                if (verbose && !errorFlag) {
                    System.out.println("[OK]");
                }
            } catch (SAXException e) {
                System.out.println("Caught a SAXException in validateSchemas: ");
                e.printStackTrace(System.out);
            } catch (IOException e) {
                System.out.println("[IOException] Probably " + xsdFilename + " doesn't exists.");
            }
        } else {
            System.out.print(xsdFilename + ": [Warning] file is empty.\n");
        }
    }
    resolver.setResolveOnlyHttp(true); // back to legacy mode again... yuck, our resolver still sticks to the "SP" field and will be used elsewhere!
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java

private XSSchemaSet parseSchema(Element schema) throws SchemaException {
    // Make sure that the schema parser sees all the namespace declarations
    DOMUtil.fixNamespaceDeclarations(schema);
    XSSchemaSet xss = null;/*w  w  w  . j  a va  2s.  c  o  m*/
    try {
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(schema);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(out);

        trans.transform(source, result);

        XSOMParser parser = createSchemaParser();
        InputSource inSource = new InputSource(new ByteArrayInputStream(out.toByteArray()));
        // XXX: hack: it's here to make entity resolver work...
        inSource.setSystemId("SystemId");
        // XXX: end hack
        inSource.setEncoding("utf-8");

        parser.parse(inSource);

        xss = parser.getResult();

    } catch (SAXException e) {
        throw new SchemaException("XML error during XSD schema parsing: " + e.getMessage()
                + "(embedded exception " + e.getException() + ") in " + shortDescription, e);
    } catch (TransformerException e) {
        throw new SchemaException("XML transformer error during XSD schema parsing: " + e.getMessage()
                + "(locator: " + e.getLocator() + ", embedded exception:" + e.getException() + ") in "
                + shortDescription, e);
    } catch (RuntimeException e) {
        // This sometimes happens, e.g. NPEs in Saxon
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected error {} during parsing of schema:\n{}", e.getMessage(),
                    DOMUtil.serializeDOMToString(schema));
        }
        throw new SchemaException(
                "XML error during XSD schema parsing: " + e.getMessage() + " in " + shortDescription, e);
    }

    return xss;
}

From source file:com.opensymphony.xwork3.config.providers.XmlConfigurationProvider.java

private List<Document> loadConfigurationFiles(String fileName, Element includeElement) {
    List<Document> docs = new ArrayList<Document>();
    List<Document> finalDocs = new ArrayList<Document>();
    if (!includedFileNames.contains(fileName)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading action configurations from: " + fileName);
        }//from www . j  ava2  s.c  om

        includedFileNames.add(fileName);

        Iterator<URL> urls = null;
        InputStream is = null;

        IOException ioException = null;
        try {
            urls = getConfigurationUrls(fileName);
        } catch (IOException ex) {
            ioException = ex;
        }

        if (urls == null || !urls.hasNext()) {
            if (errorIfMissing) {
                throw new ConfigurationException("Could not open files of the name " + fileName, ioException);
            } else {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Unable to locate configuration files of the name " + fileName + ", skipping");
                }
                return docs;
            }
        }

        URL url = null;
        while (urls.hasNext()) {
            try {
                url = urls.next();
                is = fileManager.loadFile(url);

                InputSource in = new InputSource(is);

                in.setSystemId(url.toString());

                docs.add(DomHelper.parse(in, dtdMappings));
            } /*catch (XWorkException e) {
              if (includeElement != null) {
                  throw new ConfigurationException("Unable to load " + url, e);
              } else {
                  throw new ConfigurationException("Unable to load " + url, e);
              }
              } */catch (Exception e) {
                throw new ConfigurationException("Caught exception while loading file " + fileName, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        LOG.error("Unable to close input stream", e);
                    }
                }
            }
        }

        //sort the documents, according to the "order" attribute
        Collections.sort(docs, new Comparator<Document>() {
            public int compare(Document doc1, Document doc2) {
                return XmlHelper.getLoadOrder(doc1).compareTo(XmlHelper.getLoadOrder(doc2));
            }
        });

        for (Document doc : docs) {
            Element rootElement = doc.getDocumentElement();
            NodeList children = rootElement.getChildNodes();
            int childSize = children.getLength();

            for (int i = 0; i < childSize; i++) {
                Node childNode = children.item(i);

                if (childNode instanceof Element) {
                    Element child = (Element) childNode;

                    final String nodeName = child.getNodeName();

                    if ("include".equals(nodeName)) {
                        String includeFileName = child.getAttribute("file");
                        if (includeFileName.indexOf('*') != -1) {
                            // handleWildCardIncludes(includeFileName, docs, child);
                            ClassPathFinder wildcardFinder = new ClassPathFinder();
                            wildcardFinder.setPattern(includeFileName);
                            Vector<String> wildcardMatches = wildcardFinder.findMatches();
                            for (String match : wildcardMatches) {
                                finalDocs.addAll(loadConfigurationFiles(match, child));
                            }
                        } else {
                            finalDocs.addAll(loadConfigurationFiles(includeFileName, child));
                        }
                    }
                }
            }
            finalDocs.add(doc);
            loadedFileUrls.add(url.toString());
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Loaded action configuration from: " + fileName);
        }
    }
    return finalDocs;
}

From source file:com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.java

private List<Document> loadConfigurationFiles(String fileName, Element includeElement) {
    List<Document> docs = new ArrayList<Document>();
    List<Document> finalDocs = new ArrayList<Document>();
    if (!includedFileNames.contains(fileName)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading action configurations from: " + fileName);
        }//from w ww. j  a v a  2  s .co  m

        includedFileNames.add(fileName);

        Iterator<URL> urls = null;
        InputStream is = null;

        IOException ioException = null;
        try {
            urls = getConfigurationUrls(fileName);
        } catch (IOException ex) {
            ioException = ex;
        }

        if (urls == null || !urls.hasNext()) {
            if (errorIfMissing) {
                throw new ConfigurationException("Could not open files of the name " + fileName, ioException);
            } else {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Unable to locate configuration files of the name " + fileName + ", skipping");
                }
                return docs;
            }
        }

        URL url = null;
        while (urls.hasNext()) {
            try {
                url = urls.next();
                is = fileManager.loadFile(url);

                InputSource in = new InputSource(is);

                in.setSystemId(url.toString());

                docs.add(DomHelper.parse(in, dtdMappings));
            } catch (XWorkException e) {
                if (includeElement != null) {
                    throw new ConfigurationException("Unable to load " + url, e, includeElement);
                } else {
                    throw new ConfigurationException("Unable to load " + url, e);
                }
            } catch (Exception e) {
                throw new ConfigurationException("Caught exception while loading file " + fileName, e,
                        includeElement);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        LOG.error("Unable to close input stream", e);
                    }
                }
            }
        }

        //sort the documents, according to the "order" attribute
        Collections.sort(docs, new Comparator<Document>() {
            public int compare(Document doc1, Document doc2) {
                return XmlHelper.getLoadOrder(doc1).compareTo(XmlHelper.getLoadOrder(doc2));
            }
        });

        for (Document doc : docs) {
            Element rootElement = doc.getDocumentElement();
            NodeList children = rootElement.getChildNodes();
            int childSize = children.getLength();

            for (int i = 0; i < childSize; i++) {
                Node childNode = children.item(i);

                if (childNode instanceof Element) {
                    Element child = (Element) childNode;

                    final String nodeName = child.getNodeName();

                    if ("include".equals(nodeName)) {
                        String includeFileName = child.getAttribute("file");
                        if (includeFileName.indexOf('*') != -1) {
                            // handleWildCardIncludes(includeFileName, docs, child);
                            ClassPathFinder wildcardFinder = new ClassPathFinder();
                            wildcardFinder.setPattern(includeFileName);
                            Vector<String> wildcardMatches = wildcardFinder.findMatches();
                            for (String match : wildcardMatches) {
                                finalDocs.addAll(loadConfigurationFiles(match, child));
                            }
                        } else {
                            finalDocs.addAll(loadConfigurationFiles(includeFileName, child));
                        }
                    }
                }
            }
            finalDocs.add(doc);
            loadedFileUrls.add(url.toString());
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Loaded action configuration from: " + fileName);
        }
    }
    return finalDocs;
}

From source file:com.evolveum.midpoint.prism.schema.SchemaRegistry.java

private InputSource resolveResourceFromRegisteredSchemasByNamespace(String namespaceURI) {
    if (namespaceURI != null) {
        if (parsedSchemas.containsKey(namespaceURI)) {
            SchemaDescription schemaDescription = parsedSchemas.get(namespaceURI);
            if (schemaDescription.canInputStream()) {
                InputStream inputStream = schemaDescription.openInputStream();
                InputSource source = new InputSource();
                source.setByteStream(inputStream);
                //source.setSystemId(schemaDescription.getPath());
                // Make sure that both publicId and systemId are always set to schema namespace
                // this helps to avoid double processing of the schemas
                source.setSystemId(namespaceURI);
                source.setPublicId(namespaceURI);
                return source;
            } else {
                throw new IllegalStateException("Requested resolution of schema "
                        + schemaDescription.getSourceDescription() + " that does not support input stream");
            }// w  ww . j a  v a  2  s .  c om
        }
    }
    return null;
}

From source file:org.data.support.beans.factory.xml.ResourceEntityResolver.java

@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    InputSource source = super.resolveEntity(publicId, systemId);
    if (source == null && systemId != null) {
        String resourcePath = null;
        try {//from   w ww.jav a 2 s.co  m
            String decodedSystemId = URLDecoder.decode(systemId);
            String givenUrl = new URL(decodedSystemId).toString();
            String systemRootUrl = new File("").toURL().toString();
            // Try relative to resource base if currently in system root.
            if (givenUrl.startsWith(systemRootUrl)) {
                resourcePath = givenUrl.substring(systemRootUrl.length());
            }
        } catch (Exception ex) {
            // Typically a MalformedURLException or AccessControlException.
            if (logger.isDebugEnabled()) {
                logger.debug("Could not resolve XML entity [" + systemId + "] against system root URL", ex);
            }
            // No URL (or no resolvable URL) -> try relative to resource base.
            resourcePath = systemId;
        }
        if (resourcePath != null) {
            if (logger.isTraceEnabled()) {
                logger.trace(
                        "Trying to locate XML entity [" + systemId + "] as resource [" + resourcePath + "]");
            }
            Resource resource = this.resourceLoader.getResource(resourcePath);
            source = new InputSource(resource.getInputStream());
            source.setPublicId(publicId);
            source.setSystemId(systemId);
            if (logger.isDebugEnabled()) {
                logger.debug("Found XML entity [" + systemId + "]: " + resource);
            }
        }
    }
    return source;
}

From source file:net.unicon.academus.apps.XHTMLFilter.java

public static void main(String[] args) throws Exception {
    XHTMLFilterConfig config = getConfiguration(args[1]);
    InputSource s = new InputSource();
    s.setSystemId(args[0]);
    filterHTML(s, System.out, config);
}

From source file:nl.armatiek.xslweb.utils.XMLUtils.java

public static Document readerToDocument(Reader reader, String systemId) throws Exception {
    if (reader == null) {
        return null;
    }//  w ww  .j a v  a 2 s .  c  o m
    DocumentBuilder builder = getDocumentBuilder(false, true);
    InputSource is = new InputSource(reader);
    if (systemId != null) {
        is.setSystemId(systemId);
    }
    return builder.parse(is);
}

From source file:nl.nn.adapterframework.pipes.WsdlXmlValidator.java

private InputSource getInputSource(URL url) {
    InputStream inputStream = null;
    if (url != null) {
        try {/* ww w.j  a va  2  s .c om*/
            inputStream = url.openStream();
        } catch (IOException e) {
            ioException = e;
        }
    }
    InputSource source = null;
    if (inputStream != null) {
        source = new InputSource(inputStream);
        source.setSystemId(url.toString());
    }
    return source;
}

From source file:org.apache.axis2.deployment.resolver.AARFileBasedURIResolver.java

public InputSource resolveEntity(String targetNamespace, String schemaLocation, String baseUri) {
    //no issue with abloslute schemas 
    // this schema can be in a relative location for another base scheama. so first
    // try to see the proper location

    lastImportLocation = URI.create(baseUri).resolve(schemaLocation);
    if (isAbsolute(lastImportLocation.toString())) {
        return super.resolveEntity(targetNamespace, schemaLocation, baseUri);
    } else {/*from  ww w.  j av  a  2  s  .com*/
        //validate
        if ((baseUri == null || "".equals(baseUri)) && schemaLocation.startsWith("..")) {
            throw new RuntimeException("Unsupported schema location " + schemaLocation);
        }

        ZipInputStream zin = null;
        try {
            zin = new ZipInputStream(new FileInputStream(aarFile));

            ZipEntry entry;
            byte[] buf = new byte[1024];
            int read;
            ByteArrayOutputStream out;
            String searchingStr = lastImportLocation.toString();
            while ((entry = zin.getNextEntry()) != null) {
                String entryName = entry.getName().toLowerCase();
                if (entryName.equalsIgnoreCase(searchingStr)) {
                    out = new ByteArrayOutputStream();
                    while ((read = zin.read(buf)) > 0) {
                        out.write(buf, 0, read);
                    }
                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                    InputSource inputSoruce = new InputSource(in);
                    inputSoruce.setSystemId(lastImportLocation.getPath());
                    inputSoruce.setPublicId(targetNamespace);
                    return inputSoruce;
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (zin != null) {
                    zin.close();
                }
            } catch (IOException e) {
                log.debug(e);
            }
        }

    }

    log.info("AARFileBasedURIResolver: Unable to resolve" + lastImportLocation);
    return null;
}