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:org.apache.ode.bpel.compiler_2_0.XslTest.java

private OProcess compile(String bpelFile) throws Exception {
    URL bpelURL = getClass().getResource("/xslt/" + bpelFile + ".bpel");

    InputSource isrc = new InputSource(bpelURL.openStream());
    isrc.setSystemId(bpelURL.toExternalForm());

    org.apache.ode.bpel.compiler.bom.Process process = BpelObjectFactory.getInstance().parse(isrc,
            bpelURL.toURI());/*from  www  .  ja  v a2 s  . c  o  m*/

    return _compiler.compile(process, _resfinder, 0);
}

From source file:org.apache.ode.utils.DOMUtils.java

public static Document toDocumentFromStream(StreamSource source) throws IOException, SAXException {
    DocumentBuilder builder = getBuilder();
    Document document = null;// w ww  . ja v  a2s .  c  o  m
    Reader reader = source.getReader();
    if (reader != null) {
        document = builder.parse(new InputSource(reader));
    } else {
        InputStream inputStream = source.getInputStream();
        if (inputStream != null) {
            InputSource inputsource = new InputSource(inputStream);
            inputsource.setSystemId(source.getSystemId());
            document = builder.parse(inputsource);
        } else {
            throw new IOException("No input stream or reader available");
        }
    }
    return document;
}

From source file:org.apache.solr.analysis.HyphenationCompoundWordTokenFilterFactory.java

public void inform(ResourceLoader loader) {
    InputStream stream = null;/* w w  w.  j a  va2s  . c o m*/
    try {
        if (dictFile != null) // the dictionary can be empty.
            dictionary = getWordSet(loader, dictFile, false);
        // TODO: Broken, because we cannot resolve real system id
        // ResourceLoader should also supply method like ClassLoader to get resource URL
        stream = loader.openResource(hypFile);
        final InputSource is = new InputSource(stream);
        is.setEncoding(encoding); // if it's null let xml parser decide
        is.setSystemId(hypFile);
        hyphenator = HyphenationCompoundWordTokenFilter.getHyphenationTree(is);
    } catch (Exception e) { // TODO: getHyphenationTree really shouldn't throw "Exception"
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.apache.solr.core.Config.java

/**
 * Builds a config://ww  w  .ja  va2s .c o m
 * <p>
 * Note that the 'name' parameter is used to obtain a valid input stream if no valid one is provided through 'is'.
 * If no valid stream is provided, a valid SolrResourceLoader instance should be provided through 'loader' so
 * the resource can be opened (@see SolrResourceLoader#openResource); if no SolrResourceLoader instance is provided, a default one
 * will be created.
 * </p>
 * <p>
 * Consider passing a non-null 'name' parameter in all use-cases since it is used for logging & exception reporting.
 * </p>
 * @param loader the resource loader used to obtain an input stream if 'is' is null
 * @param name the resource name used if the input stream 'is' is null
 * @param is the resource as a SAX InputSource
 * @param prefix an optional prefix that will be preprended to all non-absolute xpath expressions
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws java.io.IOException
 * @throws org.xml.sax.SAXException
 */
public Config(SolrResourceLoader loader, String name, InputSource is, String prefix)
        throws ParserConfigurationException, IOException, SAXException {
    if (loader == null) {
        loader = new SolrResourceLoader(null);
    }
    this.loader = loader;
    this.name = name;
    this.prefix = (prefix != null && !prefix.endsWith("/")) ? prefix + '/' : prefix;
    try {
        javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        if (is == null) {
            is = new InputSource(loader.openConfig(name));
            is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(name));
        }

        // only enable xinclude, if a SystemId is available
        if (is.getSystemId() != null) {
            try {
                dbf.setXIncludeAware(true);
                dbf.setNamespaceAware(true);
            } catch (UnsupportedOperationException e) {
                log.warn(name + " XML parser doesn't support XInclude option");
            }
        }

        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new SystemIdResolver(loader));
        db.setErrorHandler(xmllog);
        try {
            doc = db.parse(is);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(is.getByteStream());
        }

        DOMUtil.substituteProperties(doc, loader.getCoreProperties());
    } catch (ParserConfigurationException e) {
        SolrException.log(log, "Exception during parsing file: " + name, e);
        throw e;
    } catch (SAXException e) {
        SolrException.log(log, "Exception during parsing file: " + name, e);
        throw e;
    } catch (SolrException e) {
        SolrException.log(log, "Error in " + name, e);
        throw e;
    }
}

