Example usage for org.xml.sax InputSource getSystemId

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

Introduction

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

Prototype

public String getSystemId() 

Source Link

Document

Get the system identifier for this input source.

Usage

From source file:org.apache.axis2.jaxws.util.CatalogURIResolver.java

/**
 * Given a redirecteURI from a static XML catalog, attempt to get the InputSource.
 * @param redirectedURI URI string from static XML catalog
 * @return InputSource or null if we were not able to load the resource
 *//*from  w  w  w . jav a 2  s  .c  om*/
private InputSource getInputSourceFromRedirectedURI(String redirectedURI) {
    InputStream is = null;
    String validatedURI = null;
    InputSource returnInputSource = null;
    // If we have an absolute path, try to get the InputStream directly
    if (isAbsolute(redirectedURI)) {
        is = getInputStreamForURI(redirectedURI);
        if (is != null) {
            validatedURI = redirectedURI;
        }
    }
    // If we couldn't get the inputstream try using the classloader
    if (is == null && classLoader != null) {
        try {
            is = classLoader.getResourceAsStream(redirectedURI);
            if (is != null) {
                validatedURI = redirectedURI;
            }
        } catch (Throwable t) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "Exception occured in validateRedirectedURI, ignoring exception continuing processing: "
                                + t.getMessage());
            }
        }
        // If we failed to get an InputStream using the entire redirectedURI,
        //  try striping off the protocol.  This may be necessary for some cases
        //  if a non-standard protocol is used.
        if (is == null) {
            redirectedURI = stripProtocol(redirectedURI);
            if (log.isDebugEnabled()) {
                log.debug("getInputSourceFromRedirectedURI: new redirected location: " + redirectedURI);
            }
            try {
                is = classLoader.getResourceAsStream(redirectedURI);
                if (is != null) {
                    validatedURI = redirectedURI;
                }
            } catch (Throwable t) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Exception occured in validateRedirectedURI, ignoring exception continuing processing: "
                                    + t.getMessage());
                }
            }
        }
    }

    if (is != null) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "getInputSourceFromRedirectedURI: XSD input stream is not null after resolving import for: "
                            + redirectedURI);
        }
        returnInputSource = new InputSource(is);
        // We need to set the systemId. XmlSchema will use this value to
        // maintain a collection of
        // imported XSDs that have been read. If this value is null, then
        // circular XSDs will
        // cause infinite recursive reads.
        returnInputSource.setSystemId(validatedURI != null ? validatedURI : redirectedURI);

        if (log.isDebugEnabled()) {
            log.debug("returnInputSource :" + returnInputSource.getSystemId());
        }
    }
    return returnInputSource;
}

From source file:org.apache.cayenne.map.MapLoader.java

/**
 * Loads a DataMap from XML input source.
 *//*  w w w  .ja va 2s .  c o m*/
public synchronized DataMap loadDataMap(InputSource src) throws CayenneRuntimeException {
    if (src == null) {
        throw new NullPointerException("Null InputSource.");
    }

    try {
        String mapName = mapNameFromLocation(src.getSystemId());
        dataMap = new DataMap(mapName);
        XMLReader parser = Util.createXmlReader();

        parser.setContentHandler(this);
        parser.setErrorHandler(this);
        parser.parse(src);
    } catch (SAXException e) {
        dataMap = null;
        throw new CayenneRuntimeException(
                "Wrong DataMap format, last processed tag: " + constructCurrentStateString(),
                Util.unwindException(e));
    } catch (Exception e) {
        dataMap = null;
        throw new CayenneRuntimeException(
                "Error loading DataMap, last processed tag: " + constructCurrentStateString(),
                Util.unwindException(e));
    }
    return dataMap;
}

From source file:org.apache.cocoon.components.xslt.TraxProcessor.java

/**
 * Called by the processor when it encounters an xsl:include, xsl:import, or
 * document() function.//from   ww  w.j a  v a  2 s .  co  m
 * 
 * @param href
 *            An href attribute, which may be relative or absolute.
 * @param base
 *            The base URI in effect when the href attribute was
 *            encountered.
 * 
 * @return A Source object, or null if the href cannot be resolved, and the
 *         processor should try to resolve the URI itself.
 * 
 * @throws TransformerException
 *             if an error occurs when trying to resolve the URI.
 */
