1 /* URLConnection.java -- Abstract superclass for reading from URL's
2 Copyright (C) 1998, 2002, 2003, 2004, 2006 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
41 import gnu.classpath.SystemProperties;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.OutputStream;
46 import java.security.AllPermission;
47 import java.security.Permission;
48 import java.text.ParsePosition;
49 import java.text.SimpleDateFormat;
50 import java.util.Collections;
51 import java.util.Date;
52 import java.util.List;
53 import java.util.Locale;
55 import java.util.StringTokenizer;
58 * Written using on-line Java Platform 1.2 API Specification, as well
59 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
60 * Status: One guessContentTypeFrom... methods not implemented.
61 * getContent method assumes content type from response; see comment there.
64 * This class models a connection that retrieves the information pointed
65 * to by a URL object. This is typically a connection to a remote node
66 * on the network, but could be a simple disk read.
68 * A URLConnection object is normally created by calling the openConnection()
69 * method of a URL object. This method is somewhat misnamed because it does
70 * not actually open the connection. Instead, it return an unconnected
71 * instance of this object. The caller then has the opportunity to set
72 * various connection options prior to calling the actual connect() method.
74 * After the connection has been opened, there are a number of methods in
75 * this class that access various attributes of the data, typically
76 * represented by headers sent in advance of the actual data itself.
78 * Also of note are the getInputStream and getContent() methods which allow
79 * the caller to retrieve the actual data from the connection. Note that
80 * for some types of connections, writing is also allowed. The setDoOutput()
81 * method must be called prior to connecing in order to enable this, then
82 * the getOutputStream method called after the connection in order to
83 * obtain a stream to write the output to.
85 * The getContent() method is of particular note. This method returns an
86 * Object that encapsulates the data returned. There is no way do determine
87 * the type of object that will be returned in advance. This is determined
88 * by the actual content handlers as described in the description of that
91 * @author Aaron M. Renn (arenn@urbanophile.com)
92 * @author Warren Levy (warrenl@cygnus.com)
94 public abstract class URLConnection
97 * This is an object that maps filenames to MIME types. The interface
98 * to do this is implemented by this class, so just create an empty
99 * instance and store it here.
101 private static FileNameMap fileNameMap;
104 * This is the ContentHandlerFactory set by the caller, if any
106 private static ContentHandlerFactory factory;
109 * This is the default value that will be used to determine whether or
110 * not user interaction should be allowed.
112 private static boolean defaultAllowUserInteraction;
115 * This is the default flag indicating whether or not to use caches to
116 * store the data returned from a server
118 private static boolean defaultUseCaches = true;
121 * Default internal content handler factory.
123 private static ContentHandlerFactory defaultFactory
124 = new gnu.java.net.DefaultContentHandlerFactory();
127 * This variable determines whether or not interaction is allowed with
128 * the user. For example, to prompt for a username and password.
130 protected boolean allowUserInteraction;
133 * Indicates whether or not a connection has been established to the
134 * destination specified in the URL
136 protected boolean connected;
139 * Indicates whether or not input can be read from this URL
141 protected boolean doInput = true;
144 * Indicates whether or not output can be sent to this URL
146 protected boolean doOutput;
149 * If this flag is set, the protocol is allowed to cache data whenever
150 * it can (caching is not guaranteed). If it is not set, the protocol
151 * must a get a fresh copy of the data.
153 * This field is set by the setUseCaches method and returned by the
154 * getUseCaches method.
156 * Its default value is that determined by the last invocation of
157 * setDefaultUseCaches
159 protected boolean useCaches;
162 * If this value is non-zero, then the connection will only attempt to
163 * fetch the document pointed to by the URL if the document has been
164 * modified more recently than the date set in this variable. That date
165 * should be specified as the number of seconds since 1/1/1970 GMT.
167 protected long ifModifiedSince;
170 * This is the URL associated with this connection
174 private static SimpleDateFormat[] dateFormats;
175 private static boolean dateformats_initialized;
178 * The connection timeout period.
180 private int connectTimeout;
183 * The read timeout period.
185 private int readTimeout;
187 /* Cached ParsePosition, used when parsing dates. */
188 private ParsePosition position;
191 * Creates a URL connection to a given URL. A real connection is not made.
192 * Use <code>connect()</code> to do this.
194 * @param url The Object to create the URL connection to
196 * @see URLConnection#connect()
198 protected URLConnection(URL url)
200 // Set up all our instance variables
202 allowUserInteraction = defaultAllowUserInteraction;
203 useCaches = defaultUseCaches;
207 * Establishes the actual connection to the URL associated with this
210 * @exception IOException if an error occurs
212 public abstract void connect() throws IOException;
215 * Returns the URL object associated with this connection
217 * @return The URL for this connection.
225 * Returns the connection timeout speed, in milliseconds, or zero if
226 * the timeout is infinite or not set.
228 * @return The timeout.
232 public int getConnectTimeout()
234 return connectTimeout;
238 * Set the connection timeout speed, in milliseconds, or zero if the timeout
239 * is to be considered infinite. Note that in certain socket
240 * implementations/platforms this method may not have any effect.
242 * Throws an <code>IllegalArgumentException</code> if timeout < 0.
244 * @param timeout the timeout, in milliseconds.
248 public void setConnectTimeout(int timeout)
249 throws IllegalArgumentException
252 throw new IllegalArgumentException("Timeout must be 0 or positive.");
253 connectTimeout = timeout;
257 * Returns the read timeout, in milliseconds, or zero if the timeout
258 * is infinite or not set.
260 * @return The timeout.
262 * @see #setReadTimeout
266 public int getReadTimeout()
272 * Set the read timeout, in milliseconds, or zero if the timeout
273 * is to be considered infinite. Note that in certain socket
274 * implementations/platforms this method may not have any effect.
276 * Throws an <code>IllegalArgumentException</code> if timeout < 0.
278 * @param timeout - The timeout, in milliseconds.
280 * @throws IllegalArgumentException if timeout is negative.
282 * @see #getReadTimeout
286 public void setReadTimeout(int timeout)
287 throws IllegalArgumentException
290 throw new IllegalArgumentException("Timeout must be 0 or positive.");
291 readTimeout = timeout;
295 * Returns the value of the content-length header field or -1 if the value
296 * is not known or not present.
298 * @return The content-length field
300 public int getContentLength()
302 return getHeaderFieldInt("content-length", -1);
306 * Returns the the content-type of the data pointed to by the URL. This
307 * method first tries looking for a content-type header. If that is not
308 * present, it attempts to use the file name to determine the content's
309 * MIME type. If that is unsuccessful, the method returns null. The caller
310 * may then still attempt to determine the MIME type by a call to
311 * guessContentTypeFromStream()
313 * @return The content MIME type
315 public String getContentType()
317 return getHeaderField("content-type");
321 * Returns the value of the content-encoding field or null if it is not
322 * known or not present.
324 * @return The content-encoding field
326 public String getContentEncoding()
328 return getHeaderField("content-encoding");
332 * Returns the value of the expires header or 0 if not known or present.
333 * If populated, the return value is number of seconds since midnight
336 * @return The expiration time.
338 public long getExpiration()
340 return getHeaderFieldDate("expires", 0L);
344 * Returns the date of the document pointed to by the URL as reported in
345 * the date field of the header or 0 if the value is not present or not
346 * known. If populated, the return value is number of seconds since
347 * midnight on 1/1/1970 GMT.
349 * @return The document date
351 public long getDate()
353 return getHeaderFieldDate("date", 0L);
357 * Returns the value of the last-modified header field or 0 if not known known
358 * or not present. If populated, the return value is the number of seconds
359 * since midnight on 1/1/1970.
361 * @return The last modified time
363 public long getLastModified()
365 return getHeaderFieldDate("last-modified", 0L);
369 * Return a String representing the header value at the specified index.
370 * This allows the caller to walk the list of header fields. The analogous
371 * {@link #getHeaderField(int)} method allows access to the corresponding
372 * key for this header field
374 * @param index The index into the header field list to retrieve the value for
376 * @return The header value or null if index is past the end of the headers
378 public String getHeaderField(int index)
380 // Subclasses for specific protocols override this.
385 * Returns a String representing the value of the header field having
386 * the named key. Returns null if the header field does not exist.
388 * @param name The key of the header field
390 * @return The value of the header field as a String
392 public String getHeaderField(String name)
394 // Subclasses for specific protocols override this.
399 * Returns an unmodifiable Map containing all sent header fields.
401 * @return The map of header fields. The map consists of String keys with
402 * an unmodifiable List of String objects as value.
406 public Map<String,List<String>> getHeaderFields()
408 // Subclasses for specific protocols override this.
409 return Collections.emptyMap();
413 * Returns the value of the named header field as an int. If the field
414 * is not present or cannot be parsed as an integer, the default value
417 * @param name The header field key to lookup
418 * @param defaultValue The defaule value if the header field is not found
419 * or can't be parsed.
421 * @return The value of the header field or the default value if the field
422 * is missing or malformed
424 public int getHeaderFieldInt(String name, int defaultValue)
426 String value = getHeaderField(name);
433 return Integer.parseInt(value);
435 catch (NumberFormatException e)
442 * Returns the value of the named header field as a date. This date will
443 * be the number of seconds since midnight 1/1/1970 GMT or the default
444 * value if the field is not present or cannot be converted to a date.
446 * @param name The name of the header field
447 * @param defaultValue The default date if the header field is not found
448 * or can't be converted.
450 * @return The date value of the header filed or the default value
451 * if the field is missing or malformed
453 public long getHeaderFieldDate(String name, long defaultValue)
455 if (! dateformats_initialized)
456 initializeDateFormats();
458 if (position == null)
459 position = new ParsePosition(0);
461 long result = defaultValue;
462 String str = getHeaderField(name);
466 for (int i = 0; i < dateFormats.length; i++)
468 SimpleDateFormat df = dateFormats[i];
469 position.setIndex(0);
470 position.setErrorIndex(0);
471 Date date = df.parse(str, position);
473 return date.getTime();
481 * Returns a String representing the header key at the specified index.
482 * This allows the caller to walk the list of header fields. The analogous
483 * {@link #getHeaderField(int)} method allows access to the corresponding
484 * value for this tag.
486 * @param index The index into the header field list to retrieve the key for.
488 * @return The header field key or null if index is past the end
491 public String getHeaderFieldKey(int index)
493 // Subclasses for specific protocols override this.
498 * This method returns the content of the document pointed to by the
499 * URL as an Object. The type of object depends on the MIME type of
500 * the object and particular content hander loaded. Most text type
501 * content handlers will return a subclass of
502 * <code>InputStream</code>. Images usually return a class that
503 * implements <code>ImageProducer</code>. There is not guarantee
504 * what type of object will be returned, however.
506 * <p>This class first determines the MIME type of the content, then
507 * creates a ContentHandler object to process the input. If the
508 * <code>ContentHandlerFactory</code> is set, then that object is
509 * called to load a content handler, otherwise a class called
510 * gnu.java.net.content.<content_type> is tried. If this
511 * handler does not exist, the method will simple return the
512 * <code>InputStream</code> returned by
513 * <code>getInputStream()</code>. Note that the default
514 * implementation of <code>getInputStream()</code> throws a
515 * <code>UnknownServiceException</code> so subclasses are encouraged
516 * to override this method.</p>
518 * @return the content
520 * @exception IOException If an error with the connection occurs.
521 * @exception UnknownServiceException If the protocol does not support the
522 * content type at all.
524 public Object getContent() throws IOException
529 // FIXME: Doc indicates that other criteria should be applied as
530 // heuristics to determine the true content type, e.g. see
531 // guessContentTypeFromName() and guessContentTypeFromStream methods
532 // as well as FileNameMap class & fileNameMap field & get/set methods.
533 String type = getContentType();
534 ContentHandler ch = getContentHandler(type);
537 return ch.getContent(this);
539 return getInputStream();
543 * Retrieves the content of this URLConnection
545 * @param classes The allowed classes for the content
547 * @return the content
549 * @exception IOException If an error occurs
550 * @exception UnknownServiceException If the protocol does not support the
553 public Object getContent(Class[] classes)
558 String type = getContentType();
559 ContentHandler ch = getContentHandler(type);
561 return ch.getContent(this, classes);
562 throw new UnknownServiceException("protocol does not support the content type");
566 * This method returns a <code>Permission</code> object representing the
567 * permissions required to access this URL. This method returns
568 * <code>java.security.AllPermission</code> by default. Subclasses should
569 * override it to return a more specific permission. For example, an
570 * HTTP URL should return an instance of <code>SocketPermission</code>
571 * for the appropriate host and port.
573 * Note that because of items such as HTTP redirects, the permission
574 * object returned might be different before and after connecting.
576 * @return A Permission object
578 * @exception IOException If the computation of the permission requires
579 * network or file I/O and an exception occurs while computing it
581 public Permission getPermission() throws IOException
583 // Subclasses may override this.
584 return new AllPermission();
588 * Returns an InputStream for this connection. As this default
589 * implementation returns null, subclasses should override this method
591 * @return An InputStream for this connection
593 * @exception IOException If an error occurs
594 * @exception UnknownServiceException If the protocol does not support input
596 public InputStream getInputStream() throws IOException
598 // Subclasses for specific protocols override this.
599 throw new UnknownServiceException("Protocol " + url.getProtocol()
600 + " does not support input.");
604 * Returns an OutputStream for this connection. As this default
605 * implementation returns null, subclasses should override this method
607 * @return An OutputStream for this connection
609 * @exception IOException If an error occurs
610 * @exception UnknownServiceException If the protocol does not support output
612 public OutputStream getOutputStream() throws IOException
614 // Subclasses for specific protocols override this.
615 throw new UnknownServiceException("Protocol " + url.getProtocol()
616 + " does not support output.");
620 * The methods prints the value of this object as a String by calling the
621 * toString() method of its associated URL. Overrides Object.toString()
623 * @return A String representation of this object
625 public String toString()
627 return this.getClass().getName() + ":" + url.toString();
631 * Sets the value of a flag indicating whether or not input is going
632 * to be done for this connection. This default to true unless the
633 * doOutput flag is set to false, in which case this defaults to false.
635 * @param input <code>true</code> if input is to be done,
636 * <code>false</code> otherwise
638 * @exception IllegalStateException If already connected
640 public void setDoInput(boolean input)
643 throw new IllegalStateException("Already connected");
649 * Returns the value of a flag indicating whether or not input is going
650 * to be done for this connection. This default to true unless the
651 * doOutput flag is set to false, in which case this defaults to false.
653 * @return true if input is to be done, false otherwise
655 public boolean getDoInput()
661 * Sets a boolean flag indicating whether or not output will be done
662 * on this connection. The default value is false, so this method can
663 * be used to override the default
665 * @param output ture if output is to be done, false otherwise
667 * @exception IllegalStateException If already connected
669 public void setDoOutput(boolean output)
672 throw new IllegalStateException("Already connected");
678 * Returns a boolean flag indicating whether or not output will be done
679 * on this connection. This defaults to false.
681 * @return true if output is to be done, false otherwise
683 public boolean getDoOutput()
689 * Sets a boolean flag indicating whether or not user interaction is
690 * allowed for this connection. (For example, in order to prompt for
691 * username and password info.
693 * @param allow true if user interaction should be allowed, false otherwise.
695 * @exception IllegalStateException If already connected
697 public void setAllowUserInteraction(boolean allow)
700 throw new IllegalStateException("Already connected");
702 allowUserInteraction = allow;
706 * Returns a boolean flag indicating whether or not user interaction is
707 * allowed for this connection. (For example, in order to prompt for
708 * username and password info.
710 * @return true if user interaction is allowed, false otherwise
712 public boolean getAllowUserInteraction()
714 return allowUserInteraction;
718 * Sets the default flag for whether or not interaction with a user
719 * is allowed. This will be used for all connections unless overridden
721 * @param allow true to allow user interaction, false otherwise
723 public static void setDefaultAllowUserInteraction(boolean allow)
725 defaultAllowUserInteraction = allow;
729 * Returns the default flag for whether or not interaction with a user
730 * is allowed. This will be used for all connections unless overridden
732 * @return true if user interaction is allowed, false otherwise
734 public static boolean getDefaultAllowUserInteraction()
736 return defaultAllowUserInteraction;
740 * Sets a boolean flag indicating whether or not caching will be used
741 * (if possible) to store data downloaded via the connection.
743 * @param usecaches The new value
745 * @exception IllegalStateException If already connected
747 public void setUseCaches(boolean usecaches)
750 throw new IllegalStateException("Already connected");
752 useCaches = usecaches;
756 * Returns a boolean flag indicating whether or not caching will be used
757 * (if possible) to store data downloaded via the connection.
759 * @return true if caching should be used if possible, false otherwise
761 public boolean getUseCaches()
767 * Sets the ifModified since instance variable. If this value is non
768 * zero and the underlying protocol supports it, the actual document will
769 * not be fetched unless it has been modified since this time. The value
770 * passed should be 0 if this feature is to be disabled or the time expressed
771 * as the number of seconds since midnight 1/1/1970 GMT otherwise.
773 * @param ifmodifiedsince The new value in milliseconds
774 * since January 1, 1970 GMT
776 * @exception IllegalStateException If already connected
778 public void setIfModifiedSince(long ifmodifiedsince)
781 throw new IllegalStateException("Already connected");
783 ifModifiedSince = ifmodifiedsince;
787 * Returns the ifModified since instance variable. If this value is non
788 * zero and the underlying protocol supports it, the actual document will
789 * not be fetched unless it has been modified since this time. The value
790 * returned will be 0 if this feature is disabled or the time expressed
791 * as the number of seconds since midnight 1/1/1970 GMT otherwise
793 * @return The ifModifiedSince value
795 public long getIfModifiedSince()
797 return ifModifiedSince;
801 * Returns the default value used to determine whether or not caching
802 * of documents will be done when possible.
804 * @return true if caches will be used, false otherwise
806 public boolean getDefaultUseCaches()
808 return defaultUseCaches;
812 * Sets the default value used to determine whether or not caching
813 * of documents will be done when possible.
815 * @param use true to use caches if possible by default, false otherwise
817 public void setDefaultUseCaches(boolean use)
819 defaultUseCaches = use;
823 * Sets the value of the named request property.
824 * This method does overwrite the value of existing properties with
827 * @param key The name of the property
828 * @param value The value of the property
830 * @exception IllegalStateException If already connected
831 * @exception NullPointerException If key is null
833 * @see URLConnection#getRequestProperty(String key)
834 * @see URLConnection#addRequestProperty(String key, String value)
838 public void setRequestProperty(String key, String value)
841 throw new IllegalStateException("Already connected");
844 throw new NullPointerException("key is null");
846 // Do nothing unless overridden by subclasses that support setting
847 // header fields in the request.
851 * Adds a new request property by a key/value pair.
852 * This method does not overwrite existing properties with the same key.
854 * @param key Key of the property to add
855 * @param value Value of the Property to add
857 * @exception IllegalStateException If already connected
858 * @exception NullPointerException If key is null
860 * @see URLConnection#getRequestProperty(String)
861 * @see URLConnection#setRequestProperty(String, String)
865 public void addRequestProperty(String key, String value)
868 throw new IllegalStateException("Already connected");
871 throw new NullPointerException("key is null");
873 // Do nothing unless overridden by subclasses that support adding
874 // header fields in the request.
878 * Returns the value of the named request property.
880 * @param key The name of the property
882 * @return Value of the property, or <code>null</code> if key is null.
884 * @exception IllegalStateException If already connected
886 * @see URLConnection#setRequestProperty(String, String)
887 * @see URLConnection#addRequestProperty(String, String)
889 public String getRequestProperty(String key)
892 throw new IllegalStateException("Already connected");
894 // Overridden by subclasses that support reading header fields from the
900 * Returns an unmodifiable Map containing the request properties.
902 * @return The map of properties. The map consists of String keys with an
903 * unmodifiable List of String objects as value.
905 * @exception IllegalStateException If already connected
909 public Map<String,List<String>> getRequestProperties()
912 throw new IllegalStateException("Already connected");
914 // Overridden by subclasses that support reading header fields from the
916 return Collections.emptyMap();
920 * Sets the default value of a request property. This will be used
921 * for all connections unless the value of the property is manually
924 * @param key The request property name the default is being set for
925 * @param value The value to set the default to
927 * @deprecated 1.3 The method setRequestProperty should be used instead.
928 * This method does nothing now.
930 * @see URLConnection#setRequestProperty(String, String)
932 public static void setDefaultRequestProperty(String key, String value)
934 // This method does nothing since JDK 1.3.
938 * Returns the default value of a request property. This will be used
939 * for all connections unless the value of the property is manually
942 * @param key The request property to return the default value of
944 * @return The value of the default property or null if not available
946 * @deprecated 1.3 The method getRequestProperty should be used instead.
947 * This method does nothing now.
949 * @see URLConnection#getRequestProperty(String)
951 public static String getDefaultRequestProperty(String key)
953 // This method does nothing since JDK 1.3.
958 * Sets the ContentHandlerFactory for an application. This can be called
959 * once and only once. If it is called again, then an Error is thrown.
960 * Unlike for other set factory methods, this one does not do a security
961 * check prior to setting the factory.
963 * @param factory The ContentHandlerFactory for this application
965 * @exception Error If the factory has already been defined
966 * @exception SecurityException If a security manager exists and its
967 * checkSetFactory method doesn't allow the operation
969 public static synchronized void setContentHandlerFactory(ContentHandlerFactory factory)
971 if (URLConnection.factory != null)
972 throw new Error("ContentHandlerFactory already set");
974 // Throw an exception if an extant security mgr precludes
975 // setting the factory.
976 SecurityManager s = System.getSecurityManager();
980 URLConnection.factory = factory;
984 * Returns the MIME type of a file based on the name of the file. This
985 * works by searching for the file's extension in a list of file extensions
986 * and returning the MIME type associated with it. If no type is found,
987 * then a MIME type of "application/octet-stream" will be returned.
989 * @param filename The filename to determine the MIME type for
991 * @return The MIME type String
993 * @specnote public since JDK 1.4
995 public static String guessContentTypeFromName(String filename)
997 return getFileNameMap().getContentTypeFor(filename.toLowerCase());
1001 * Returns the MIME type of a stream based on the first few characters
1002 * at the beginning of the stream. This routine can be used to determine
1003 * the MIME type if a server is believed to be returning an incorrect
1004 * MIME type. This method returns "application/octet-stream" if it
1005 * cannot determine the MIME type.
1007 * NOTE: Overriding MIME types sent from the server can be obnoxious
1008 * to user's. See Internet Exploder 4 if you don't believe me.
1010 * @param is The InputStream to determine the MIME type from
1012 * @return The MIME type
1014 * @exception IOException If an error occurs
1016 public static String guessContentTypeFromStream(InputStream is)
1019 String result = VMURLConnection.guessContentTypeFromStream(is);
1021 return "application/octet-stream";
1026 * This method returns the <code>FileNameMap</code> object being used
1027 * to decode MIME types by file extension.
1029 * @return The <code>FileNameMap</code>.
1033 public static synchronized FileNameMap getFileNameMap()
1035 // Delayed initialization.
1036 if (fileNameMap == null)
1037 fileNameMap = new MimeTypeMapper();
1043 * This method sets the <code>FileNameMap</code> object being used
1044 * to decode MIME types by file extension.
1046 * @param map The <code>FileNameMap</code>.
1048 * @exception SecurityException If a security manager exists and its
1049 * checkSetFactory method doesn't allow the operation
1053 public static synchronized void setFileNameMap(FileNameMap map)
1055 // Throw an exception if an extant security manager precludes
1056 // setting the factory.
1057 SecurityManager s = System.getSecurityManager();
1059 s.checkSetFactory();
1064 private ContentHandler getContentHandler(String contentType)
1066 // No content type so just handle it as the default.
1067 if (contentType == null || contentType.equals(""))
1070 ContentHandler handler = null;
1072 // If a non-default factory has been set, use it.
1073 if (factory != null)
1074 handler = factory.createContentHandler(contentType);
1076 // Now try default factory. Using this factory to instantiate built-in
1077 // content handlers is preferable
1078 if (handler == null)
1079 handler = defaultFactory.createContentHandler(contentType);
1081 // User-set factory has not returned a handler. Use the default search
1083 if (handler == null)
1085 // Get the list of packages to check and append our default handler
1086 // to it, along with the JDK specified default as a last resort.
1087 // Except in very unusual environments the JDK specified one shouldn't
1088 // ever be needed (or available).
1089 String propVal = SystemProperties.getProperty("java.content.handler.pkgs");
1090 propVal = (((propVal == null) ? "" : (propVal + "|"))
1091 + "gnu.java.net.content|sun.net.www.content");
1093 // Deal with "Content-Type: text/html; charset=ISO-8859-1".
1094 int parameterBegin = contentType.indexOf(';');
1095 if (parameterBegin >= 1)
1096 contentType = contentType.substring(0, parameterBegin);
1097 contentType = contentType.trim();
1099 // Replace the '/' character in the content type with '.' and
1100 // all other non-alphabetic, non-numeric characters with '_'.
1101 char[] cArray = contentType.toCharArray();
1102 for (int i = 0; i < cArray.length; i++)
1104 if (cArray[i] == '/')
1106 else if (! ((cArray[i] >= 'A' && cArray[i] <= 'Z') ||
1107 (cArray[i] >= 'a' && cArray[i] <= 'z') ||
1108 (cArray[i] >= '0' && cArray[i] <= '9')))
1111 String contentClass = new String(cArray);
1113 // See if a class of this content type exists in any of the packages.
1114 StringTokenizer pkgPrefix = new StringTokenizer(propVal, "|");
1117 String facName = pkgPrefix.nextToken() + "." + contentClass;
1121 (ContentHandler) Class.forName(facName).newInstance();
1125 // Can't instantiate; handler still null, go on to next element.
1127 } while (handler == null && pkgPrefix.hasMoreTokens());
1133 // We don't put these in a static initializer, because it creates problems
1134 // with initializer co-dependency: SimpleDateFormat's constructors
1135 // eventually depend on URLConnection (via the java.text.*Symbols classes).
1136 private static synchronized void initializeDateFormats()
1138 if (dateformats_initialized)
1141 Locale locale = new Locale("En", "Us", "Unix");
1142 dateFormats = new SimpleDateFormat[3];
1144 new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss 'GMT'", locale);
1146 new SimpleDateFormat("EEEE, dd-MMM-yy hh:mm:ss 'GMT'", locale);
1147 dateFormats[2] = new SimpleDateFormat("EEE MMM d hh:mm:ss yyyy", locale);
1148 dateformats_initialized = true;