From source file:org.apache.solr.core.ZkContainer.java

public SolrConfig getSolrConfigFromZk(String zkConfigName, String solrConfigFileName,
        SolrResourceLoader resourceLoader) {
    SolrConfig cfg = null;//from   w w  w.ja  va 2 s. c o m
    try {
        byte[] config = zkController.getConfigFileData(zkConfigName, solrConfigFileName);
        InputSource is = new InputSource(new ByteArrayInputStream(config));
        is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(solrConfigFileName));
        cfg = solrConfigFileName == null ? new SolrConfig(resourceLoader, SolrConfig.DEFAULT_CONF_FILE, is)
                : new SolrConfig(resourceLoader, solrConfigFileName, is);
    } catch (Exception e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "getSolrConfigFromZK failed for " + zkConfigName + " " + solrConfigFileName, e);
    }
    return cfg;
}

From source file:org.apache.solr.handler.dataimport.DataImporter.java

boolean maybeReloadConfiguration(RequestInfo params, NamedList<?> defaultParams) throws IOException {
    if (importLock.tryLock()) {
        boolean success = false;
        try {//  w w  w. j  ava  2s .  co m
            if (null != params.getRequest()) {
                if (schema != params.getRequest().getSchema()) {
                    schema = params.getRequest().getSchema();
                }
            }
            String dataConfigText = params.getDataConfig();
            String dataconfigFile = params.getConfigFile();
            InputSource is = null;
            if (dataConfigText != null && dataConfigText.length() > 0) {
                is = new InputSource(new StringReader(dataConfigText));
            } else if (dataconfigFile != null) {
                is = new InputSource(core.getResourceLoader().openResource(dataconfigFile));
                is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(dataconfigFile));
                LOG.info("Loading DIH Configuration: " + dataconfigFile);
            }
            if (is != null) {
                config = loadDataConfig(is);
                success = true;
            }

            Map<String, Map<String, String>> dsProps = new HashMap<>();
            if (defaultParams != null) {
                int position = 0;
                while (position < defaultParams.size()) {
                    if (defaultParams.getName(position) == null) {
                        break;
                    }
                    String name = defaultParams.getName(position);
                    if (name.equals("datasource")) {
                        success = true;
                        NamedList dsConfig = (NamedList) defaultParams.getVal(position);
                        LOG.info("Getting configuration for Global Datasource...");
                        Map<String, String> props = new HashMap<>();
                        for (int i = 0; i < dsConfig.size(); i++) {
                            props.put(dsConfig.getName(i), dsConfig.getVal(i).toString());
                        }
                        LOG.info("Adding properties to datasource: " + props);
                        dsProps.put((String) dsConfig.get("name"), props);
                    }
                    position++;
                }
            }
            requestLevelDataSourceProps = Collections.unmodifiableMap(dsProps);
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            importLock.unlock();
        }
        return success;
    } else {
        return false;
    }
}

From source file:org.apache.solr.schema.ManagedIndexSchemaFactory.java

/**
 * First, try to locate the managed schema file named in the managedSchemaResourceName
 * param. If the managed schema file exists and is accessible, it is used to instantiate
 * an IndexSchema.//from  w  w w  .  j a v a 2s . co  m
 *
 * If the managed schema file can't be found, the resource named by the resourceName
 * parameter is used to instantiate an IndexSchema.
 *
 * Once the IndexSchema is instantiated, if the managed schema file does not exist,
 * the instantiated IndexSchema is persisted to the managed schema file named in the
 * managedSchemaResourceName param, in the directory given by 
 * {@link org.apache.solr.core.SolrResourceLoader#getConfigDir()}, or if configs are
 * in ZooKeeper, under {@link org.apache.solr.cloud.ZkSolrResourceLoader#getConfigSetZkPath()}.
 *
 * After the managed schema file is persisted, the original schema file is
 * renamed by appending the extension named in {@link #UPGRADED_SCHEMA_EXTENSION}.
 */
@Override
public ManagedIndexSchema create(String resourceName, SolrConfig config) {
    this.resourceName = resourceName;
    this.config = config;
    this.loader = config.getResourceLoader();
    InputStream schemaInputStream = null;

    if (null == resourceName) {
        resourceName = IndexSchema.DEFAULT_SCHEMA_FILE;
    }

    int schemaZkVersion = -1;
    if (!(loader instanceof ZkSolrResourceLoader)) {
        schemaInputStream = readSchemaLocally();
    } else { // ZooKeeper
        final ZkSolrResourceLoader zkLoader = (ZkSolrResourceLoader) loader;
        final SolrZkClient zkClient = zkLoader.getZkController().getZkClient();
        final String managedSchemaPath = zkLoader.getConfigSetZkPath() + "/" + managedSchemaResourceName;
        Stat stat = new Stat();
        try {
            // Attempt to load the managed schema
            byte[] data = zkClient.getData(managedSchemaPath, null, stat, true);
            schemaZkVersion = stat.getVersion();
            schemaInputStream = new ByteArrayInputStream(data);
            loadedResource = managedSchemaResourceName;
            warnIfNonManagedSchemaExists();
        } catch (InterruptedException e) {
            // Restore the interrupted status
            Thread.currentThread().interrupt();
            log.warn("", e);
        } catch (KeeperException.NoNodeException e) {
            log.info("The schema is configured as managed, but managed schema resource "
                    + managedSchemaResourceName + " not found - loading non-managed schema " + resourceName
                    + " instead");
        } catch (KeeperException e) {
            String msg = "Error attempting to access " + managedSchemaPath;
            log.error(msg, e);
            throw new SolrException(ErrorCode.SERVER_ERROR, msg, e);
        }
        if (null == schemaInputStream) {
            // The managed schema file could not be found - load the non-managed schema
            try {
                schemaInputStream = loader.openSchema(resourceName);
                loadedResource = resourceName;
                shouldUpgrade = true;
            } catch (Exception e) {
                try {
                    // Retry to load the managed schema, in case it was created since the first attempt
                    byte[] data = zkClient.getData(managedSchemaPath, null, stat, true);
                    schemaZkVersion = stat.getVersion();
                    schemaInputStream = new ByteArrayInputStream(data);
                    loadedResource = managedSchemaPath;
                    warnIfNonManagedSchemaExists();
                } catch (Exception e1) {
                    if (e1 instanceof InterruptedException) {
                        Thread.currentThread().interrupt(); // Restore the interrupted status
                    }
                    final String msg = "Error loading both non-managed schema '" + resourceName
                            + "' and managed schema '" + managedSchemaResourceName + "'";
                    log.error(msg, e);
                    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);
                }
            }
        }
    }
    InputSource inputSource = new InputSource(schemaInputStream);
    inputSource.setSystemId(SystemIdResolver.createSystemIdFromResourceName(loadedResource));
    try {
        schema = new ManagedIndexSchema(config, loadedResource, inputSource, isMutable,
                managedSchemaResourceName, schemaZkVersion, getSchemaUpdateLock());
    } catch (KeeperException e) {
        final String msg = "Error instantiating ManagedIndexSchema";
        log.error(msg, e);
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);
    } catch (InterruptedException e) {
        // Restore the interrupted status
        Thread.currentThread().interrupt();
        log.warn("", e);
    }

    if (shouldUpgrade) {
        // Persist the managed schema if it doesn't already exist
        upgradeToManagedSchema();
    }

    return schema;
}

From source file:org.apache.struts2.jasper.compiler.TldLocationsCache.java

private void processWebDotXml() throws Exception {

    InputStream is = null;/*from  w ww .j av a 2s.  c om*/

    try {
        // Acquire input stream to web application deployment descriptor
        String altDDName = (String) ctxt.getAttribute(Constants.ALT_DD_ATTR);
        URL uri = null;
        if (altDDName != null) {
            try {
                uri = new URL(FILE_PROTOCOL + altDDName.replace('\\', '/'));
            } catch (MalformedURLException e) {
                if (log.isWarnEnabled()) {
                    log.warn(Localizer.getMessage("jsp.error.internal.filenotfound", altDDName));
                }
            }
        } else {
            uri = ctxt.getResource(WEB_XML);
        }

        if (uri == null) {
            return;
        }
        is = uri.openStream();
        InputSource ip = new InputSource(is);
        ip.setSystemId(uri.toExternalForm());

        // Parse the web application deployment descriptor
        TreeNode webtld = null;
        // altDDName is the absolute path of the DD
        if (altDDName != null) {
            webtld = new ParserUtils().parseXMLDocument(altDDName, ip);
        } else {
            webtld = new ParserUtils().parseXMLDocument(WEB_XML, ip);
        }

        // Allow taglib to be an element of the root or jsp-config (JSP2.0)
        TreeNode jspConfig = webtld.findChild("jsp-config");
        if (jspConfig != null) {
            webtld = jspConfig;
        }
        Iterator taglibs = webtld.findChildren("taglib");
        while (taglibs.hasNext()) {

            // Parse the next <taglib> element
            TreeNode taglib = (TreeNode) taglibs.next();
            String tagUri = null;
            String tagLoc = null;
            TreeNode child = taglib.findChild("taglib-uri");
            if (child != null)
                tagUri = child.getBody();
            child = taglib.findChild("taglib-location");
            if (child != null)
                tagLoc = child.getBody();

            // Save this location if appropriate
            if (tagLoc == null)
                continue;
            if (uriType(tagLoc) == NOROOT_REL_URI)
                tagLoc = "/WEB-INF/" + tagLoc;
            String tagLoc2 = null;
            if (tagLoc.endsWith(JAR_FILE_SUFFIX)) {
                tagLoc = ctxt.getResource(tagLoc).toString();
                tagLoc2 = "META-INF/taglib.tld";
            }
            mappings.put(tagUri, new String[] { tagLoc, tagLoc2 });
        }
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Throwable t) {
            }
        }
    }
}

From source file:org.apache.synapse.util.resolver.ResourceMap.java

/**
 * Resolve a resource for a given location.
 * /*www  .j a v a2  s.  c o  m*/
 * @param synCfg the Synapse configuration (used to access the registry)
 * @param location the location of of the resource at is appears in the referencing document
 * @return an <code>InputSource</code> object for the referenced resource
 */
public InputSource resolve(SynapseConfiguration synCfg, String location) {
    String key = resources.get(location);
    if (key == null) {
        if (log.isDebugEnabled()) {
            log.debug("No resource mapping is defined for location '" + location + "'");
        }
        return null;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Resolving location '" + location + "' to registry item '" + key + "'");
        }
        synCfg.getEntryDefinition(key);
        Object keyObject = synCfg.getEntry(key);
        if (keyObject instanceof OMElement) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ((OMElement) keyObject).serialize(baos);
            } catch (XMLStreamException ex) {
                String msg = "Unable to serialize registry item '" + key + "' for location '" + location + "'";
                log.error(msg);
                throw new SynapseException(msg, ex);
            }
            InputSource inputSource = new InputSource(new ByteArrayInputStream(baos.toByteArray()));
            // We must set a system ID because Axis2 relies on this (see SYNAPSE-362). Compose a
            // valid URI with the registry key so that it uniquely identifies the resource.
            inputSource.setSystemId("synapse-reg:///" + key);
            return inputSource;
        } else {
            String msg = "Registry item '" + key + "' for location '" + location + "' is not an OMElement";
            log.error(msg);
            throw new SynapseException(msg);
        }
    }
}

From source file:org.apache.tomcat.util.digester.Digester.java

/**
 * Parse the content of the specified file using this Digester.  Returns
 * the root element from the object stack (if any).
 *
 * @param file File containing the XML data to be parsed
 *
 * @exception IOException if an input/output error occurs
 * @exception SAXException if a parsing exception occurs
 *//*from w ww .j  av a  2s. c  o m*/
public Object parse(File file) throws IOException, SAXException {

    configure();
    InputSource input = new InputSource(new FileInputStream(file));
    input.setSystemId("file://" + file.getAbsolutePath());
    getXMLReader().parse(input);
    return (root);

}