Example usage for org.xml.sax InputSource setPublicId

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

Introduction

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

Prototype

public void setPublicId(String publicId) 

Source Link

Document

Set the public identifier for this input source.

Usage

From source file:org.betaconceptframework.astroboa.engine.definition.xsom.CmsEntityResolverForValidation.java

@Override
/**/*from   ww  w  . j  ava 2 s .co  m*/
 * According to XSOM library 
 * By setting EntityResolver to XSOMParser, you can redirect <xs:include>s and <xs:import>s to different resources.
 * For imports, the namespace URI of the target schema is passed as the public ID,
 * and the absolutized value of the schemaLocation attribute will be passed as the system ID. 
 */
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    if (systemId != null) {

        try {

            String schemaFilename = systemId;

            //We are only interested in file name
            if (schemaFilename.contains(File.separator)) {
                schemaFilename = StringUtils.substringAfterLast(systemId, File.separator);
            } else if (!File.separator.equals(schemaFilename.contains(CmsConstants.FORWARD_SLASH))
                    && schemaFilename.contains(CmsConstants.FORWARD_SLASH)) {
                //Perform the extra check in case File.separator is not '/' and it 
                //does not exist in the schema filename.
                //This case usually appears in a windows environment.
                schemaFilename = StringUtils.substringAfterLast(systemId, CmsConstants.FORWARD_SLASH);
            }

            if (definitionSources.containsKey(schemaFilename)) {
                InputStream inputStream = IOUtils.toInputStream(definitionSources.get(schemaFilename), "UTF-8");
                openStreams.add(inputStream);

                InputSource inputSource = new InputSource(inputStream);

                inputSource.setPublicId(publicId);
                inputSource.setSystemId(schemaFilename);

                return inputSource;
            }

            return entityResolverForBuiltInSchemas.resolveEntity(publicId, systemId);

        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    //Returning null allow XSD Parser to continue with default behavior
    //and will try to resolve entity using its own implementation
    return null;
}

From source file:org.betaconceptframework.astroboa.engine.definition.xsom.EntityResolverForBuiltInSchemas.java

@Override
/**// www.  j av a  2  s . com
 * According to XSOM library 
 * By setting EntityResolver to XSOMParser, you can redirect <xs:include>s and <xs:import>s to different resources.
 * For imports, the namespace URI of the target schema is passed as the public ID,
 * and the absolutized value of the schemaLocation attribute will be passed as the system ID. 
 */
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    if (publicId != null && publicId.startsWith(BetaConceptNamespaceConstants.ASTROBOA_SCHEMA_URI)
            && systemId != null) {

        try {

            String schemaFilename = systemId;

            //We are only interested in file name
            if (schemaFilename.contains(CmsConstants.FORWARD_SLASH)) {
                schemaFilename = StringUtils.substringAfterLast(systemId, CmsConstants.FORWARD_SLASH);
            }

            URL definitionFileURL = locateBuiltinDefinitionURL(schemaFilename);

            if (definitionFileURL != null) {

                InputSource is = new InputSource(definitionFileURL.openStream());

                /*
                 * SystemId is actual the path to the resource
                 * although its content has been loaded to input source.
                 * Provided value (sustemId) is not set because if in XSD file in the corresponding import's
                 * schemaLocation contains only the schema filename, then XSOM parser will
                 * consider it as a relative path and will prefix it with the correct absolute path.
                 * 
                 * For example, in cases where two different schemas, located in two different directories (portal-1.0.xsd and basicText-1.0.xsd),
                 * import schema astroboa-model-1.2.xsd, xs import will look like
                 * 
                 * <xs:import
                      namespace="http://www.betaconceptframework.org/schema/astroboa/model"
                      schemaLocation="astroboa-model-1.2.xsd" />
                 * 
                 * When XSOM parser will try to load astroboa-model-1.2.xsd, it will append
                 * schemaLocation with the path of the directory where each of the parent XSDs are located. 
                 * 
                 * SchemaLocation value refers to systemId and if it is provided in this input source, XSOM parser
                 * will have two different instances of InputSource referring to the same xsd file  (definitionFileURL),
                 * having the same publiId (namespace) but different systemIds (appended schemaLocation).
                 * 
                 * This situation causes XSOM parser to throw an exception when the second input source is loaded
                 * complaining that it found the same type(s) defined already, which is true since as far as XSOM parser
                 * concerns these input sources are not the same.
                 * 
                 * To overcome this, we set as system id the URL of the XSD file which is the same
                 * in both situations.
                 */
                is.setSystemId(definitionFileURL.toString());
                is.setPublicId(publicId);

                if (systemId.startsWith(BetaConceptNamespaceConstants.ASTROBOA_SCHEMA_URI)) {
                    logger.warn("Schema Location for XSD Schema " + schemaFilename
                            + ", which contains built in Astroboa model, is not relative but absolute."
                            + " Unless this absolute location really 'serves' XSD, there will be a problem "
                            + " when importing XML which contain xml elements derived from this Schema If this location is not real, then you are advised to delete it and leave only"
                            + "the schema file name. Nevertheless the contents of " + schemaFilename
                            + " have been found internally and have been successfully loaded to Astroboa");
                }

                return is;
            }

        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    //Returning null allow XSD Parser to continue with default behavior
    //and will try to resolve entity using its own implementation
    return resolveXmlSchemaRelatedToW3C(publicId, systemId);
}

From source file:org.exist.collections.Collection.java

private InputSource closeShieldInputSource(final InputSource source) {

    final InputSource protectedInputSource = new InputSource();
    protectedInputSource.setEncoding(source.getEncoding());
    protectedInputSource.setSystemId(source.getSystemId());
    protectedInputSource.setPublicId(source.getPublicId());

    if (source.getByteStream() != null) {
        //TODO consider AutoCloseInputStream
        final InputStream closeShieldByteStream = new CloseShieldInputStream(source.getByteStream());
        protectedInputSource.setByteStream(closeShieldByteStream);
    }/*w w  w  .j a v a2  s .  c om*/

    if (source.getCharacterStream() != null) {
        //TODO consider AutoCloseReader
        final Reader closeShieldReader = new CloseShieldReader(source.getCharacterStream());
        protectedInputSource.setCharacterStream(closeShieldReader);
    }

    return protectedInputSource;
}

From source file:org.exist.collections.MutableCollection.java

private InputSource closeShieldInputSource(final InputSource source) {
    final InputSource protectedInputSource = new InputSource();
    protectedInputSource.setEncoding(source.getEncoding());
    protectedInputSource.setSystemId(source.getSystemId());
    protectedInputSource.setPublicId(source.getPublicId());

    if (source.getByteStream() != null) {
        //TODO consider AutoCloseInputStream
        final InputStream closeShieldByteStream = new CloseShieldInputStream(source.getByteStream());
        protectedInputSource.setByteStream(closeShieldByteStream);
    }/*  w w  w.jav  a2 s .  c om*/

    if (source.getCharacterStream() != null) {
        //TODO consider AutoCloseReader
        final Reader closeShieldReader = new CloseShieldReader(source.getCharacterStream());
        protectedInputSource.setCharacterStream(closeShieldReader);
    }

    return protectedInputSource;
}

From source file:org.geoserver.wms.WMSTestSupport.java

/**
 * Utility method to run the transformation on tr with the provided request and returns the
 * result as a DOM/*from   w w  w.jav a 2s.  c o m*/
 * 
 * @param req
 *            , the Object to run the xml transformation against with {@code tr}, usually an
 *            instance of a {@link Request} subclass
 * @param tr
 *            , the transformer to run the transformation with and produce the result as a DOM
 * @param namespaceAware
 *            whether to use a namespace aware parser for the response or not
 */
public static Document transform(Object req, TransformerBase tr, boolean namespaceAware) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    tr.transform(req, out);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(namespaceAware);

    DocumentBuilder db = dbf.newDocumentBuilder();

    /**
     * Resolves everything to an empty xml document, useful for skipping errors due to missing
     * dtds and the like
     * 
     * @author Andrea Aime - TOPP
     */
    class EmptyResolver implements org.xml.sax.EntityResolver {
        public InputSource resolveEntity(String publicId, String systemId)
                throws org.xml.sax.SAXException, IOException {
            StringReader reader = new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            InputSource source = new InputSource(reader);
            source.setPublicId(publicId);
            source.setSystemId(systemId);

            return source;
        }
    }
    db.setEntityResolver(new EmptyResolver());

    // System.out.println(out.toString());

    Document doc = db.parse(new ByteArrayInputStream(out.toByteArray()));
    return doc;
}

From source file:org.impalaframework.xml.schema.ClassPathSchemaResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    if (systemId != null) {
        if (resourceLocation != null) {
            Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
            InputSource source = new InputSource(resource.getInputStream());
            source.setPublicId(publicId);
            source.setSystemId(systemId);

            if (logger.isDebugEnabled()) {
                logger.debug("Found XML schema for system id in '" + systemId + "' in classpath: "
                        + resourceLocation);
            }/*from   w w w.  ja  va2s. c  o  m*/

            return source;
        }
    }
    return null;
}

From source file:org.mule.config.MuleDtdResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException {
    logger.debug("Trying to resolve XML entity with public ID: " + publicId + " and system ID: " + systemId);

    InputSource source = null;
    currentXsl = null;//from   w ww .  jav  a  2  s.com
    if (delegate != null) {
        source = delegate.resolveEntity(publicId, systemId);
    }
    if ((source == null) && StringUtils.isNotBlank(systemId) && systemId.endsWith(".dtd")) {
        String[] tokens = systemId.split("/");
        String dtdFile = tokens[tokens.length - 1];
        logger.debug("Looking on classpath for " + SEARCH_PATH + dtdFile);

        InputStream is = IOUtils.getResourceAsStream(SEARCH_PATH + dtdFile, getClass(), /* tryAsFile */
                true, /* tryAsUrl */false);
        if (is != null) {
            source = new InputSource(is);
            source.setPublicId(publicId);
            source.setSystemId(systemId);
            logger.debug("Found on classpath mule DTD: " + systemId);
            currentXsl = xsl;
            return source;
        }
        logger.debug("Could not find dtd resource on classpath: " + SEARCH_PATH + dtdFile);
    }
    return source;
}

From source file:org.mycore.common.xml.MCREntityResolver.java

@Override
public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId)
        throws SAXException, IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(MessageFormat.format("Resolving: \nname: {0}\npublicId: {1}\nbaseURI: {2}\nsystemId: {3}",
                name, publicId, baseURI, systemId));
    }//  w  ww  .  j  a v  a 2 s  .  c  om
    InputSource entity = catalogResolver.resolveEntity(name, publicId, baseURI, systemId);
    if (entity != null) {
        return resolvedEntity(entity);
    }
    if (systemId == null) {
        return null; // Use default resolver
    }

    if (systemId.length() == 0) {
        // if you overwrite SYSTEM by empty String in XSL
        return new InputSource(new StringReader(""));
    }

    //resolve against base:
    URI absoluteSystemId = resolveRelativeURI(baseURI, systemId);
    if (absoluteSystemId.isAbsolute() && uriExists(absoluteSystemId)) {
        InputSource inputSource = new InputSource(absoluteSystemId.toString());
        inputSource.setPublicId(publicId);
        return resolvedEntity(inputSource);
    }
    //required for XSD files that are usually classpath resources
    InputSource is = getCachedResource("/" + systemId);
    if (is == null) {
        return null;
    }
    is.setPublicId(publicId);
    return resolvedEntity(is);
}

From source file:org.pentaho.reporting.libraries.xmlns.parser.ParserEntityResolver.java

/**
 * Allow the application to resolve external entities.
 * <p/>//from  w  w w .j  av  a 2  s .c o  m
 * Resolves the DTD definition to point to a local copy, if the specified public ID is known to this resolver.
 *
 * @param publicId the public ID.
 * @param systemId the system ID.
 * @return The input source.
 */
public InputSource resolveEntity(final String publicId, final String systemId) {
    try {
        // cannot validate without public id ...
        if (publicId == null) {
            //Log.debug ("No PUBLIC ID, cannot continue");
            if (systemId != null) {
                final URL location = getDTDLocation(systemId);
                if (location != null) {
                    final InputSource inputSource = new InputSource(location.openStream());
                    inputSource.setSystemId(systemId);
                    return inputSource;
                }
            }
            return null;
        }

        final URL location = getDTDLocation(publicId);
        if (location != null) {
            final InputSource inputSource = new InputSource(location.openStream());
            inputSource.setSystemId(systemId);
            inputSource.setPublicId(publicId);
            return inputSource;
        }
        final String message = getDeprecatedDTDMessage(publicId);
        if (message != null) {
            logger.info(message);
        } else {
            logger.info("A public ID was given for the document, but it was unknown or invalid.");
        }
        return null;
    } catch (IOException ioe) {
        logger.warn("Unable to open specified DTD", ioe);
    }
    return null;
}

From source file:org.quartz.xml.JobSchedulingDataProcessor.java

/**
 * EntityResolver interface./*www .  ja v  a2s  .c  o  m*/
 * <p/>
 * Allow the application to resolve external entities.
 * <p/>
 * Until <code>quartz.dtd</code> has a public ID, it must resolved as a
 * system ID. Here's the order of resolution (if one fails, continue to the
 * next).
 * <ol>
 * <li>Tries to resolve the <code>systemId</code> with <code>ClassLoader.getResourceAsStream(String)</code>.
 * </li>
 * <li>If the <code>systemId</code> starts with <code>QUARTZ_SYSTEM_ID_PREFIX</code>,
 * then resolve the part after <code>QUARTZ_SYSTEM_ID_PREFIX</code> with
 * <code>ClassLoader.getResourceAsStream(String)</code>.</li>
 * <li>Else try to resolve <code>systemId</code> as a URL.
 * <li>If <code>systemId</code> has a colon in it, create a new <code>URL</code>
 * </li>
 * <li>Else resolve <code>systemId</code> as a <code>File</code> and
 * then call <code>File.toURL()</code>.</li>
 * </li>
 * </ol>
 * <p/>
 * If the <code>publicId</code> does exist, resolve it as a URL.  If the
 * <code>publicId</code> is the Quartz public ID, then resolve it locally.
 * 
 * @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 SAXException
 *              Any SAX exception, possibly wrapping another exception.
 * @exception IOException
 *              A Java-specific IO exception, possibly the result of
 *              creating a new InputStream or Reader for the InputSource.
 */
public InputSource resolveEntity(String publicId, String systemId) {
    InputSource inputSource = null;

    InputStream is = null;

    URL url = null;

    try {
        if (publicId == null) {
            if (systemId != null) {
                // resolve Quartz Schema locally
                if (QUARTZ_SCHEMA.equals(systemId)) {
                    is = getClass().getResourceAsStream(QUARTZ_XSD);
                } else {
                    is = getInputStream(systemId);

                    if (is == null) {
                        int start = systemId.indexOf(QUARTZ_SYSTEM_ID_PREFIX);

                        if (start > -1) {
                            String fileName = systemId.substring(QUARTZ_SYSTEM_ID_PREFIX.length());
                            is = getInputStream(fileName);
                        } else {
                            if (systemId.indexOf(':') == -1) {
                                File file = new java.io.File(systemId);
                                url = file.toURL();
                            } else {
                                url = new URL(systemId);
                            }

                            is = url.openStream();
                        }
                    }
                }
            }
        } else {
            // resolve Quartz DTD locally
            if (QUARTZ_PUBLIC_ID.equals(publicId)) {
                is = getClass().getResourceAsStream(QUARTZ_DTD);
            } else {
                url = new URL(systemId);
                is = url.openStream();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            inputSource = new InputSource(is);
            inputSource.setPublicId(publicId);
            inputSource.setSystemId(systemId);
        }

    }

    return inputSource;
}