DataFlavor.java 32.1 KB
Newer Older
Tom Tromey committed
1
/* DataFlavor.java -- A type of data to transfer via the clipboard.
2
   Copyright (C) 1999, 2001, 2004, 2005, 2006 Free Software Foundation, Inc.
Tom Tromey committed
3 4 5 6 7 8 9 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 37 38 39 40 41 42 43 44 45 46

This file is part of GNU Classpath.

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.

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., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 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. */


package java.awt.datatransfer;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInput;
import java.io.ObjectOutput;
47
import java.io.OptionalDataException;
Tom Tromey committed
48
import java.io.Reader;
49
import java.io.Serializable;
Tom Tromey committed
50 51 52 53
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
54
import java.nio.charset.Charset;
Tom Tromey committed
55
import java.rmi.Remote;
Tom Tromey committed
56 57 58 59 60 61 62 63 64 65 66 67 68

/**
 * This class represents a particular data format used for transferring
 * data via the clipboard.
 *
 * @author Aaron M. Renn (arenn@urbanophile.com)
 */
public class DataFlavor implements java.io.Externalizable, Cloneable
{
  static final long serialVersionUID = 8367026044764648243L;

  // FIXME: Serialization: Need to write methods for.

69 70 71 72 73 74 75 76
  /**
   * This is the data flavor used for tranferring plain text.  The MIME
   * type is "text/plain; charset=unicode".  The representation class
   * is <code>java.io.InputStream</code>.
   *
   * @deprecated The charset unicode is platform specific and InputStream
   * deals with bytes not chars. Use <code>getRederForText()</code>.
   */
77
  public static final DataFlavor plainTextFlavor =
78
    new DataFlavor("text/plain; charset=unicode; class=java.io.InputStream",
79
                   "plain unicode text");
Tom Tromey committed
80

81 82
  /**
   * This is the data flavor used for transferring Java strings.  The
83
   * MIME type is "application/x-java-serialized-object" and the
84 85
   * representation class is <code>java.lang.String</code>.
   */
86
  public static final DataFlavor stringFlavor =
87
    new DataFlavor(java.lang.String.class, "Java Unicode String");
Tom Tromey committed
88

89 90
  /**
   * This is a data flavor used for transferring lists of files.  The
91
   * representation type is a <code>java.util.List</code>, with each
92 93
   * element of the list being a <code>java.io.File</code>.
   */
94
  public static final DataFlavor javaFileListFlavor =
95
    new DataFlavor("application/x-java-file-list; class=java.util.List",
96
                   "Java File List");
Tom Tromey committed
97

98 99 100 101
  /**
   * This is an image flavor used for transferring images.  The
   * representation type is a <code>java.awt.Image</code>.
   */
102
  public static final DataFlavor imageFlavor =
103
    new DataFlavor(java.awt.Image.class, "Java Image");
Tom Tromey committed
104

105 106 107 108 109 110
  /**
   * This is the MIME type used for transferring a serialized object.
   * The representation class is the type of object be deserialized.
   */
  public static final String javaSerializedObjectMimeType =
    "application/x-java-serialized-object";
Tom Tromey committed
111

112 113 114 115 116 117 118
  /**
   * This is the MIME type used to transfer a Java object reference within
   * the same JVM.  The representation class is the class of the object
   * being transferred.
   */
  public static final String javaJVMLocalObjectMimeType =
    "application/x-java-jvm-local-objectref";
Tom Tromey committed
119

120 121 122 123 124 125
  /**
   * This is the MIME type used to transfer a link to a remote object.
   * The representation class is the type of object being linked to.
   */
  public static final String javaRemoteObjectMimeType =
    "application/x-java-remote-object";
Tom Tromey committed
126 127

  /*
128 129
   * Instance Variables
   */
130

131
  // The MIME type for this flavor
132
  private MimeType mimeType;
133

134
  // The representation class for this flavor
135
  private Class<?> representationClass;
136

137 138
  // The human readable name of this flavor
  private String humanPresentableName;
Tom Tromey committed
139 140

  /*
141 142
   * Static Methods
   */
143

144 145 146 147 148 149 150 151 152 153 154 155
  /**
   * This method attempts to load the named class.  The following class
   * loaders are searched in order: the bootstrap class loader, the
   * system class loader, the context class loader (if it exists), and
   * the specified fallback class loader.
   *
   * @param className The name of the class to load.
   * @param classLoader The class loader to use if all others fail, which
   * may be <code>null</code>.
   *
   * @exception ClassNotFoundException If the class cannot be loaded.
   */
156
  protected static final Class<?> tryToLoadClass(String className,
157
                                                 ClassLoader classLoader)
158 159
    throws ClassNotFoundException
  {
160
    // Bootstrap
161 162
    try
      {
163
        return Class.forName(className);
164
      }
165
    catch(ClassNotFoundException cnfe)
166
      {
167
        // Ignored.
168
      }
169

170
    // System
171 172
    try
      {
173
        ClassLoader loader = ClassLoader.getSystemClassLoader();
174
        return Class.forName(className, true, loader);
175
      }
176 177
    catch(ClassNotFoundException cnfe)
      {
178
        // Ignored.
179
      }
180

181
    // Context
182 183
    try
      {
184
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
185
        return Class.forName(className, true, loader);
186
      }
187 188
    catch(ClassNotFoundException cnfe)
      {
189
        // Ignored.
190
      }
191

192
    if (classLoader != null)
193 194 195
      return Class.forName(className, true, classLoader);

    throw new ClassNotFoundException(className);
196
  }
197

198 199 200 201 202 203 204
  /**
   * XXX - Currently returns <code>plainTextFlavor</code>.
   */
  public static final DataFlavor getTextPlainUnicodeFlavor()
  {
    return plainTextFlavor;
  }
205

206 207 208 209 210 211 212 213 214 215
  /**
   * Selects the best supported text flavor on this implementation.
   * Returns <code>null</code> when none of the given flavors is liked.
   *
   * The <code>DataFlavor</code> returned the first data flavor in the
   * array that has either a representation class which is (a subclass of)
   * <code>Reader</code> or <code>String</code>, or has a representation
   * class which is (a subclass of) <code>InputStream</code> and has a
   * primary MIME type of "text" and has an supported encoding.
   */
216
  public static final DataFlavor
217 218 219 220 221 222
    selectBestTextFlavor(DataFlavor[] availableFlavors)
  {
    for(int i = 0; i < availableFlavors.length; i++)
      {
        DataFlavor df = availableFlavors[i];
        Class c = df.representationClass;
223

224 225 226 227
        // A Reader or String is good.
        if ((Reader.class.isAssignableFrom(c))
           || (String.class.isAssignableFrom(c)))
      return df;
228

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        // A InputStream is good if the mime primary type is "text"
        if ((InputStream.class.isAssignableFrom(c))
           && ("text".equals(df.getPrimaryType())))
          {
            String encoding = availableFlavors[i].getParameter("charset");
            if (encoding == null)
              encoding = "us-ascii";
            Reader r = null;
            try
              {
                // Try to construct a dummy reader with the found encoding
                r = new InputStreamReader
                      (new ByteArrayInputStream(new byte[0]), encoding);
              }
            catch(UnsupportedEncodingException uee) { /* ignore */ }

            if (r != null)
              return df;
          }
      }
249

250 251 252
    // Nothing found
    return null;
  }
Tom Tromey committed
253 254


255 256 257
  /*
   * Constructors
   */
258

259 260 261 262 263 264
  /**
   * Empty public constructor needed for externalization.
   * Should not be used for normal instantiation.
   */
  public DataFlavor()
  {
265
    // Used for deserialization only, nothing to do here.
266
  }
Tom Tromey committed
267

268 269 270 271 272 273 274 275 276 277
  /**
   * Initializes a new instance of <code>DataFlavor</code>.  The class
   * and human readable name are specified, the MIME type will be
   * "application/x-java-serialized-object". If the human readable name
   * is not specified (<code>null</code>) then the human readable name
   * will be the same as the MIME type.
   *
   * @param representationClass The representation class for this object.
   * @param humanPresentableName The display name of the object.
   */
278
  public DataFlavor(Class<?> representationClass, String humanPresentableName)
279
  {
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    if (representationClass == null)
      throw new NullPointerException("representationClass must not be null");
    try
      {
        mimeType = new MimeType(javaSerializedObjectMimeType);
      }
    catch (MimeTypeParseException ex)
      {
        // Must not happen as we use a constant string.
        assert false;
      }
    if (humanPresentableName == null)
      humanPresentableName = javaSerializedObjectMimeType;
    this.humanPresentableName = humanPresentableName;
    this.representationClass = representationClass;
295
  }
Tom Tromey committed
296

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  /**
   * Initializes a new instance of <code>DataFlavor</code> with the
   * specified MIME type and description.  If the MIME type has a
   * "class=&lt;rep class&gt;" parameter then the representation class will
   * be the class name specified. Otherwise the class defaults to
   * <code>java.io.InputStream</code>. If the human readable name
   * is not specified (<code>null</code>) then the human readable name
   * will be the same as the MIME type.
   *
   * @param mimeType The MIME type for this flavor.
   * @param humanPresentableName The display name of this flavor.
   * @param classLoader The class loader for finding classes if the default
   * class loaders do not work.
   *
   * @exception IllegalArgumentException If the representation class
   * specified cannot be loaded.
   * @exception ClassNotFoundException If the class is not loaded.
   */
315
  public DataFlavor(String mimeType, String humanPresentableName,
316 317 318
                   ClassLoader classLoader)
    throws ClassNotFoundException
  {
319
    init(mimeType, humanPresentableName, classLoader);
320
  }
Tom Tromey committed
321

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  /**
   * Initializes a new instance of <code>DataFlavor</code> with the
   * specified MIME type and description.  If the MIME type has a
   * "class=&lt;rep class&gt;" parameter then the representation class will
   * be the class name specified. Otherwise the class defaults to
   * <code>java.io.InputStream</code>. If the human readable name
   * is not specified (<code>null</code>) then the human readable name
   * will be the same as the MIME type. This is the same as calling
   * <code>new DataFlavor(mimeType, humanPresentableName, null)</code>.
   *
   * @param mimeType The MIME type for this flavor.
   * @param humanPresentableName The display name of this flavor.
   *
   * @exception IllegalArgumentException If the representation class
   * specified cannot be loaded.
   */
  public DataFlavor(String mimeType, String humanPresentableName)
  {
340 341 342 343 344 345 346 347 348 349 350
    try
      {
        init(mimeType, humanPresentableName, getClass().getClassLoader());
      }
    catch (ClassNotFoundException ex)
      {
        IllegalArgumentException iae =
          new IllegalArgumentException("Class not found: " + ex.getMessage());
        iae.initCause(ex);
        throw iae;
      }
351
  }
Tom Tromey committed
352

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  /**
   * Initializes a new instance of <code>DataFlavor</code> with the specified
   * MIME type.  This type can have a "class=" parameter to specify the
   * representation class, and then the class must exist or an exception will
   * be thrown. If there is no "class=" parameter then the representation class
   * will be <code>java.io.InputStream</code>. This is the same as calling
   * <code>new DataFlavor(mimeType, null)</code>.
   *
   * @param mimeType The MIME type for this flavor.
   *
   * @exception IllegalArgumentException If a class is not specified in
   * the MIME type.
   * @exception ClassNotFoundException If the class cannot be loaded.
   */
  public DataFlavor(String mimeType) throws ClassNotFoundException
  {
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    init(mimeType, null, getClass().getClassLoader());
  }

  /**
   * Called by various constructors to initialize this object.
   *
   * @param mime the mime string
   * @param humanPresentableName the human presentable name
   * @param loader the class loader to use for loading the representation
   *        class
   */
  private void init(String mime, String humanPresentableName,
                    ClassLoader loader)
    throws ClassNotFoundException
  {
    if (mime == null)
      throw new NullPointerException("The mime type must not be null");
    try
      {
        mimeType = new MimeType(mime);
      }
    catch (MimeTypeParseException ex)
      {
        IllegalArgumentException iae =
          new IllegalArgumentException("Invalid mime type");
        iae.initCause(ex);
        throw iae;
      }
    String className = mimeType.getParameter("class");
    if (className == null)
      {
        if (mimeType.getBaseType().equals(javaSerializedObjectMimeType))
          throw new IllegalArgumentException("Serialized object type must have"
                                        + " a representation class parameter");
        else
          representationClass = java.io.InputStream.class;
      }
    else
      representationClass = tryToLoadClass(className, loader);
    mimeType.addParameter("class", representationClass.getName());

    if (humanPresentableName == null)
      {
        humanPresentableName = mimeType.getParameter("humanPresentableName");
        if (humanPresentableName == null)
          humanPresentableName = mimeType.getBaseType();
      }
    this.humanPresentableName = humanPresentableName;
417
  }
Tom Tromey committed
418

419 420 421 422 423 424 425
  /**
   * Returns the MIME type of this flavor.
   *
   * @return The MIME type for this flavor.
   */
  public String getMimeType()
  {
426
    return(mimeType.toString());
427
  }
Tom Tromey committed
428

429 430 431 432 433
  /**
   * Returns the representation class for this flavor.
   *
   * @return The representation class for this flavor.
   */
434
  public Class<?> getRepresentationClass()
435 436 437
  {
    return(representationClass);
  }
Tom Tromey committed
438

439 440 441 442 443 444 445 446
  /**
   * Returns the human presentable name for this flavor.
   *
   * @return The human presentable name for this flavor.
   */
  public String getHumanPresentableName()
  {
    return(humanPresentableName);
447
  }
Tom Tromey committed
448

449 450 451 452 453 454 455
  /**
   * Returns the primary MIME type for this flavor.
   *
   * @return The primary MIME type for this flavor.
   */
  public String getPrimaryType()
  {
456
    return(mimeType.getPrimaryType());
457
  }
Tom Tromey committed
458

459 460 461 462 463 464 465
  /**
   * Returns the MIME subtype for this flavor.
   *
   * @return The MIME subtype for this flavor.
   */
  public String getSubType()
  {
466
    return mimeType.getSubType();
467
  }
Tom Tromey committed
468

469 470 471 472 473 474 475 476 477 478 479 480
  /**
   * Returns the value of the named MIME type parameter, or <code>null</code>
   * if the parameter does not exist.
   *
   * @param paramName The name of the paramter.
   *
   * @return The value of the parameter.
   */
  public String getParameter(String paramName)
  {
    if ("humanPresentableName".equals(paramName))
      return getHumanPresentableName();
481

482
    return mimeType.getParameter(paramName);
483
  }
Tom Tromey committed
484

485 486 487 488 489 490 491 492 493
  /**
   * Sets the human presentable name to the specified value.
   *
   * @param humanPresentableName The new display name.
   */
  public void setHumanPresentableName(String humanPresentableName)
  {
    this.humanPresentableName = humanPresentableName;
  }
Tom Tromey committed
494

495 496 497 498 499 500 501 502 503 504 505 506 507
  /**
   * Tests the MIME type of this object for equality against the specified
   * MIME type. Ignores parameters.
   *
   * @param mimeType The MIME type to test against.
   *
   * @return <code>true</code> if the MIME type is equal to this object's
   * MIME type (ignoring parameters), <code>false</code> otherwise.
   *
   * @exception NullPointerException If mimeType is null.
   */
  public boolean isMimeTypeEqual(String mimeType)
  {
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
    if (mimeType == null)
      throw new NullPointerException("mimeType must not be null");
    boolean equal = false;
    try
      {
        if (this.mimeType != null)
          {
            MimeType other = new MimeType(mimeType);
            equal = this.mimeType.matches(other);
          }
      }
    catch (MimeTypeParseException ex)
      {
        // Return false in this case.
      }
    return equal;
524
  }
Tom Tromey committed
525

526 527 528 529 530 531
  /**
   * Tests the MIME type of this object for equality against the specified
   * data flavor's MIME type
   *
   * @param flavor The flavor to test against.
   *
532
   * @return <code>true</code> if the flavor's MIME type is equal to this
533 534 535 536 537 538
   * object's MIME type, <code>false</code> otherwise.
   */
  public final boolean isMimeTypeEqual(DataFlavor flavor)
  {
    return isMimeTypeEqual(flavor.getMimeType());
  }
Tom Tromey committed
539

540 541 542 543 544 545 546 547
  /**
   * Tests whether or not this flavor represents a serialized object.
   *
   * @return <code>true</code> if this flavor represents a serialized
   * object, <code>false</code> otherwise.
   */
  public boolean isMimeTypeSerializedObject()
  {
548
    return isMimeTypeEqual(javaSerializedObjectMimeType);
549
  }
Tom Tromey committed
550

551 552 553 554 555 556 557 558 559
  /**
   * Tests whether or not this flavor has a representation class of
   * <code>java.io.InputStream</code>.
   *
   * @return <code>true</code> if the representation class of this flavor
   * is <code>java.io.InputStream</code>, <code>false</code> otherwise.
   */
  public boolean isRepresentationClassInputStream()
  {
560
    return InputStream.class.isAssignableFrom(representationClass);
561
  }
Tom Tromey committed
562

563 564 565 566 567 568 569 570 571
  /**
   * Tests whether the representation class for this flavor is
   * serializable.
   *
   * @return <code>true</code> if the representation class is serializable,
   * <code>false</code> otherwise.
   */
  public boolean isRepresentationClassSerializable()
  {
572
    return Serializable.class.isAssignableFrom(representationClass);
573
  }
Tom Tromey committed
574

575 576 577 578 579 580 581 582 583 584
  /**
   * Tests whether the representation class for his flavor is remote.
   *
   * @return <code>true</code> if the representation class is remote,
   * <code>false</code> otherwise.
   */
  public boolean isRepresentationClassRemote()
  {
    return Remote.class.isAssignableFrom (representationClass);
  }
Tom Tromey committed
585

586 587 588 589 590 591 592 593
  /**
   * Tests whether or not this flavor represents a serialized object.
   *
   * @return <code>true</code> if this flavor represents a serialized
   * object, <code>false</code> otherwise.
   */
  public boolean isFlavorSerializedObjectType()
  {
594 595
    return isRepresentationClassSerializable()
           && isMimeTypeEqual(javaSerializedObjectMimeType);
596
  }
Tom Tromey committed
597

598 599 600 601 602 603 604 605
  /**
   * Tests whether or not this flavor represents a remote object.
   *
   * @return <code>true</code> if this flavor represents a remote object,
   * <code>false</code> otherwise.
   */
  public boolean isFlavorRemoteObjectType()
  {
606 607 608
    return isRepresentationClassRemote()
           && isRepresentationClassSerializable()
           && isMimeTypeEqual(javaRemoteObjectMimeType);
609
  }
Tom Tromey committed
610

611 612 613 614 615 616 617 618
  /**
   * Tests whether or not this flavor represents a list of files.
   *
   * @return <code>true</code> if this flavor represents a list of files,
   * <code>false</code> otherwise.
   */
  public boolean isFlavorJavaFileListType()
  {
619 620 621
    if (getPrimaryType().equals(javaFileListFlavor.getPrimaryType())
        && getSubType().equals(javaFileListFlavor.getSubType())
        && javaFileListFlavor.representationClass
622
           .isAssignableFrom(representationClass))
623
      return true;
624

625 626
    return false ;
  }
Tom Tromey committed
627

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  /**
   * Returns a copy of this object.
   *
   * @return A copy of this object.
   *
   * @exception CloneNotSupportedException If the object's class does not support
   * the Cloneable interface. Subclasses that override the clone method can also
   * throw this exception to indicate that an instance cannot be cloned.
   */
  public Object clone () throws CloneNotSupportedException
  {
    // FIXME - This cannot be right.
    try
      {
        return super.clone();
      }
    catch(Exception e)
      {
        return null;
      }
  }
Tom Tromey committed
649

650 651 652
  /**
   * This method test the specified <code>DataFlavor</code> for equality
   * against this object.  This will be true if the MIME type and
653 654 655 656 657
   * representation class are the equal. If the primary type is 'text'
   * then also the value of the charset parameter is compared. In such a
   * case when the charset parameter isn't given then the charset is
   * assumed to be equal to the default charset of the platform.  All
   * other parameters are ignored.
658 659 660 661 662 663 664 665 666 667
   *
   * @param flavor The <code>DataFlavor</code> to test against.
   *
   * @return <code>true</code> if the flavor is equal to this object,
   * <code>false</code> otherwise.
   */
  public boolean equals(DataFlavor flavor)
  {
    if (flavor == null)
      return false;
668 669 670

    String primary = getPrimaryType();
    if (! primary.equals(flavor.getPrimaryType()))
671
      return false;
672 673 674 675 676

    String sub = getSubType();
    if (! sub.equals(flavor.getSubType()))
      return false;

677 678
    if (! this.representationClass.equals(flavor.representationClass))
      return false;
679 680 681 682 683

    if (primary.equals("text"))
      if (! isRepresentationClassCharBuffer()
          && ! isRepresentationClassReader()
          && representationClass != java.lang.String.class
684 685 686 687 688 689 690 691
          && ! (representationClass.isArray()
                && representationClass.getComponentType() == Character.TYPE))
        {
          String charset = getParameter("charset");
          String otherset = flavor.getParameter("charset");
          String defaultset = Charset.defaultCharset().name();

          if (charset == null || charset.equals(defaultset))
692 693
            return (otherset == null || otherset.equals(defaultset));

694 695 696
          return charset.equals(otherset);
        }

697 698
    return true;
  }
Tom Tromey committed
699

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
  /**
   * This method test the specified <code>Object</code> for equality
   * against this object.  This will be true if the following conditions
   * are met:
   * <p>
   * <ul>
   * <li>The object is not <code>null</code>.</li>
   * <li>The object is an instance of <code>DataFlavor</code>.</li>
   * <li>The object's MIME type and representation class are equal to
   * this object's.</li>
   * </ul>
   *
   * @param obj The <code>Object</code> to test against.
   *
   * @return <code>true</code> if the flavor is equal to this object,
   * <code>false</code> otherwise.
   */
  public boolean equals(Object obj)
  {
    if (! (obj instanceof DataFlavor))
      return false;
721

722 723
    return equals((DataFlavor) obj);
  }
Tom Tromey committed
724

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
  /**
   * Tests whether or not the specified string is equal to the MIME type
   * of this object.
   *
   * @param str The string to test against.
   *
   * @return <code>true</code> if the string is equal to this object's MIME
   * type, <code>false</code> otherwise.
   *
   * @deprecated Not compatible with <code>hashCode()</code>.
   *             Use <code>isMimeTypeEqual()</code>
   */
  public boolean equals(String str)
  {
    return isMimeTypeEqual(str);
  }
Tom Tromey committed
741

742 743 744 745 746 747 748
  /**
   * Returns the hash code for this data flavor.
   * The hash code is based on the (lower case) mime type and the
   * representation class.
   */
  public int hashCode()
  {
749
    return mimeType.toString().hashCode() ^ representationClass.hashCode();
750
  }
Tom Tromey committed
751

752 753 754 755 756 757 758 759 760
  /**
   * Returns <code>true</code> when the given <code>DataFlavor</code>
   * matches this one.
   */
  public boolean match(DataFlavor dataFlavor)
  {
    // XXX - How is this different from equals?
    return equals(dataFlavor);
  }
Tom Tromey committed
761

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
  /**
   * This method exists for backward compatibility.  It simply returns
   * the same name/value pair passed in.
   *
   * @param name The parameter name.
   * @param value The parameter value.
   *
   * @return The name/value pair.
   *
   * @deprecated
   */
  protected String normalizeMimeTypeParameter(String name, String value)
  {
    return name + "=" + value;
  }
Tom Tromey committed
777

778 779 780 781 782
  /**
   * This method exists for backward compatibility.  It simply returns
   * the MIME type string unchanged.
   *
   * @param type The MIME type.
783
   *
784 785 786 787 788 789 790 791
   * @return The MIME type.
   *
   * @deprecated
   */
  protected String normalizeMimeType(String type)
  {
    return type;
  }
Tom Tromey committed
792

793 794 795 796 797 798 799
  /**
   * Serialize this class.
   *
   * @param stream The <code>ObjectOutput</code> stream to serialize to.
   *
   * @exception IOException If an error occurs.
   */
800
  public void writeExternal(ObjectOutput stream)
801
    throws IOException
802
  {
803 804 805 806 807 808 809 810 811
    if (mimeType != null)
      {
        mimeType.addParameter("humanPresentableName", humanPresentableName);
        stream.writeObject(mimeType);
        mimeType.removeParameter("humanPresentableName");
      }
    else
      stream.writeObject(null);
    stream.writeObject(representationClass);
812
  }
Tom Tromey committed
813 814


815 816 817 818 819 820 821 822 823
  /**
   * De-serialize this class.
   *
   * @param stream The <code>ObjectInput</code> stream to deserialize from.
   *
   * @exception IOException If an error ocurs.
   * @exception ClassNotFoundException If the class for an object being restored
   * cannot be found.
   */
824
  public void readExternal(ObjectInput stream)
825
    throws IOException, ClassNotFoundException
826
  {
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
    mimeType = (MimeType) stream.readObject();
    String className = null;
    if (mimeType != null)
      {
        humanPresentableName =
          mimeType.getParameter("humanPresentableName");
        mimeType.removeParameter("humanPresentableName");
        className = mimeType.getParameter("class");
        if (className == null)
          throw new IOException("No class in mime type");
      }
    try
      {
        representationClass = (Class) stream.readObject();
      }
    catch (OptionalDataException ex)
      {
        if (ex.eof && ex.length == 0)
          {
            if (className != null)
              representationClass = tryToLoadClass(className,
                                                  getClass().getClassLoader());
          }
        else
          throw ex;
      }
853
  }
Tom Tromey committed
854

855 856 857 858 859 860 861 862 863 864 865 866
  /**
   * Returns a string representation of this DataFlavor. Including the
   * representation class name, MIME type and human presentable name.
   */
  public String toString()
  {
    return (getClass().getName()
           + "[representationClass=" + getRepresentationClass().getName()
           + ",mimeType=" + getMimeType()
           + ",humanPresentableName=" + getHumanPresentableName()
           + "]");
  }
Tom Tromey committed
867

868 869 870 871 872
  /**
   * XXX - Currently returns <code>java.io.InputStream</code>.
   *
   * @since 1.3
   */
873
  public final Class<?> getDefaultRepresentationClass()
874 875 876
  {
    return java.io.InputStream.class;
  }
Tom Tromey committed
877

878 879 880 881 882 883 884
  /**
   * XXX - Currently returns <code>java.io.InputStream</code>.
   */
  public final String getDefaultRepresentationClassAsString()
  {
    return getDefaultRepresentationClass().getName();
  }
Tom Tromey committed
885

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
  /**
   * Creates a <code>Reader</code> for a given <code>Transferable</code>.
   *
   * If the representation class is a (subclass of) <code>Reader</code>
   * then an instance of the representation class is returned. If the
   * representatation class is a <code>String</code> then a
   * <code>StringReader</code> is returned. And if the representation class
   * is a (subclass of) <code>InputStream</code> and the primary MIME type
   * is "text" then a <code>InputStreamReader</code> for the correct charset
   * encoding is returned.
   *
   * @param transferable The <code>Transferable</code> for which a text
   *                     <code>Reader</code> is requested.
   *
   * @exception IllegalArgumentException If the representation class is not one
   * of the seven listed above or the Transferable has null data.
   * @exception NullPointerException If the Transferable is null.
   * @exception UnsupportedFlavorException when the transferable doesn't
   * support this <code>DataFlavor</code>. Or if the representable class
   * isn't a (subclass of) <code>Reader</code>, <code>String</code>,
   * <code>InputStream</code> and/or the primary MIME type isn't "text".
   * @exception IOException when any IOException occurs.
   * @exception UnsupportedEncodingException if the "charset" isn't supported
   * on this platform.
   */
  public Reader getReaderForText(Transferable transferable)
    throws UnsupportedFlavorException, IOException
  {
      if (!transferable.isDataFlavorSupported(this))
          throw new UnsupportedFlavorException(this);
916

917 918
      if (Reader.class.isAssignableFrom(representationClass))
          return (Reader)transferable.getTransferData(this);
919

920 921
      if (String.class.isAssignableFrom(representationClass))
          return new StringReader((String)transferable.getTransferData(this));
922

923 924
      if (InputStream.class.isAssignableFrom(representationClass)
          && "text".equals(getPrimaryType()))
Tom Tromey committed
925
        {
926 927
          InputStream in = (InputStream)transferable.getTransferData(this);
          String encoding = getParameter("charset");
Tom Tromey committed
928
          if (encoding == null)
929 930
              encoding = "us-ascii";
          return new InputStreamReader(in, encoding);
Tom Tromey committed
931
        }
932

933 934
      throw new UnsupportedFlavorException(this);
  }
Tom Tromey committed
935 936 937 938 939 940 941

