Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Tip: Load resources from the classpath

Using SAX EntityResolver with the Java classpath

Brett McLaughlin (brett@oreilly.com), Author and editor, O'Reilly and Associates
Brett McLaughlin has been working in computers since the Logo days (Remember the little triangle?). He currently specializes in building application infrastructure using Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom, Inc. Brett is one of the co-founders of the Java Apache project Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine.

Summary:  The SAX API offers the EntityResolver interface for locating resources in an XML document. This tip describes how to use this interface to resolve entities using the local Java classpath.

View more content in this series

Date:  01 Aug 2002
Level:  Intermediate

Comments:  

One of the basic building blocks of the SAX API is the process of entity resolution; this process is handled through the org.xml.sax.EntityResolver interface. Unfortunately, the EntityResolver interface is often ignored by all but the most advanced SAX developers. This shouldn't be the case, as this interface allows all sorts of performance improvements in your applications. If you use a clever EntityResolver implementation, you can dramatically speed up parsing and simplify resource management.

A simple entity resolution

At its simplest, an EntityResolver tells a SAX parser implementation how to look up resources specified in an XML document. Listing 1 shows an XML document fragment with an entity reference.


<footer>
  <smallText>&copyright;</smallText>
</footer>


This simple document fragment shown in Listing 1 illustrates an entity reference (named copyright). When a SAX parsing process runs across this entity reference, it has to resolve the entity into another piece of content. The parsing process first consults the document's DTD or XML schema for a definition like that shown in Listing 2.


<!ENTITY copyright 
    PUBLIC "-//IBM//TEXT DeveloperWorks Copyright//EN"
    "copyright.xml"
>


From this reference, the parser figures out the public ID (-//IBM//TEXT DeveloperWorks Copyright//EN) and system ID (copyright.xml) of the entity reference. The parsing process then checks to see if an EntityResolver implementation has been registered on the current XMLReader implementation. If so, it invokes the resolveEntity() method with the public and system IDs extracted from the DTD or schema. Listing 3 shows an EntityResolver implementation at its simplest.


import java.io.IOException;

import org.xml.sax.SAXException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

public class SimpleEntityResolver implements EntityResolver {

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

        // Returning null means use normal resolution
        return null;
    }
}


This implementation simply returns null every time which signals the parser that normal entity resolution should occur. The public ID and (subsequently) the system ID, are looked up through the Internet or local file system, as specified by the IDs of the reference. In this case, the parser resolves the public ID through the Internet, and if that fails, the parser searches for a local file called copyright.xml. The contents of this process are then inserted into the document.

Looking up resources on the Internet is time-consuming, and slows your application down every time the document is parsed. To combat this, it is common to download all required references and resources to a local file system. To ensure that these local files are used instead of the online resources, developers often change the constraint set of the XML and point the system ID of the entity reference definition to the local copy of a file or downloaded resource. Unfortunately, this turns out to be a bad idea: It ties the reference to a specific file, on a specific file system, in a specific location.

A better solution is to leave the document's constraints alone, and package all required resources in a jar file with the XML document and Java classes used in the application. This means you'll have your libraries (like an XML parser), your application files (Java classes), your XML documents and constraints, and any resources referenced by the XML (like the copyright.xml file). When you use a jar file, deployment is very simple, as all required resources are included in the jar file. Then, add this archive to the Java classpath.


Register the entity resolver

Your final step is to register an entity resolver that looks up entity references on the current classpath. Listing 4 shows just such a resolver.


import java.io.InputStream;
import java.io.IOException;

import org.xml.sax.SAXException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

public class ClassPathEntityResolver implements EntityResolver {

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

        InputSource inputSource = null;
      
        try {
            InputStream inputStream =    
                EntityResolver.class.getResourceAsStream(
                    systemId);
            inputSource = new InputSource(inputStream);
        } catch (Exception e) {
            // No action; just let the null InputSource pass through
        }

        // If nothing found, null is returned, for normal processing
        return inputSource;
    }
}


If the system ID of your XML reference is copyright.xml, you simply put the resource in the top level of your jar file, and ensure that it is named copyright.xml. You then register an instance of the ClassPathEntityResolver with your XMLReader, and let parsing and resolution take off.


Resources

About the author

Brett McLaughlin has been working in computers since the Logo days (Remember the little triangle?). He currently specializes in building application infrastructure using Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom, Inc. Brett is one of the co-founders of the Java Apache project Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


Forgot your IBM ID?


Forgot your password?
Change your password


By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)


By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML
ArticleID=12143
ArticleTitle=Tip: Load resources from the classpath
publish-date=08012002
author1-email=brett@oreilly.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).