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.

 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 43
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%.

Google Hopes Chrome Will Help, Not Hurt Firefox
Remember Figlets? They're Back With Zend
Microsoft Readies an App Store Competitor?
Google: Chrome Browser Will Make Money
Sam Ramji: Microsoft's Man in Open Source
Google to Shake Up Browsers With Own Launch
Mozilla's Ubquity Mashup: For The Masses?
iPhone Users Just Want to Have Fun
Oops! I Fixed the Linux Kernel
Jim Zemlin: The New Center of Linux Gravity

Code Around C#'s Using Statement to Release Unmanaged Resources
Writing Functional Code with RDFa
BitLocker Brings Encryption to Windows Server 2008
Network Know-How: Exploring Network Algorithms
Create a Durable and Reliable WCF Service with MSMQ 4.0
The Baker's Dozen: 13 Tips for SQL Server 2008 and SSRS 2008
Book Excerpt: Microsoft Expression Blend Unleashed
Develop a Mobile RSS Feed the Easy Way
State of the Semantic Web: Know Where to Look
A 3D Exploration of the HTML Canvas Element

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
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES