advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Creating Content and Protocol Handlers in Java :

Creating Content and Protocol Handlers in Java

by Anghel Leonard

Certainly, you've noticed that when you "ask" for an Internet file, your browser has different ways to access it, depending on the file type. For example, if the file is a simple HTML or a common image type (.gif, .jpg), the browser becomes a viewer for it. However, if the file is a .pdf, a movie, or some other complex file type, the browser calls for external help. The browser identifies the file types, knows how to process the "simple" ones, and knows it needs special viewers or some plug-ins to handle complex file types.

Browsers also know how to "talk" with different kinds of Internet servers—HTTP servers, FTP servers, and any other kind of familiar server, depending on the kind of URL that's supplied.

Did you know that it's possible to simulate this behavior in Java? This article will show you how to create the Internet client, the Internet server (a minimal HTTP server), and a dedicated viewer for a new image type—also known as a content handler. You'll also learn how to use an existing content handler.

Working with an Existing Content Handler

When you "ask" for an Internet file, the browser usually inspects the MIME (Multipurpose Internet Mail Extensions) type of that file to determine how to process it. MIME types provide the browser with information about the file type—for example, if the file is HTML, then the MIME type will be text/html. If the file is a .jpg, then the MIME type will be image/jpeg, if the file type is a video MPEG, then the MIME type will be video/mpeg, etc.) Click here for a detailed description of existing MIME types.

Java allows you to create a network application that uses a URL to access a Web resource through the java.net.URLConnection class. Similar to a Web browser, this class inspects the MIME type of the received file and determines how to process it. It then calls a specialized class that understands the file format and puts that format into a "readable" form. These specialized classes are known as "content handlers" and they are subclasses of the java.net.ContentHandler abstract class. The practical purpose of a content handler is to extract an object specific to a MIME type from an URLConnection. You can extend this abstract class for new viewers, new MIME types, or for existing types that are not, by default, supported by Java. Java offers a default set of content handlers that cover the most used MIME types. The content handlers' class names-along with the names of the packages where you can find them—reflects the MIME type name. For instance, the MIME type image/png's content handler is in the sun.net.www.content.image package and its name is png.class. So, the sun.net.www.content path is fixed and the rest of it depends on the MIME type.

Note: You can usually find the sun.net.www.content... path in the <JDK_HOME>/jre/lib/rt.jar.

MIME TYPE

Class

package

audio/aiff

aiff.class

sun.net.www.content.audio

audio/basic

basic.class

sun.net.www.content.audio

audio/wav

wav.class

sun.net.www.content.audio

audio/x_aiff

x_aiff.class

sun.net.www.content.audio

image/gif

gif.class

sun.net.www.content.image

image/jpeg

jpeg.class

sun.net.www.content.image

image/png

png.class

sun.net.www.content.image

text/plain

plain.class

sun.net.www.content.text


Table 1: Java correspondence between MIME types and their content handlers.

When you access an Internet resource through URLConnection, Java joins the proper content handler with the resource MIME type. Java determines the proper content handler by using the MIME type to find the class it implements.

To create a content handler, you must first create a subclass of the ContentHandler class and override the getContent method. This method gets a URLConnection argument and returns an Object object that fits with the MIME type. The most effective way to use the object returned by this method is to make a cast conversion to the right object. Here's the syntax for the getContent method:

public abstract Object getContent(URLConnection URLcon) throws IOException
To join a content handler with a MIME type, you must use the java.net.Content HandlerFactory interface. Implementing this interface forces you to implement a behavior to the ContentHandlerFactory.createContentHandler method. This method is gets a string argument representing the MIME type and uses this string for returning the right content handler:
ContentHandler createContentHandler(String MIME_type)
To install a ContentHandlerFactory as your default type, you must call the URLConnection.setContentHandlerFactory method:
public static void setContentHandlerFactory(ContentHandlerFactory CHF)
To create a viewer for a MIME type for which a default content handler already exists, choose an ordinary .jpg image who's type matches a default content handler. Request the .jpg file from an HTTP server using the proper URL. Listing 1 shows the use of a minimal HTTP server (HTTPServer) that runs on the local host on port 80. It's using the URL http://localhost/image.jpg (though you can use any other .jpg image as long as you put it into the C:\JEditor\handlers directory—this is the default directory that is used by the HTTPServer for locating the requested resource). Of course, you can make minimal changes to the application for access any .jpg image on the Internet. All you have to do in this case, is to change the URL and eventually configure your application to pass through a proxy server.

To test this application, make sure you have in the classes for HTTPServer and JPGViewer in C:\JEditor\handlers. You also need in the same directory a .jpg file named image that can be any JPG image.


As shown in Figure 1, IE displays the same result as the JPGViewer application. This is because the image/jpeg MIME type is a "member" of the Internet MIME types standard.

Listing 2 coresponds to the MIME type, text/plain and can be used for viewing the content of any text file. The Java content handler for this MIME type is plain.class and is located in the sun.net.www.content.text package. This example uses the same HTTPServer and the URL http://localhost/test.txt. The text file is named test.txt and contains the text "This is a text file...". Of course, you can use any other text file—just remember to copy the text file into the C:\\JEditor\handlers directory, so that HTTPServer can find it.


Figure 2 shows how the test.txt file content is viewed by IE and in the ListTextFiles application.

ListTextFiles

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 DevX Skillbuilding from IBM developerWorks
 RIA Run Contest: Build Next-Gen Apps in Microsoft Silverlight 2
 Avaya DevConnect Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

SaaS Tool Offers Custom Database Development
Microsoft’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear
Red Hat Heads for the JON 2.0
Out with the Old, in with the New at JavaOne
Trolltech Expands WebKit Footprint
Oracle: Eating its Own Open Source Food
Big Money and Open Source May Not Compute
Open Source Embrace Gives Sun New Fans
NetBeans, OpenSolaris Also in Spotlight at JavaOne

Moving to VoIP: Should You Go It Alone?
Introduction to the WPF Command Framework
7.0, Microsoft's Lucky Version?
Will Hyper-V Make VMware This Decade's Netscape?
Eliminate Fragmentation Frustration with Netbiscuits
Taming Trees: Building Branching Structures
Clean Up Function Syntax Mess with decltype
Sutter Speaks: The Future of Concurrency
INTEL SCAVENGER HUNT, LENOVO X300 AND APPLE IPOD TOUCH GIVEAWAY (the "Giveaway")
Comparing Multi-Core Processors for Server Virtualization

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES