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, Part 2 :

Creating a Protocol Handler

There are also three steps to creating your own protocol handler:
  1. The first step consists of extending the URLStreamHandler class. This abstract class and is the superclass for every protocol handler. When you create a protocol handler class, it must be named Handler.class (shown in Listing 2) and it has to override the URLStreamHandler's openConnection methods:
    protected abstract URLConnection openConnection(URL url)throws IOException
    protected URLConnection openConnection(URL url, Proxy proxy) throws IOException
    
    As you can see, these methods return URLConnection objects. A URLConnection object can be used for creating input and/or output streaming to the specified resource. Obviously, the resource is specified by the URL argument.

    Another important method from the URLStreamHandler class is parseURL:

    protected void parseURL(URL url, String string, int start, int end):
    
    This method is parses strings that represent URLs (the string argument). The URL argument represents a URL object that keeps the result of the parsing process. The start and the end arguments delimitate the portion of the string argument that will be parsed. By default, the string argument is parsed to conform to the HTTP specification. When this isn't possible, you have to override this method. In this article, you will see an example of overriding the parseURL method for a particular kind of URL.
  2. The second step of creating a protocol handler involves defining a class that extends the URLConnection class. The URLConnection object returned by the openConnection method (overridden by the class that extends the URLStreamHandler) must be passed to the constructor of the new defined class. This class then implements the communication with the server. To do this, the new class generally overrides three URLConnection methods. These methods are: connect, getInputStream, and getContent. The syntaxes of these methods are listed below:
    • public abstract void connect()throws IOException: This s used to open a connection to a resource indicated by an URL.
    • public InputStream getInputStream()throws IOException: This is used to "read" from the opened connection. The important aspect of this method is that it reads only "clean" information. That means that the information doesn't contain the protocol particularities, like protocol headers. The information is returned into an InputStream object.
    • public Object getContent() throws IOException: This is used to determine the MIME type of the requested resource (by calling the getContentType method). The method uses the MIME type to associate itself with appropriate content handler. The object returned by this method represents the result of calling the content handler's getContent method.
  3. The third step consists of associating a protocol handler with a protocol using the URLStreamHandlerFactory interface. When you implement this interface, you also have to implement the createURLStreamHandler method. The createURLStreamHandler method receives a string argument representing the name of the protocol (for example, http, ftp, nntp, file—the last example indicates resources that are on the local machine.) and returns an object representing the appropriate protocol handler. Thus, the protocol name is the key for locating the right protocol handler.
    URLStreamHandler createURLStreamHandler(String protocol_name)
    
    In order to set an URLStreamHandlerFactory object as a default, you have to call setURLStreamHandlerFactory from the URL class. This method has the following syntax:
    public static void setURLStreamHandlerFactory(URLStreamHandlerFactory USHF)
    
    Notice in Listing 3 that the Handler and the xyURLConnection classes are placed in the sun.net.www.protocol.xy package. This helps Java to automatically find this protocol handler and saves you from installing it manually by calling the URL.setURLStreamHandlerFactory method and also saves you from defining a URLStreamHandlerFactory factory.
Normally, a new protocol handler is specific to a new protocol, but this article uses a simplified variant of the HTTP protocol named xy. The new protocol will be identified by a new kind of URL:
xy:X//host[:port]/path/resource
Look out—the new protocol handler recognizes only the content handler defined in the first part of this article and the resource can be only an .xy file.

As you can see, this URL is similar to the http://... URL. The difference is that this URL starts with the new protocol name, xy and after that the :X characters. The "X" character doesn't mean anything (but it could), it is merely used as an excuse for overriding the parseURL method. The default implementation of this method doesn't know how to identify the right protocol handler for this URL. The new protocol handler will implement the HTTP GET command for forwarding a request to the server and will process the answer using the content handler developed in Part 1. The HTTP server used in this example, HTTPServer.java, was also developed in Part 1.

Now, the protocol handler is ready! To test it, use the TestProtocolHandler class shown in Listing 4.

Notice that if you didn't place the Handler and xyURLConnection classes into the sun.net.www.protocol.xy package, you have to erase the comments from the PersonalStreamHandlerFactory class and from the line into the main method representing the manual instal. That's because, in this case, Java will not find any proper protocol handler in the automatic search.

To test the new protocol handler on a single machine, you have to first be sure that all the files are in their proper places.

In the C:\Jeditor\handlers directory:

  • The image.xy file
  • The classes for the HTTPServer application
  • The classes for the TestProtocolHandler application
In the sun.net.www.content.image package:
  • The xy.class class
In the the sun.net.www.protocol.xy package:
  • The Handler class
  • The xyURLConnection class
  • Of course, in the case of putting the content and protocol handler in the handlers directory, you have to modify them by removing the sun.net.www... packages from the path).

    After that, all you have to do is to run the HTTP server and the TestProtocolHandler application. The URL for testing this example is xy:X//localhost/image.xy, fixed in the TestProtocolHandler application.

    To see the difference between an Internet client that doesn't understand the above URL and your TestProtocolHandler client, you can run both. The result may look like Figure 1:


    Obviously, the Internet Explorer can't display the image because it doesn't understand this kind of URL.

    Home / Articles / Creating Content and Protocol Handlers in Java, Part 2 / 1 / 2 / Next Page

    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

    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
    Intel® Desktop Business Computing Solutions
    Intel: What Downturn?
    Managing the Evolving Data Center
    Implement Drag and Drop in Your Windows Forms Applications
    Processing Linked Web Data with XSLT

    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: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    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