Content Handlers
An Introduction with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
The Relevant Classes
ImageContentHandler
import java.io.*; import java.net.*; import javax.swing.ImageIcon; /** * A factory that constructs ImageContentHandler objects * * @author Prof. David Bernstein, James Madison University * @version 1.0 */ public class ImageContentHandler extends ContentHandler { /** * Given a URL connect stream positioned at the beginning of the * representation of an object, this method reads that stream and * creates an object from it. * * @param connection The URLConnection to read from */ public Object getContent(URLConnection connection) throws IOException { byte[] data; ImageIcon icon; InputStream is; int length; icon = null; is = connection.getInputStream(); length = connection.getContentLength(); data = new byte[length]; is.read(data); icon = new ImageIcon(data); return icon; } }
ImageContentHandlerFactory
import java.net.*; /** * A factory that constructs ImageContentHandler objects * * @author Prof. David Bernstein, James Madison University * @version 1.0 */ public class ImageContentHandlerFactory implements ContentHandlerFactory { /** * Creates a new ContentHandler to read an object from a * URLStreamHandler. * * @param mimetype The mimetype to create the content handler for */ public ContentHandler createContentHandler(String mimetype) { ContentHandler handler; handler = null; if (mimetype.startsWith("image")) { handler = new ImageContentHandler(); } return handler; } }
ImageViewer
BufferedReader in; ImageContentHandlerFactory factory; ImageIcon icon; Object content; String resource; URL url; // Tell the URLConnection class what ContentHandlerFactory to use factory = new ImageContentHandlerFactory(); URLConnection.setContentHandlerFactory(factory); in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("URL for the image: "); while ((resource = in.readLine()) != null) { // Connect to a URL url = new URL(resource); // Get the content content = url.getContent(); if (content != null) { // Cast the content appropriately icon = (ImageIcon)content; // Display the image label.setIcon(icon); } System.out.println("URL for the image: "); }