public javax.xml.transform.Source resolve(String href, String base) throws TransformerException {
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("resolve(href = " + href + ", base = " + base + "); resolver = " + m_resolver);
    }

    Source xslSource = null;
    try {
        if (base == null || href.indexOf(":") > 1) {
            // Null base - href must be an absolute URL
            xslSource = m_resolver.resolveURI(href);
        } else if (href.length() == 0) {
            // Empty href resolves to base
            xslSource = m_resolver.resolveURI(base);
        } else {
            // is the base a file or a real m_url
            if (!base.startsWith("file:")) {
                int lastPathElementPos = base.lastIndexOf('/');
                if (lastPathElementPos == -1) {
                    // this should never occur as the base should
                    // always be protocol:/....
                    return null; // we can't resolve this
                } else {
                    xslSource = m_resolver.resolveURI(base.substring(0, lastPathElementPos) + "/" + href);
                }
            } else {
                File parent = new File(base.substring(5));
                File parent2 = new File(parent.getParentFile(), href);
                xslSource = m_resolver.resolveURI(parent2.toURL().toExternalForm());
            }
        }

        InputSource is = getInputSource(xslSource);

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("xslSource = " + xslSource + ", system id = " + xslSource.getURI());
        }

        if (m_checkIncludes) {
            // Populate included validities
            List includes = (List) m_includesMap.get(base);
            if (includes != null) {
                SourceValidity included = xslSource.getValidity();
                if (included != null) {
                    includes.add(new Object[] { xslSource.getURI(), xslSource.getValidity() });
                } else {
                    // One of the included stylesheets is not cacheable
                    m_includesMap.remove(base);
                }
            }
        }

        return new StreamSource(is.getByteStream(), is.getSystemId());
    } catch (SourceException e) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Failed to resolve " + href + "(base = " + base + "), return null", e);
        }

        // CZ: To obtain the same behaviour as when the resource is
        // transformed by the XSLT Transformer we should return null here.
        return null;
    } catch (java.net.MalformedURLException mue) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Failed to resolve " + href + "(base = " + base + "), return null", mue);
        }

        return null;
    } catch (IOException ioe) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Failed to resolve " + href + "(base = " + base + "), return null", ioe);
        }

        return null;
    } finally {
        m_resolver.release(xslSource);
    }
}

From source file:org.apache.cocoon.core.xml.impl.DefaultEntityResolver.java

/**
 * Allow the application to resolve external entities.
 *
 * <p>The Parser will call this method before opening any external
 * entity except the top-level document entity (including the
 * external DTD subset, external entities referenced within the
 * DTD, and external entities referenced within the document
 * element): the application may request that the parser resolve
 * the entity itself, that it use an alternative URI, or that it
 * use an entirely different input source.</p>
 *
 * <p>Application writers can use this method to redirect external
 * system identifiers to secure and/or local URIs, to look up
 * public identifiers in a catalogue, or to read an entity from a
 * database or other input source (including, for example, a dialog
 * box).</p>//from   w  ww. ja  v a2  s. c o  m
 *
 * <p>If the system identifier is a URL, the SAX parser must
 * resolve it fully before reporting it to the application.</p>
 *
 * @param publicId The public identifier of the external entity
 *        being referenced, or null if none was supplied.
 * @param systemId The system identifier of the external entity
 *        being referenced.
 * @return An InputSource object describing the new input source,
 *         or null to request that the parser open a regular
 *         URI connection to the system identifier.
 * @exception org.xml.sax.SAXException Any SAX exception, possibly
 *            wrapping another exception.
 * @exception java.io.IOException A Java-specific IO exception,
 *            possibly the result of creating a new InputStream
 *            or Reader for the InputSource.
 * @see org.xml.sax.InputSource
 */
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    InputSource altInputSource = this.catalogResolver.resolveEntity(publicId, systemId);
    if (altInputSource != null) {
        if (this.getLogger().isDebugEnabled()) {
            this.getLogger().debug("Resolved catalog entity: " + publicId + " " + altInputSource.getSystemId());
        }
    }

    return altInputSource;
}

From source file:org.apache.ode.jbi.util.SchemaCollection.java

public void read(InputSource inputSource) throws Exception {
    DocumentBuilderFactory docFac = XMLParserUtils.getDocumentBuilderFactory(); // don't trust system provided parser!
    docFac.setNamespaceAware(true);// w w  w.  j  av  a2  s .c  o m
    DocumentBuilder builder = docFac.newDocumentBuilder();
    Document doc = builder.parse(inputSource);
    read(doc.getDocumentElement(),
            inputSource.getSystemId() != null ? new URI(inputSource.getSystemId()) : null);
}

From source file:org.apache.solr.common.util.TestSystemIdResolver.java

private void assertEntityResolving(SystemIdResolver resolver, String expectedSystemId, String base,
        String systemId) throws Exception {
    final InputSource is = resolver.resolveEntity(null, null, base, systemId);
    try {//  w  w w .  jav  a 2  s .  c om
        assertEquals("Resolved SystemId does not match", expectedSystemId, is.getSystemId());
    } finally {
        IOUtils.closeQuietly(is.getByteStream());
    }
}

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

/**
 * Builds a config://from  ww w.  j av  a  2 s.com
 * <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.handler.dataimport.DataImporter.java

public DIHConfiguration loadDataConfig(InputSource configFile) {

    DIHConfiguration dihcfg = null;// w ww  .  ja  va  2 s .c  o  m
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        // only enable xinclude, if a a SolrCore and SystemId is present (makes no sense otherwise)
        if (core != null && configFile.getSystemId() != null) {
            try {
                dbf.setXIncludeAware(true);
                dbf.setNamespaceAware(true);
            } catch (UnsupportedOperationException e) {
                LOG.warn("XML parser doesn't support XInclude option");
            }
        }

        DocumentBuilder builder = dbf.newDocumentBuilder();
        if (core != null)
            builder.setEntityResolver(new SystemIdResolver(core.getResourceLoader()));
        builder.setErrorHandler(XMLLOG);
        Document document;
        try {
            document = builder.parse(configFile);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(configFile.getByteStream());
        }

        dihcfg = readFromXml(document);
        LOG.info("Data Configuration loaded successfully");
    } catch (Exception e) {
        throw new DataImportHandlerException(SEVERE, "Data Config problem: " + e.getMessage(), e);
    }
    for (Entity e : dihcfg.getEntities()) {
        if (e.getAllAttributes().containsKey(SqlEntityProcessor.DELTA_QUERY)) {
            isDeltaImportSupported = true;
            break;
        }
    }
    return dihcfg;
}

From source file:org.castor.jdo.engine.DatabaseRegistry.java

/**
 * Instantiates a ConnectionFactory from the JDO configuration file.
 * /*from   w w w  .j ava 2 s .c o m*/
 * @param source
 *                {@link InputSource} pointing to the JDO configuration.
 * @param resolver
 *                An entity resolver.
 * @param loader
 *                A class loader
 * @param classDescriptorResolver
 *                {@link ClassDescriptorResolver} used for class to class
 *                descriptor resolution.
 * @throws MappingException
 *                 If the database cannot be instantiated/loaded.
 */
public static synchronized void loadDatabase(final InputSource source, final EntityResolver resolver,
        final ClassLoader loader, final JDOClassDescriptorResolver classDescriptorResolver)
        throws MappingException {

    // Load the JDO configuration file from the specified input source.
    JdoConf jdoConf = null;
    jdoConf = JDOConfFactory.createJdoConf(source, resolver, loader);
    LOG.debug("Loaded jdo conf successfully");

    loadDatabase(jdoConf, resolver, loader, source.getSystemId(), classDescriptorResolver);
}

From source file:org.castor.mapping.MappingUnmarshaller.java

/**
 * Internal recursive loading method. This method will load the mapping document into a mapping
 * object and load all the included mapping along the way into a single collection.
 *
 * @param mapping The mapping instance.//from   ww  w .  j  a v a  2  s.  c  om
 * @param resolver The entity resolver to use.
 * @param url The URL of the mapping file.
 * @throws IOException An error occured when reading the mapping file.
 * @throws MappingException The mapping file is invalid.
 */
protected void loadMappingInternal(final Mapping mapping, final DTDResolver resolver, final String url)
        throws IOException, MappingException {
    try {
        InputSource source = resolver.resolveEntity(null, url);
        if (source == null) {
            source = new InputSource(url);
        }
        if (source.getSystemId() == null) {
            source.setSystemId(url);
        }
        LOG.info(Messages.format("mapping.loadingFrom", url));
        loadMappingInternal(mapping, resolver, source);
    } catch (SAXException ex) {
        throw new MappingException(ex);
    }
}