  /**
   * Returns whether the representation class for this DataFlavor is
   * @see java.nio.ByteBuffer or a subclass thereof.
   *
   * @since 1.4
   */
942
  public boolean isRepresentationClassByteBuffer()
Tom Tromey committed
943
  {
944
    return ByteBuffer.class.isAssignableFrom(representationClass);
Tom Tromey committed
945 946 947 948 949 950 951 952
  }

  /**
   * Returns whether the representation class for this DataFlavor is
   * @see java.nio.CharBuffer or a subclass thereof.
   *
   * @since 1.4
   */
953
  public boolean isRepresentationClassCharBuffer()
Tom Tromey committed
954
  {
955
    return CharBuffer.class.isAssignableFrom(representationClass);
Tom Tromey committed
956 957 958 959 960 961 962 963
  }

  /**
   * Returns whether the representation class for this DataFlavor is
   * @see java.io.Reader or a subclass thereof.
   *
   * @since 1.4
   */
964
  public boolean isRepresentationClassReader()
Tom Tromey committed
965
  {
966 967
    return Reader.class.isAssignableFrom(representationClass);
  }
968

969 970 971 972 973 974 975 976 977
  /**
   * Returns whether this <code>DataFlavor</code> is a valid text flavor for
   * this implementation of the Java platform. Only flavors equivalent to
   * <code>DataFlavor.stringFlavor</code> and <code>DataFlavor</code>s with
   * a primary MIME type of "text" can be valid text flavors.
   * <p>
   * If this flavor supports the charset parameter, it must be equivalent to
   * <code>DataFlavor.stringFlavor</code>, or its representation must be
   * <code>java.io.Reader</code>, <code>java.lang.String</code>,
978
   * <code>java.nio.CharBuffer</code>, <code>java.io.InputStream</code> or
979
   * <code>java.nio.ByteBuffer</code>,
980 981 982 983
   * If the representation is <code>java.io.InputStream</code> or
   * <code>java.nio.ByteBuffer</code>, then this flavor's <code>charset</code>
   * parameter must be supported by this implementation of the Java platform.
   * If a charset is not specified, then the platform default charset, which
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
   * is always supported, is assumed.
   * <p>
   * If this flavor does not support the charset parameter, its
   * representation must be <code>java.io.InputStream</code>,
   * <code>java.nio.ByteBuffer</code>.
   * <p>
   * See <code>selectBestTextFlavor</code> for a list of text flavors which
   * support the charset parameter.
   *
   * @return <code>true</code> if this <code>DataFlavor</code> is a valid
   *         text flavor as described above; <code>false</code> otherwise
   * @see #selectBestTextFlavor
   * @since 1.4
   */
  public boolean isFlavorTextType() {
999
    // FIXME: I'm not 100% sure if this implementation does the same like sun's does
1000 1001 1002 1003
    if(equals(DataFlavor.stringFlavor) || getPrimaryType().equals("text"))
      {
        String charset = getParameter("charset");
        Class c = getRepresentationClass();
1004 1005 1006 1007 1008
        if(charset != null)
          {
            if(Reader.class.isAssignableFrom(c)
                || CharBuffer.class.isAssignableFrom(c)
                || String.class.isAssignableFrom(c))
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
              {
                return true;
              }
            else if(InputStream.class.isAssignableFrom(c)
                    || ByteBuffer.class.isAssignableFrom(c))
              {
                return Charset.isSupported(charset);
              }
          }
        else if(InputStream.class.isAssignableFrom(c)
            || ByteBuffer.class.isAssignableFrom(c))
          {
            return true;
          }
      }
    return false;
Tom Tromey committed
1025 1026
  }
} // class DataFlavor