URLConnection.java 33.8 KB
Newer Older
1
/* URLConnection.java -- Abstract superclass for reading from URL's
2
   Copyright (C) 1998, 2002, 2003, 2004 Free Software Foundation, Inc.
Tom Tromey committed
3

4
This file is part of GNU Classpath.
Tom Tromey committed
5

6 7 8 9
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
10

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
Tom Tromey committed
37

38

Tom Tromey committed
39 40
package java.net;

41
import java.io.IOException;
42
import java.io.InputStream;
43 44
import java.io.OutputStream;
import java.security.AllPermission;
45
import java.security.Permission;
Tom Tromey committed
46 47
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
48
import java.util.Collections;
Tom Tromey committed
49 50
import java.util.Date;
import java.util.Hashtable;
51
import java.util.Locale;
52
import java.util.Map;
Tom Tromey committed
53
import java.util.StringTokenizer;
Anthony Green committed
54
import gnu.gcj.io.MimeTypes;
Tom Tromey committed
55

56

Tom Tromey committed
57 58 59
/**
 * Written using on-line Java Platform 1.2 API Specification, as well
 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
Anthony Green committed
60
 * Status:  One guessContentTypeFrom... methods not implemented.
61
 *    getContent method assumes content type from response; see comment there.
Tom Tromey committed
62
 */
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/**
 * This class models a connection that retrieves the information pointed
 * to by a URL object.  This is typically a connection to a remote node
 * on the network, but could be a simple disk read.
 * <p>
 * A URLConnection object is normally created by calling the openConnection()
 * method of a URL object.  This method is somewhat misnamed because it does
 * not actually open the connection.  Instead, it return an unconnected
 * instance of this object.  The caller then has the opportunity to set
 * various connection options prior to calling the actual connect() method.
 * <p>
 * After the connection has been opened, there are a number of methods in
 * this class that access various attributes of the data, typically
 * represented by headers sent in advance of the actual data itself.
 * <p>
 * Also of note are the getInputStream and getContent() methods which allow
 * the caller to retrieve the actual data from the connection.  Note that
 * for some types of connections, writing is also allowed.  The setDoOutput()
 * method must be called prior to connecing in order to enable this, then
 * the getOutputStream method called after the connection in order to
 * obtain a stream to write the output to.
 * <p>
 * The getContent() method is of particular note.  This method returns an
 * Object that encapsulates the data returned.  There is no way do determine
 * the type of object that will be returned in advance.  This is determined
 * by the actual content handlers as described in the description of that
 * method.
 *
91 92
 * @author Aaron M. Renn (arenn@urbanophile.com)
 * @author Warren Levy (warrenl@cygnus.com)
93
 */
Tom Tromey committed
94 95
public abstract class URLConnection
{
96 97 98 99 100 101
  /**
   * This is an object that maps filenames to MIME types.  The interface
   * to do this is implemented by this class, so just create an empty
   * instance and store it here.
   */
  private static FileNameMap fileNameMap;
102

103 104 105 106
  /**
   * This is the ContentHandlerFactory set by the caller, if any
   */
  private static ContentHandlerFactory factory;
107

108 109 110 111
  /**
   * This is the default value that will be used to determine whether or
   * not user interaction should be allowed.
   */
Michael Koch committed
112
  private static boolean defaultAllowUserInteraction;
113

114 115 116 117
  /**
   * This is the default flag indicating whether or not to use caches to
   * store the data returned from a server
   */
Tom Tromey committed
118 119
  private static boolean defaultUseCaches = true;

120 121 122
  private static ContentHandlerFactory defaultFactory
    = new gnu.java.net.DefaultContentHandlerFactory();

123
  /**
124 125
   * This variable determines whether or not interaction is allowed with
   * the user.  For example, to prompt for a username and password.
126
   */
127
  protected boolean allowUserInteraction;
128 129

  /**
130 131 132
   * Indicates whether or not a connection has been established to the
   * destination specified in the URL
   */
Michael Koch committed
133
  protected boolean connected;
134

135
  /**
136 137 138
   * Indicates whether or not input can be read from this URL
   */
  protected boolean doInput = true;
139

140 141 142
  /**
   * Indicates whether or not output can be sent to this URL
   */
Michael Koch committed
143
  protected boolean doOutput;
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  /**
   * If this flag is set, the protocol is allowed to cache data whenever
   * it can (caching is not guaranteed). If it is not set, the protocol
   * must a get a fresh copy of the data.
   * <p>
   * This field is set by the setUseCaches method and returned by the
   * getUseCaches method.
   *
   * Its default value is that determined by the last invocation of
   * setDefaultUseCaches
   */
  protected boolean useCaches;

  /**
   * If this value is non-zero, then the connection will only attempt to
   * fetch the document pointed to by the URL if the document has been
   * modified more recently than the date set in this variable.  That date
   * should be specified as the number of seconds since 1/1/1970 GMT.
   */
Michael Koch committed
164
  protected long ifModifiedSince;
165 166

  /**
167
   * This is the URL associated with this connection
168
   */
169 170 171
  protected URL url;

  private static Hashtable handlers = new Hashtable();
172
  private static SimpleDateFormat[] dateFormats;
Michael Koch committed
173
  private static boolean dateformats_initialized;
174

175 176 177
  /* Cached ParsePosition, used when parsing dates. */
  private ParsePosition position;

178
  /**
179 180 181 182 183
   * Creates a URL connection to a given URL. A real connection is not made.
   * Use #connect to do this.
   *
   * @param url The Object to create the URL connection to
   *
184
   * @see URLConnection#connect()
185
   */
Tom Tromey committed
186 187
  protected URLConnection(URL url)
  {
188
    // Set up all our instance variables
Tom Tromey committed
189 190 191 192 193
    this.url = url;
    allowUserInteraction = defaultAllowUserInteraction;
    useCaches = defaultUseCaches;
  }

194
  /**
195 196
   * Establishes the actual connection to the URL associated with this
   * connection object
197 198
   *
   * @exception IOException if an error occurs
199
   */
Tom Tromey committed
200 201
  public abstract void connect() throws IOException;

202
  /**
203 204 205
   * Returns the URL object associated with this connection
   *
   * @return The URL for this connection.
206
   */
Tom Tromey committed
207 208 209 210 211
  public URL getURL()
  {
    return url;
  }

212
  /**
213 214 215 216
   * Returns the value of the content-length header field or -1 if the value
   * is not known or not present.
   *
   * @return The content-length field
217
   */
Tom Tromey committed
218 219 220 221 222
  public int getContentLength()
  {
    return getHeaderFieldInt("content-length", -1);
  }

223
  /**
224 225 226 227 228 229 230 231
   * Returns the the content-type of the data pointed to by the URL.  This
   * method first tries looking for a content-type header.  If that is not
   * present, it attempts to use the file name to determine the content's
   * MIME type.  If that is unsuccessful, the method returns null.  The caller
   * may then still attempt to determine the MIME type by a call to
   * guessContentTypeFromStream()
   *
   * @return The content MIME type
232
   */
Tom Tromey committed
233 234 235 236 237
  public String getContentType()
  {
    return getHeaderField("content-type");
  }

238
  /**
239 240
   * Returns the value of the content-encoding field or null if it is not
   * known or not present.
241
   *
242
   * @return The content-encoding field
243
   */
Tom Tromey committed
244 245 246 247 248
  public String getContentEncoding()
  {
    return getHeaderField("content-encoding");
  }

249
  /**
250 251 252 253 254
   * Returns the value of the expires header or 0 if not known or present.
   * If populated, the return value is number of seconds since midnight
   * on 1/1/1970 GMT.
   *
   * @return The expiration time.
255
   */
Tom Tromey committed
256 257
  public long getExpiration()
  {
258
    return getHeaderFieldDate("expires", 0L);
Tom Tromey committed
259 260
  }

261
  /**
262 263 264 265 266 267
   * Returns the date of the document pointed to by the URL as reported in
   * the date field of the header or 0 if the value is not present or not
   * known. If populated, the return value is number of seconds since
   * midnight on 1/1/1970 GMT.
   *
   * @return The document date
268
   */
Tom Tromey committed
269 270 271 272 273
  public long getDate()
  {
    return getHeaderFieldDate("date", 0L);
  }

274
  /**
275 276 277 278 279
   * Returns the value of the last-modified header field or 0 if not known known
   * or not present.  If populated, the return value is the number of seconds
   * since midnight on 1/1/1970.
   *
   * @return The last modified time
280
   */
Tom Tromey committed
281 282 283 284 285
  public long getLastModified()
  {
    return getHeaderFieldDate("last-modified", 0L);
  }

286
  /**
287 288 289 290 291 292
   * Return a String representing the header value at the specified index.
   * This allows the caller to walk the list of header fields.  The analogous
   * getHeaderFieldKey(int) method allows access to the corresponding key
   * for this header field
   *
   * @param index The index into the header field list to retrieve the value for
293
   *
294
   * @return The header value or null if index is past the end of the headers
295
   */
296
  public String getHeaderField(int index)
Tom Tromey committed
297 298 299 300 301
  {
    // Subclasses for specific protocols override this.
    return null;
  }

302
  /**
303 304
   * Returns a String representing the value of the header field having
   * the named key.  Returns null if the header field does not exist.
305
   *
306
   * @param name The key of the header field
307 308
   *
   * @return The value of the header field as a String
309
   */
Tom Tromey committed
310 311 312 313 314 315
  public String getHeaderField(String name)
  {
    // Subclasses for specific protocols override this.
    return null;
  }

316
  /**
317
   * Returns a map of all sent header fields
318 319 320
   *
   * @return all header fields
   *
321 322 323 324 325
   * @since 1.4
   */
  public Map getHeaderFields()
  {
    // Subclasses for specific protocols override this.
326
    return Collections.EMPTY_MAP;
327 328
  }

329
  /**
330 331 332
   * Returns the value of the named header field as an int.  If the field
   * is not present or cannot be parsed as an integer, the default value
   * will be returned.
333
   *
334 335 336
   * @param name The header field key to lookup
   * @param defaultValue The defaule value if the header field is not found
   * or can't be parsed.
337
   *
338 339
   * @return The value of the header field or the default value if the field
   * is missing or malformed
340
   */
341
  public int getHeaderFieldInt(String name, int defaultValue)
Tom Tromey committed
342
  {
343 344
    String value = getHeaderField(name);

345 346 347
    if (value == null)
      return defaultValue;

Tom Tromey committed
348 349
    try
      {
350
	return Integer.parseInt(value);
Tom Tromey committed
351
      }
352 353 354
    catch (NumberFormatException e)
      {
	return defaultValue;
Tom Tromey committed
355 356 357
      }
  }

358
  /**
359 360 361
   * Returns the value of the named header field as a date.  This date will
   * be the number of seconds since midnight 1/1/1970 GMT or the default
   * value if the field is not present or cannot be converted to a date.
362 363
   *
   * @param name The name of the header field
364 365
   * @param defaultValue The default date if the header field is not found
   * or can't be converted.
366 367 368 369
   *
   * @return Returns the date value of the header filed or the default value
   * if the field is missing or malformed
   */
370
  public long getHeaderFieldDate(String name, long defaultValue)
Tom Tromey committed
371
  {
372
    if (! dateformats_initialized)
373
      initializeDateFormats();
374

375 376
    if (position == null)
      position = new ParsePosition(0);
377

378
    long result = defaultValue;
379 380
    String str = getHeaderField(name);

Tom Tromey committed
381 382
    if (str != null)
      {
383 384 385 386 387 388 389 390 391
	for (int i = 0; i < dateFormats.length; i++)
	  {
	    SimpleDateFormat df = dateFormats[i];
	    position.setIndex(0);
	    position.setErrorIndex(0);
	    Date date = df.parse(str, position);
	    if (date != null)
	      return date.getTime();
	  }
Tom Tromey committed
392
      }
393

394
    return result;
Tom Tromey committed
395 396
  }

397
  /**
398 399 400 401
   * Returns a String representing the header key at the specified index.
   * This allows the caller to walk the list of header fields.  The analogous
   * getHeaderField(int) method allows access to the corresponding value for
   * this tag.
402
   *
403
   * @param index The index into the header field list to retrieve the key for.
404 405 406
   *
   * @return The header field key or null if index is past the end
   * of the headers.
407
   */
408
  public String getHeaderFieldKey(int index)
Tom Tromey committed
409 410 411 412 413
  {
    // Subclasses for specific protocols override this.
    return null;
  }

414
  /**
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
   * This method returns the content of the document pointed to by the
   * URL as an Object.  The type of object depends on the MIME type of
   * the object and particular content hander loaded.  Most text type
   * content handlers will return a subclass of
   * <code>InputStream</code>.  Images usually return a class that
   * implements <code>ImageProducer</code>.  There is not guarantee
   * what type of object will be returned, however.
   *
   * <p>This class first determines the MIME type of the content, then
   * creates a ContentHandler object to process the input.  If the
   * <code>ContentHandlerFactory</code> is set, then that object is
   * called to load a content handler, otherwise a class called
   * gnu.java.net.content.&lt;content_type&gt; is tried.  If this
   * handler does not exist, the method will simple return the
   * <code>InputStream</code> returned by
   * <code>getInputStream()</code>.  Note that the default
   * implementation of <code>getInputStream()</code> throws a
   * <code>UnknownServiceException</code> so subclasses are encouraged
   * to override this method.</p>
   *
   * @exception IOException If an error with the connection occurs.
436
   * @exception UnknownServiceException If the protocol does not support the
437
   * content type at all.
438
   */
Tom Tromey committed
439 440
  public Object getContent() throws IOException
  {
441 442 443
    if (!connected)
      connect();

Tom Tromey committed
444 445 446 447
    // FIXME: Doc indicates that other criteria should be applied as
    // heuristics to determine the true content type, e.g. see 
    // guessContentTypeFromName() and guessContentTypeFromStream methods
    // as well as FileNameMap class & fileNameMap field & get/set methods.
448
    String type = getContentType();
449
    ContentHandler ch = getContentHandler(type);
450

451 452
    if (ch != null)
      return ch.getContent(this);
Tom Tromey committed
453

454
    return getInputStream();
Tom Tromey committed
455 456
  }

457
  /**
458 459
   * Retrieves the content of this URLConnection
   *
460 461
   * @param classes The allowed classes for the content
   *
462 463 464 465 466 467 468
   * @exception IOException If an error occurs
   * @exception UnknownServiceException If the protocol does not support the
   * content type
   */
  public Object getContent(Class[] classes) throws IOException
  {
    // FIXME: implement this
469
    return getContent();
470 471 472
  }

  /**
473 474 475 476 477 478 479 480 481
   * This method returns a <code>Permission</code> object representing the
   * permissions required to access this URL.  This method returns
   * <code>java.security.AllPermission</code> by default.  Subclasses should
   * override it to return a more specific permission.  For example, an
   * HTTP URL should return an instance of <code>SocketPermission</code>
   * for the appropriate host and port.
   * <p>
   * Note that because of items such as HTTP redirects, the permission
   * object returned might be different before and after connecting.
482
   *
483 484
   * @return A Permission object
   *
485 486
   * @exception IOException If the computation of the permission requires
   * network or file I/O and an exception occurs while computing it
487 488 489 490
   */
  public Permission getPermission() throws IOException
  {
    // Subclasses may override this.
491
    return new AllPermission();
492
  }
Tom Tromey committed
493

494
  /**
495 496 497 498
   * Returns an InputStream for this connection.  As this default
   * implementation returns null, subclasses should override this method
   *
   * @return An InputStream for this connection
499 500 501
   *
   * @exception IOException If an error occurs
   * @exception UnknownServiceException If the protocol does not support input
502
   */
Tom Tromey committed
503 504 505
  public InputStream getInputStream() throws IOException
  {
    // Subclasses for specific protocols override this.
506 507
    throw new UnknownServiceException("Protocol " + url.getProtocol()
                                      + " does not support input.");
Tom Tromey committed
508 509
  }

510
  /**
511 512 513 514
   * Returns an OutputStream for this connection.  As this default
   * implementation returns null, subclasses should override this method
   *
   * @return An OutputStream for this connection
515 516 517
   *
   * @exception IOException If an error occurs
   * @exception UnknownServiceException If the protocol does not support output
518
   */
Tom Tromey committed
519 520 521
  public OutputStream getOutputStream() throws IOException
  {
    // Subclasses for specific protocols override this.
522 523
    throw new UnknownServiceException("Protocol " + url.getProtocol()
                                      + " does not support output.");
Tom Tromey committed
524 525
  }

526
  /**
527 528
   * The methods prints the value of this object as a String by calling the
   * toString() method of its associated URL.  Overrides Object.toString()
529
   *
530
   * @return A String representation of this object
531
   */
Tom Tromey committed
532 533 534 535 536
  public String toString()
  {
    return this.getClass().getName() + ":" + url.toString();
  }

537
  /**
538 539 540
   * Returns the value of a flag indicating whether or not input is going
   * to be done for this connection.  This default to true unless the
   * doOutput flag is set to false, in which case this defaults to false.
541
   *
542 543
   * @param input <code>true</code> if input is to be done,
   * <code>false</code> otherwise
544 545
   *
   * @exception IllegalStateException If already connected
546
   */
547
  public void setDoInput(boolean input)
Tom Tromey committed
548 549
  {
    if (connected)
550
      throw new IllegalStateException("Already connected");
Tom Tromey committed
551

552
    doInput = input;
Tom Tromey committed
553 554
  }

555
  /**
556 557 558 559 560
   * Returns the value of a flag indicating whether or not input is going
   * to be done for this connection.  This default to true unless the
   * doOutput flag is set to false, in which case this defaults to false.
   *
   * @return true if input is to be done, false otherwise
561
   */
Tom Tromey committed
562 563 564 565 566
  public boolean getDoInput()
  {
    return doInput;
  }

567
  /**
568 569 570
   * Returns a boolean flag indicating whether or not output will be done
   * on this connection.  The default value is false, so this method can
   * be used to override the default
571
   *
572
   * @param output ture if output is to be done, false otherwise
573 574
   *
   * @exception IllegalStateException If already connected
575
   */
576
  public void setDoOutput(boolean output)
Tom Tromey committed
577 578
  {
    if (connected)
579
      throw new IllegalStateException("Already connected");
Tom Tromey committed
580

581
    doOutput = output;
Tom Tromey committed
582 583
  }

584
  /**
585 586 587 588
   * Returns a boolean flag indicating whether or not output will be done
   * on this connection.  This defaults to false.
   *
   * @return true if output is to be done, false otherwise
589
   */
Tom Tromey committed
590 591 592 593 594
  public boolean getDoOutput()
  {
    return doOutput;
  }

595
  /**
596 597 598
   * Sets a boolean flag indicating whether or not user interaction is
   * allowed for this connection.  (For example, in order to prompt for
   * username and password info.
599
   *
600
   * @param allow true if user interaction should be allowed, false otherwise.
601 602
   *
   * @exception IllegalStateException If already connected
603
   */
604
  public void setAllowUserInteraction(boolean allow)
Tom Tromey committed
605
  {
606
    allowUserInteraction = allow;
Tom Tromey committed
607 608
  }

609
  /**
610 611 612 613 614
   * Returns a boolean flag indicating whether or not user interaction is
   * allowed for this connection.  (For example, in order to prompt for
   * username and password info.
   *
   * @return true if user interaction is allowed, false otherwise
615
   */
Tom Tromey committed
616 617 618 619 620
  public boolean getAllowUserInteraction()
  {
    return allowUserInteraction;
  }

621
  /**
622 623
   * Sets the default flag for whether or not interaction with a user
   * is allowed.  This will be used for all connections unless overridden
624
   *
625
   * @param allow true to allow user interaction, false otherwise
626
   */
627
  public static void setDefaultAllowUserInteraction(boolean allow)
Tom Tromey committed
628
  {
629
    defaultAllowUserInteraction = allow;
Tom Tromey committed
630 631
  }

632
  /**
633 634 635 636
   * Returns the default flag for whether or not interaction with a user
   * is allowed.  This will be used for all connections unless overridden
   *
   * @return true if user interaction is allowed, false otherwise
637
   */
Tom Tromey committed
638 639 640 641 642
  public static boolean getDefaultAllowUserInteraction()
  {
    return defaultAllowUserInteraction;
  }

643
  /**
644 645
   * Sets a boolean flag indicating whether or not caching will be used
   * (if possible) to store data downloaded via the connection.
646 647
   *
   * @param usecaches The new value
648 649
   *
   * @exception IllegalStateException If already connected
650
   */
Tom Tromey committed
651 652 653
  public void setUseCaches(boolean usecaches)
  {
    if (connected)
654
      throw new IllegalStateException("Already connected");
Tom Tromey committed
655 656 657 658

    useCaches = usecaches;
  }

659
  /**
660 661 662 663
   * Returns a boolean flag indicating whether or not caching will be used
   * (if possible) to store data downloaded via the connection.
   *
   * @return true if caching should be used if possible, false otherwise
664
   */
Tom Tromey committed
665 666 667 668 669
  public boolean getUseCaches()
  {
    return useCaches;
  }

670
  /**
671 672 673 674 675
   * Sets the ifModified since instance variable.  If this value is non
   * zero and the underlying protocol supports it, the actual document will
   * not be fetched unless it has been modified since this time.  The value
   * passed should  be 0 if this feature is to be disabled or the time expressed
   * as the number of seconds since midnight 1/1/1970 GMT otherwise.
676 677 678
   *
   * @param ifmodifiedsince The new value in milliseconds
   * since January 1, 1970 GMT
679 680
   *
   * @exception IllegalStateException If already connected
681
   */
Tom Tromey committed
682 683 684
  public void setIfModifiedSince(long ifmodifiedsince)
  {
    if (connected)
685
      throw new IllegalStateException("Already connected");
Tom Tromey committed
686 687 688 689

    ifModifiedSince = ifmodifiedsince;
  }

690
  /**
691 692 693 694 695 696 697
   * Returns the ifModified since instance variable.  If this value is non
   * zero and the underlying protocol supports it, the actual document will
   * not be fetched unless it has been modified since this time.  The value
   * returned will be 0 if this feature is disabled or the time expressed
   * as the number of seconds since midnight 1/1/1970 GMT otherwise
   *
   * @return The ifModifiedSince value
698
   */
Tom Tromey committed
699 700 701 702 703
  public long getIfModifiedSince()
  {
    return ifModifiedSince;
  }

704
  /**
705 706 707 708
   * Returns the default value used to determine whether or not caching
   * of documents will be done when possible.
   *
   * @return true if caches will be used, false otherwise
709
   */
Tom Tromey committed
710 711 712 713 714
  public boolean getDefaultUseCaches()
  {
    return defaultUseCaches;
  }

715
  /**
716 717
   * Sets the default value used to determine whether or not caching
   * of documents will be done when possible.
718
   *
719
   * @param use true to use caches if possible by default, false otherwise
720
   */
721
  public void setDefaultUseCaches(boolean use)
Tom Tromey committed
722
  {
723
    defaultUseCaches = use;
Tom Tromey committed
724 725
  }

726
  /**
727
   * Sets the value of the named request property
728
   *
729 730
   * @param key The name of the property
   * @param value The value of the property
731
   *
732 733 734
   * @exception IllegalStateException If already connected
   * @exception NullPointerException If key is null
   *
735 736
   * @see URLConnection#getRequestProperty(String key)
   * @see URLConnection#addRequestProperty(String key, String value)
737
   *
738
   * @since 1.4
739
   */
Tom Tromey committed
740 741
  public void setRequestProperty(String key, String value)
  {
742
    if (connected)
743
      throw new IllegalStateException("Already connected");
744

745
    if (key == null)
746 747
      throw new NullPointerException("key is null");

Tom Tromey committed
748 749 750 751
    // Do nothing unless overridden by subclasses that support setting
    // header fields in the request.
  }

752
  /**
753
   * Adds a new request property by a key/value pair.
754
   * This method does not overwrite existing properties with the same key.
755
   *
756 757
   * @param key Key of the property to add
   * @param value Value of the Property to add
758 759 760
   *
   * @exception IllegalStateException If already connected
   * @exception NullPointerException If key is null
761
   *
762 763
   * @see URLConnection#getRequestProperty(String key)
   * @see URLConnection#setRequestProperty(String key, String value)
764
   *
765 766 767 768
   * @since 1.4
   */
  public void addRequestProperty(String key, String value)
  {
769
    if (connected)
770
      throw new IllegalStateException("Already connected");
771

772
    if (key == null)
773 774
      throw new NullPointerException("key is null");

775 776
    // Do nothing unless overridden by subclasses that support adding
    // header fields in the request.
777 778 779
  }

  /**
780
   * Returns the value of the named request property.
781
   *
782 783 784
   * @param key The name of the property
   *
   * @return Value of the property
785
   *
786 787
   * @exception IllegalStateException If already connected
   *
788 789
   * @see URLConnection#setRequestProperty(String key, String value)
   * @see URLConnection#addRequestProperty(String key, String value)
790
   */
Tom Tromey committed
791 792
  public String getRequestProperty(String key)
  {
793
    if (connected)
794
      throw new IllegalStateException("Already connected");
795

Tom Tromey committed
796 797 798 799 800
    // Overridden by subclasses that support reading header fields from the
    // request.
    return null;
  }

801
  /**
802 803 804
   * Returns an unmodifiable Map containing the request properties.
   *
   * @return The map of properties
805
   *
806 807
   * @exception IllegalStateException If already connected
   *
808
   * @since 1.4
809 810 811
   */
  public Map getRequestProperties()
  {
812
    if (connected)
813
      throw new IllegalStateException("Already connected");
814

815 816
    // Overridden by subclasses that support reading header fields from the
    // request.
817
    return Collections.EMPTY_MAP;
818 819 820
  }

  /**
821 822 823
   * Sets the default value of a request property.  This will be used
   * for all connections unless the value of the property is manually
   * overridden.
824
   *
825 826
   * @param key The request property name the default is being set for
   * @param value The value to set the default to
827
   *
828 829
   * @deprecated 1.3 The method setRequestProperty should be used instead.
   * This method does nothing now.
830
   *
831
   * @see URLConnection#setRequestProperty(String key, String value)
832
   */
833
  public static void setDefaultRequestProperty(String key, String value)
Tom Tromey committed
834
  {
835
    // This method does nothing since JDK 1.3.
Tom Tromey committed
836 837
  }

838
  /**
839 840 841
   * Returns the default value of a request property.  This will be used
   * for all connections unless the value of the property is manually
   * overridden.
842
   *
843
   * @param key The request property to return the default value of
844 845
   *
   * @return The value of the default property or null if not available
846
   *
847 848
   * @deprecated 1.3 The method getRequestProperty should be used instead.
   * This method does nothing now.
849
   *
850
   * @see URLConnection#getRequestProperty(String key)
851
   */
Tom Tromey committed
852 853
  public static String getDefaultRequestProperty(String key)
  {
854
    // This method does nothing since JDK 1.3.
Tom Tromey committed
855 856 857
    return null;
  }

858
  /**
859 860 861 862
   * Set's the ContentHandlerFactory for an application.  This can be called
   * once and only once.  If it is called again, then an Error is thrown.
   * Unlike for other set factory methods, this one does not do a security
   * check prior to setting the factory.
863
   *
864
   * @param factory The ContentHandlerFactory for this application
865 866 867 868
   *
   * @exception Error If the factory has already been defined
   * @exception SecurityException If a security manager exists and its
   * checkSetFactory method doesn't allow the operation
869
   */
870
  public static synchronized void setContentHandlerFactory(ContentHandlerFactory factory)
Tom Tromey committed
871
  {
872
    if (URLConnection.factory != null)
Tom Tromey committed
873 874 875 876 877 878 879
      throw new Error("ContentHandlerFactory already set");

    // Throw an exception if an extant security mgr precludes
    // setting the factory.
    SecurityManager s = System.getSecurityManager();
    if (s != null)
      s.checkSetFactory();
880

881
    URLConnection.factory = factory;
Tom Tromey committed
882 883
  }

884
  /**
885 886 887 888 889 890
   * Returns the MIME type of a file based on the name of the file.  This
   * works by searching for the file's extension in a list of file extensions
   * and returning the MIME type associated with it.  If no type is found,
   * then a MIME type of "application/octet-stream" will be returned.
   *
   * @param filename The filename to determine the MIME type for
891
   *
892
   * @return The MIME type String
893 894
   *
   * @specnote public since JDK 1.4
895
   */
896
  public static String guessContentTypeFromName(String filename)
Anthony Green committed
897
  {
898
    int dot = filename.lastIndexOf(".");
Anthony Green committed
899 900 901
    
    if (dot != -1)
      {
902
	if (dot == filename.length())
903
	  return "application/octet-stream";
Anthony Green committed
904
	else
905
	  filename = filename.substring(dot + 1);
Anthony Green committed
906 907
      }
    
908
    String type = MimeTypes.getMimeTypeFromExtension(filename);
Anthony Green committed
909 910
    
    if (type == null)
911
      return"application/octet-stream";
Anthony Green committed
912

913
    return type;
Anthony Green committed
914
  }
Tom Tromey committed
915

916
  /**
917 918 919
   * Returns the MIME type of a stream based on the first few characters
   * at the beginning of the stream.  This routine can be used to determine
   * the MIME type if a server is believed to be returning an incorrect
920
   * MIME type.  This method returns "application/octet-stream" if it
921 922 923 924 925 926
   * cannot determine the MIME type.
   * <p>
   * NOTE: Overriding MIME types sent from the server can be obnoxious
   * to user's.  See Internet Exploder 4 if you don't believe me.
   *
   * @param is The InputStream to determine the MIME type from
927
   *
928
   * @return The MIME type
929 930 931 932 933 934 935 936 937 938 939
   *
   * @exception IOException If an error occurs
   */
  public static String guessContentTypeFromStream(InputStream is)
    throws IOException
  {
    is.mark(1024);
    // FIXME: Implement this. Use system mimetype informations (like "file").
    is.reset();
    return null;
  }
Tom Tromey committed
940

941
  /**
942 943
   * This method returns the <code>FileNameMap</code> object being used
   * to decode MIME types by file extension.
944
   *
945 946
   * @return The <code>FileNameMap</code>.
   *
947 948
   * @since 1.2
   */
Tom Tromey committed
949 950 951 952 953
  public static FileNameMap getFileNameMap()
  {
    return fileNameMap;
  }

954
  /**
955 956
   * This method set the <code>FileNameMap</code> object being used
   * to decode MIME types by file extension.
957
   *
958
   * @param map The <code>FileNameMap</code>.
959 960 961
   *
   * @exception SecurityException If a security manager exists and its
   * checkSetFactory method doesn't allow the operation
962
   *
963 964
   * @since 1.2
   */
Tom Tromey committed
965 966
  public static void setFileNameMap(FileNameMap map)
  {
967
    // Throw an exception if an extant security manager precludes
Tom Tromey committed
968 969 970 971 972 973 974 975
    // setting the factory.
    SecurityManager s = System.getSecurityManager();
    if (s != null)
      s.checkSetFactory();

    fileNameMap = map;
  }

976
  private ContentHandler getContentHandler(String contentType)
Tom Tromey committed
977 978
  {
    // No content type so just handle it as the default.
979
    if (contentType == null || contentType.equals(""))
Tom Tromey committed
980 981
      return null;

982 983
    ContentHandler handler;

Tom Tromey committed
984 985 986 987 988 989 990 991 992 993
    // See if a handler has been cached for this content type.
    // For efficiency, if a content type has been searched for but not
    // found, it will be in the hash table but as the contentType String
    // instead of a ContentHandler.
    if ((handler = (ContentHandler) handlers.get(contentType)) != null)
      if (handler instanceof ContentHandler)
	return handler;
      else
	return null;

994
    // If a non-default factory has been set, use it.
Tom Tromey committed
995 996 997
    if (factory != null)
      handler = factory.createContentHandler(contentType);

998 999 1000 1001 1002 1003 1004
    // Now try default factory. Using this factory to instantiate built-in
    // content handlers is preferable  
    if (handler == null)
      handler = defaultFactory.createContentHandler(contentType);

    // User-set factory has not returned a handler. Use the default search 
    // algorithm.
Tom Tromey committed
1005 1006 1007 1008 1009 1010 1011 1012
    if (handler == null)
      {
	// Get the list of packages to check and append our default handler
	// to it, along with the JDK specified default as a last resort.
	// Except in very unusual environments the JDK specified one shouldn't
	// ever be needed (or available).
	String propVal = System.getProperty("java.content.handler.pkgs");
	propVal = (propVal == null) ? "" : (propVal + "|");
1013
	propVal = propVal + "gnu.java.net.content|sun.net.www.content";
Tom Tromey committed
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029

	// Replace the '/' character in the content type with '.' and
	// all other non-alphabetic, non-numeric characters with '_'.
	char[] cArray = contentType.toCharArray();
	for (int i = 0; i < cArray.length; i++)
	  {
	    if (cArray[i] == '/')
	      cArray[i] = '.';
	    else if (! ((cArray[i] >= 'A' && cArray[i] <= 'Z') || 
			(cArray[i] >= 'a' && cArray[i] <= 'z') ||
			(cArray[i] >= '0' && cArray[i] <= '9')))
	      cArray[i] = '_';
	  }
	String contentClass = new String(cArray);

	// See if a class of this content type exists in any of the packages.
1030
	StringTokenizer pkgPrefix = new StringTokenizer(propVal, "|");
Tom Tromey committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	do
	  {
	    String facName = pkgPrefix.nextToken() + "." + contentClass;
	    try
	      {
		handler =
		  (ContentHandler) Class.forName(facName).newInstance();
	      }
	    catch (Exception e)
	      {
		// Can't instantiate; handler still null, go on to next element.
	      }
	  } while ((handler == null ||
		    ! (handler instanceof ContentHandler)) &&
		   pkgPrefix.hasMoreTokens());
      }

    // Update the hashtable with the new content handler.
1049
    if (handler instanceof ContentHandler)
Tom Tromey committed
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
      {
	handlers.put(contentType, handler);
	return handler;
      }

    // For efficiency on subsequent searches, put a dummy entry in the hash
    // table for content types that don't have a non-default ContentHandler.
    handlers.put(contentType, contentType);
    return null;
  }
1060 1061 1062 1063
  
  // We don't put these in a static initializer, because it creates problems
  // with initializer co-dependency: SimpleDateFormat's constructors eventually 
  // depend on URLConnection (via the java.text.*Symbols classes).
1064
  private static synchronized void initializeDateFormats()
1065 1066 1067
  {
    if (dateformats_initialized)
      return;
1068 1069

    Locale locale = new Locale("En", "Us", "Unix");
1070 1071
    dateFormats = new SimpleDateFormat[3];
    dateFormats[0] =
1072
      new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss 'GMT'", locale);
1073
    dateFormats[1] =
1074
      new SimpleDateFormat("EEEE, dd-MMM-yy hh:mm:ss 'GMT'", locale);
1075
    dateFormats[2] = new SimpleDateFormat("EEE MMM d hh:mm:ss yyyy", locale);
1076 1077
    dateformats_initialized = true;
  }
1078
}