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.

     Avaya DevConnect Center
     Service Component Architecture/Service Data Objects Solution Center
     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 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%.

    Is .NET on Linux Finally Ready?
    Red Hat Takes on HPC Market, Microsoft
    Python's New Release Bridges the Gap
    No Flash Seen on iPhone Horizon
    Apple Yields to Complaints Over iPhone NDA
    Microsoft Shows Some Ankle With Visual Studio
    Gentoo Linux Cancels Distribution
    It's Official: Windows 7 at PDC, WinHEC
    Oracle Keeps Building on Spoils From BEA
    Intel, Oracle Head For 'The Cloud'

    "Supply Chain" SOA with SKOS
    Service Component Architecture in Real Life
    C++Ox: The Dawning of a New Standard
    Getting Started with Virtualization
    Master Complex Builds with MSBuild
    eCryptfs: Single-File Encryption in Linux
    CCXML in Action: A CCXML Auto Attendant
    Ballmer: Current Woes Won't Halt Tech, Microsoft
    Microsoft Uses VMworld to Hype Its Hypervisor
    Microsoft Charges Ahead in 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
    IBM Whitepaper: Innovative Collaboration to Advance Your Business
    Internet.com eBook: Real Life Rails
    Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
    Internet.com eBook: The Pros and Cons of Outsourcing
    Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
    Internet.com eBook: Best Practices for Developing a Web Site
    IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
    Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
    Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
    IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
    Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
    Go Parallel Article: Getting Started with TBB on Windows
    HP eBook: Storage Networking , Part 1
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
    HP Video: Is Your Data Center Ready for a Real World Disaster?
    Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
    HP On Demand Webcast: Virtualization in Action
    Go Parallel Video: Performance and Threading Tools for Game Developers
    Rackspace Hosting Center: Customer Videos
    Intel vPro Developer Virtual Bootcamp
    HP Disaster-Proof Solutions eSeminar
    HP On Demand Webcast: Discover the Benefits of Virtualization
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Microsoft Download: Silverlight 2 Software Development Kit Beta 2
    30-Day Trial: SPAMfighter Exchange Module
    Red Gate Download: SQL Toolbelt
    Iron Speed Designer Application Generator
    Microsoft Download: Silverlight 2 Beta 2 Runtime
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
    Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
    Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES