Example usage for org.xml.sax EntityResolver resolveEntity

List of usage examples for org.xml.sax EntityResolver resolveEntity

Introduction

In this page you can find the example usage for org.xml.sax EntityResolver resolveEntity.

Prototype

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

Source Link

Document

Allow the application to resolve external entities.

Usage

From source file:de.micromata.genome.gwiki.page.gspt.taglibs.TagLibraryInfoImpl.java

protected void loadTagLibary(String uri) {
    Digester dig = new Digester();
    dig.setClassLoader(Thread.currentThread().getContextClassLoader());
    dig.setValidating(false);/*from   ww  w  .  jav a2  s . co  m*/
    final EntityResolver parentResolver = dig.getEntityResolver();
    dig.setEntityResolver(new EntityResolver() {

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

            InputStream is = null;
            if (StringUtils.equals(systemId, "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd") == true
                    || StringUtils.equals(publicId,
                            "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN") == true) {
                is = loadLocalDtd("web-jsptaglibrary_1_1.dtd");

            } else if (StringUtils.equals(systemId, "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd") == true
                    || StringUtils.equals(publicId,
                            "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN") == true) {
                is = loadLocalDtd("web-jsptaglibrary_1_2.dtd");
            }
            if (is == null) {
                if (parentResolver == null) {
                    GWikiLog.error("Cannot resolve entity: " + systemId);
                    return null;
                }
                return parentResolver.resolveEntity(publicId, systemId);
            }
            InputSource source = new InputSource(is);
            source.setPublicId(publicId);
            source.setSystemId(systemId);
            return source;
        }
    });
    dig.addCallMethod("taglib/tlib-version", "setTlibversion", 0);
    dig.addCallMethod("taglib/tlibversion", "setTlibversion", 0);
    dig.addCallMethod("taglib/jsp-version", "setJspversion", 0);
    dig.addCallMethod("taglib/jspversion", "setJspversion", 0);
    dig.addCallMethod("taglib/short-name", "setShortname", 0);
    dig.addCallMethod("taglib/shortname", "setShortname", 0);
    dig.addObjectCreate("taglib/tag", TagTmpInfo.class);
    dig.addCallMethod("taglib/tag/name", "setTagName", 0);
    dig.addCallMethod("taglib/tag/description", "setInfoString", 0);
    dig.addCallMethod("taglib/tag/tag-class", "setTagClassName", 0);
    dig.addCallMethod("taglib/tag/tagclass", "setTagClassName", 0);

    dig.addCallMethod("taglib/tag/body-content", "setBodycontent", 0);
    dig.addCallMethod("taglib/tag/bodycontent", "setBodycontent", 0);

    dig.addObjectCreate("taglib/tag/attribute", TagTmpAttributeInfo.class);
    dig.addCallMethod("taglib/tag/attribute/name", "setName", 0);
    dig.addCallMethod("taglib/tag/attribute/required", "setRequired", 0);
    dig.addCallMethod("taglib/tag/attribute/rtexprvalue", "setRtexprvalue", 0);
    dig.addSetNext("taglib/tag/attribute", "addAttributeInfo");
    dig.addSetNext("taglib/tag", "addTag");

    dig.push(this);
    try {
        InputStream is = loadImpl(uri);
        if (is == null) {
            throw new RuntimeException("could not load tld '" + uri + "'");
        }
        /*
         * ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); String text =
         * Converter.stringFromBytes(baos.toByteArray()); dig.parse(new StringReader(text));
         */
        dig.parse(is);
        rework();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.apache.xml.security.test.c14n.implementations.Canonicalizer20010315Test.java

/**
 * 3.7 Document Subsets/*from  ww  w  . ja  va2 s.c  o m*/
 *
 * @throws CanonicalizationException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-DocSubsets">the example from the spec</A>
 * @throws TransformerException
 */
public static void test37byNodeList()
        throws IOException, FileNotFoundException, SAXException, ParserConfigurationException,
        CanonicalizationException, InvalidCanonicalizerException, TransformerException {

    //String descri = "3.7 Document Subsets. (uncommented), c14n by NodeList";
    String fileIn = prefix + "in/37_input.xml";
    String fileRef = prefix + "in/37_c14n.xml";
    //String c14nURI = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
    //boolean validating = true;
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

    dfactory.setNamespaceAware(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();
    org.xml.sax.EntityResolver resolver = new TestVectorResolver();

    db.setEntityResolver(resolver);

    Document doc = db.parse(resolver.resolveEntity(null, fileIn));
    //J-
    Element nscontext = TestUtils.createDSctx(doc, "ietf", "http://www.ietf.org");

    String xpath = "(//. | //@* | //namespace::*)" + "[ " + "self::ietf:e1 or "
            + "(parent::ietf:e1 and not(self::text() or self::e2)) or "
            + "count(id(\"E3\")|ancestor-or-self::node()) = count(ancestor-or-self::node()) " + "]";
    //J+
    CachedXPathAPI xpathAPI = new CachedXPathAPI();

    NodeList nodes = xpathAPI.selectNodeList(doc, xpath, nscontext);
    Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    byte c14nBytes[] = c14n.canonicalizeXPathNodeSet(nodes);
    InputStream refStream = resolver.resolveEntity(null, fileRef).getByteStream();
    byte refBytes[] = JavaUtils.getBytesFromStream(refStream);
    assertEquals(new String(refBytes), new String(c14nBytes));
}

From source file:org.apache.xml.security.test.c14n.implementations.Canonicalizer20010315Test.java

/**
 * The XPath data model represents data using UCS characters.
 * Implementations MUST use XML processors that support UTF-8 and UTF-16
 * and translate to the UCS character domain. For UTF-16, the leading byte
 * order mark is treated as an artifact of encoding and stripped from the
 * UCS character data (subsequent zero width non-breaking spaces appearing
 * within the UTF-16 data are not removed) [UTF-16, Section 3.2]. Support
 * for ISO-8859-1 encoding is RECOMMENDED, and all other character encodings
 * are OPTIONAL.//  w  w w .j  av  a  2s .  c  o m
 *
 * $todo$ implement the test
 * @throws CanonicalizationException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
public static void testTranslationFromUTF16toUTF8()
        throws IOException, FileNotFoundException, SAXException, ParserConfigurationException,
        CanonicalizationException, InvalidCanonicalizerException, TransformerException {

    String val = "<UTF16>The german &amp;auml (which is Unicode &amp;#xE4;):  &quot;&#xE4;&quot;</UTF16>";
    byte utf16[] = convertToUTF16(val.getBytes());
    Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    byte c14nBytes[] = c14n.canonicalize(utf16);
    org.xml.sax.EntityResolver resolver = new TestVectorResolver();
    InputStream refStream = resolver.resolveEntity(null, prefix + "/in/testTranslationFromUTF16toUTF8.xml")
            .getByteStream();
    byte refBytes[] = JavaUtils.getBytesFromStream(refStream);
    boolean equal = java.security.MessageDigest.isEqual(refBytes, c14nBytes);

    assertTrue("Parser does not translate to UCS character domain", equal);
}

From source file:org.eclipse.gemini.blueprint.context.support.ChainedEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    boolean trace = log.isTraceEnabled();

    for (Map.Entry<EntityResolver, String> entry : resolvers.entrySet()) {
        EntityResolver entityResolver = entry.getKey();
        if (trace)
            log.trace("Trying to resolve entity [" + publicId + "|" + systemId + "] through resolver "
                    + entry.getValue());
        InputSource entity = entityResolver.resolveEntity(publicId, systemId);

        String resolvedMsg = (entity != null ? "" : "not ");
        if (trace)
            log.trace("Entity [" + publicId + "|" + systemId + "] was " + resolvedMsg
                    + "resolved through entity resolver " + entry.getValue());

        if (entity != null) {
            return entity;
        }//from  www .  j a v  a2s  .c  o m
    }
    return null;
}

From source file:org.opencms.xml.CmsXmlContentDefinition.java

/**
 * Factory method to unmarshal (read) a XML content definition instance from a given XML schema location.<p>
 * //w ww .j a v  a  2s.  c om
 * The XML content definition data to unmarshal will be read from the provided schema location using
 * an XML InputSource.<p>
 * 
 * @param schemaLocation the location from which to read the XML schema (system id)
 * @param resolver the XML entity resolver to use
 * 
 * @return a XML content definition instance unmarshalled from the InputSource
 * 
 * @throws CmsXmlException if something goes wrong
 * @throws SAXException if the XML schema location could not be converted to an XML InputSource
 * @throws IOException if the XML schema location could not be converted to an XML InputSource
 */
public static CmsXmlContentDefinition unmarshal(String schemaLocation, EntityResolver resolver)
        throws CmsXmlException, SAXException, IOException {

    schemaLocation = translateSchema(schemaLocation);
    CmsXmlContentDefinition result = getCachedContentDefinition(schemaLocation, resolver);
    if (result == null) {
        // content definition was not found in the cache, unmarshal the XML document
        InputSource source = resolver.resolveEntity(null, schemaLocation);
        result = unmarshalInternal(CmsXmlUtils.unmarshalHelper(source, resolver), schemaLocation, resolver);
    }
    return result;
}

From source file:org.opencms.xml.CmsXmlContentDefinition.java

/**
 * Internal method to unmarshal (read) a XML content definition instance from a XML document.<p>
 * //  ww  w.  j a  v  a 2 s. c  o m
 * It is assumed that the XML content definition cache has already been tested and the document 
 * has not been found in the cache. After the XML content definition has been successfully created, 
 * it is placed in the cache.<p>
 * 
 * @param document the XML document to generate a XML content definition from
 * @param schemaLocation the location from which the XML schema was read (system id)
 * @param resolver the XML entity resolver used by the given XML document
 * 
 * @return a XML content definition instance unmarshalled from the XML document
 * 
 * @throws CmsXmlException if something goes wrong
 */
private static CmsXmlContentDefinition unmarshalInternal(Document document, String schemaLocation,
        EntityResolver resolver) throws CmsXmlException {

    // analyze the document and generate the XML content type definition        
    Element root = document.getRootElement();
    if (!XSD_NODE_SCHEMA.equals(root.getQName())) {
        // schema node is required
        throw new CmsXmlException(Messages.get().container(Messages.ERR_CD_NO_SCHEMA_NODE_0));
    }

    List<Element> includes = CmsXmlGenericWrapper.elements(root, XSD_NODE_INCLUDE);
    if (includes.size() < 1) {
        // one include is required
        throw new CmsXmlException(Messages.get().container(Messages.ERR_CD_ONE_INCLUDE_REQUIRED_0));
    }

    Element include = includes.get(0);
    String target = validateAttribute(include, XSD_ATTRIBUTE_SCHEMA_LOCATION, null);
    if (!XSD_INCLUDE_OPENCMS.equals(target)) {
        // the first include must point to the default OpenCms standard schema include
        throw new CmsXmlException(
                Messages.get().container(Messages.ERR_CD_FIRST_INCLUDE_2, XSD_INCLUDE_OPENCMS, target));
    }

    boolean recursive = false;
    Set<CmsXmlContentDefinition> nestedDefinitions = new HashSet<CmsXmlContentDefinition>();
    if (includes.size() > 1) {
        // resolve additional, nested include calls
        for (int i = 1; i < includes.size(); i++) {

            Element inc = includes.get(i);
            String schemaLoc = validateAttribute(inc, XSD_ATTRIBUTE_SCHEMA_LOCATION, null);
            if (!(schemaLoc.equals(schemaLocation))) {
                InputSource source = null;
                try {
                    source = resolver.resolveEntity(null, schemaLoc);
                } catch (Exception e) {
                    throw new CmsXmlException(
                            Messages.get().container(Messages.ERR_CD_BAD_INCLUDE_1, schemaLoc));
                }
                CmsXmlContentDefinition xmlContentDefinition = unmarshal(source, schemaLoc, resolver);
                nestedDefinitions.add(xmlContentDefinition);
            } else {
                // recursion
                recursive = true;
            }
        }
    }

    List<Element> elements = CmsXmlGenericWrapper.elements(root, XSD_NODE_ELEMENT);
    if (elements.size() != 1) {
        // only one root element is allowed
        throw new CmsXmlException(Messages.get().container(Messages.ERR_CD_ROOT_ELEMENT_COUNT_1,
                XSD_INCLUDE_OPENCMS, new Integer(elements.size())));
    }

    // collect the data from the root element node
    Element main = elements.get(0);
    String name = validateAttribute(main, XSD_ATTRIBUTE_NAME, null);

    // now process the complex types
    List<Element> complexTypes = CmsXmlGenericWrapper.elements(root, XSD_NODE_COMPLEXTYPE);
    if (complexTypes.size() != 2) {
        // exactly two complex types are required
        throw new CmsXmlException(Messages.get().container(Messages.ERR_CD_COMPLEX_TYPE_COUNT_1,
                new Integer(complexTypes.size())));
    }

    // get the outer element sequence, this must be the first element 
    CmsXmlComplexTypeSequence outerSequence = validateComplexTypeSequence(complexTypes.get(0),
            nestedDefinitions);
    CmsXmlNestedContentDefinition outer = (CmsXmlNestedContentDefinition) outerSequence.getSequence().get(0);

    // make sure the inner and outer element names are as required
    String outerTypeName = createTypeName(name);
    String innerTypeName = createTypeName(outer.getName());
    validateAttribute(complexTypes.get(0), XSD_ATTRIBUTE_NAME, outerTypeName);
    validateAttribute(complexTypes.get(1), XSD_ATTRIBUTE_NAME, innerTypeName);
    validateAttribute(main, XSD_ATTRIBUTE_TYPE, outerTypeName);

    // generate the result XML content definition
    CmsXmlContentDefinition result = new CmsXmlContentDefinition(name, null, schemaLocation);

    // set the nested definitions
    result.m_includes = nestedDefinitions;
    // set the schema document
    result.m_schemaDocument = document;

    // the inner name is the element name set in the outer sequence
    result.setInnerName(outer.getName());
    if (recursive) {
        nestedDefinitions.add(result);
    }

    // get the inner element sequence, this must be the second element 
    CmsXmlComplexTypeSequence innerSequence = validateComplexTypeSequence(complexTypes.get(1),
            nestedDefinitions);

    // add the types from the main sequence node
    Iterator<I_CmsXmlSchemaType> it = innerSequence.getSequence().iterator();
    while (it.hasNext()) {
        result.addType(it.next());
    }

    // store if this content definition contains a xsd:choice sequence
    result.m_sequenceType = innerSequence.getSequenceType();
    result.m_choiceMaxOccurs = innerSequence.getChoiceMaxOccurs();

    // resolve the XML content handler information
    List<Element> annotations = CmsXmlGenericWrapper.elements(root, XSD_NODE_ANNOTATION);
    I_CmsXmlContentHandler contentHandler = null;
    Element appInfoElement = null;

    if (annotations.size() > 0) {
        List<Element> appinfos = CmsXmlGenericWrapper.elements(annotations.get(0), XSD_NODE_APPINFO);

        if (appinfos.size() > 0) {
            // the first appinfo node contains the specific XML content data 
            appInfoElement = appinfos.get(0);

            // check for a special content handler in the appinfo node
            Element handlerElement = appInfoElement.element("handler");
            if (handlerElement != null) {
                String className = handlerElement.attributeValue("class");
                if (className != null) {
                    contentHandler = OpenCms.getXmlContentTypeManager().getFreshContentHandler(className);
                }
            }
        }
    }

    if (contentHandler == null) {
        // if no content handler is defined, the default handler is used
        contentHandler = OpenCms.getXmlContentTypeManager()
                .getFreshContentHandler(CmsDefaultXmlContentHandler.class.getName());
    }

    // analyze the app info node with the selected XML content handler
    contentHandler.initialize(appInfoElement, result);
    result.m_contentHandler = contentHandler;

    result.freeze();

    if (resolver instanceof CmsXmlEntityResolver) {
        // put the generated content definition in the cache
        ((CmsXmlEntityResolver) resolver).cacheContentDefinition(schemaLocation, result);
    }

    return result;
}

From source file:org.springframework.osgi.context.support.DelegatedEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    boolean trace = log.isTraceEnabled();

    for (Iterator iterator = resolvers.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry entry = (Map.Entry) iterator.next();
        EntityResolver entityResolver = (EntityResolver) entry.getKey();
        if (trace)
            log.trace("Trying to resolve entity [" + publicId + "|" + systemId + "] through resolver "
                    + entry.getValue());
        InputSource entity = entityResolver.resolveEntity(publicId, systemId);

        String resolvedMsg = (entity != null ? "" : "not ");
        if (trace)
            log.trace("Entity [" + publicId + "|" + systemId + "] was " + resolvedMsg
                    + "resolved through entity resolver " + entry.getValue());

        if (entity != null) {
            return entity;
        }/*from w ww.j ava2  s .c o  m*/
    }
    return null;
}