1 /*
   2  * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.awt.datatransfer;
  27 
  28 import sun.awt.datatransfer.DataTransferer;
  29 import sun.reflect.misc.ReflectUtil;
  30 
  31 import java.io.ByteArrayInputStream;
  32 import java.io.CharArrayReader;
  33 import java.io.Externalizable;
  34 import java.io.IOException;
  35 import java.io.InputStream;
  36 import java.io.InputStreamReader;
  37 import java.io.ObjectInput;
  38 import java.io.ObjectOutput;
  39 import java.io.OptionalDataException;
  40 import java.io.Reader;
  41 import java.io.StringReader;
  42 import java.io.UnsupportedEncodingException;
  43 import java.nio.ByteBuffer;
  44 import java.nio.CharBuffer;
  45 import java.util.Arrays;
  46 import java.util.Collections;
  47 import java.util.Comparator;
  48 import java.util.Objects;
  49 
  50 import static sun.security.util.SecurityConstants.GET_CLASSLOADER_PERMISSION;
  51 
  52 /**
  53  * A {@code DataFlavor} provides meta information about data. {@code DataFlavor}
  54  * is typically used to access data on the clipboard, or during
  55  * a drag and drop operation.
  56  * <p>
  57  * An instance of {@code DataFlavor} encapsulates a content type as
  58  * defined in <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
  59  * and <a href="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</a>.
  60  * A content type is typically referred to as a MIME type.
  61  * <p>
  62  * A content type consists of a media type (referred
  63  * to as the primary type), a subtype, and optional parameters. See
  64  * <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
  65  * for details on the syntax of a MIME type.
  66  * <p>
  67  * The JRE data transfer implementation interprets the parameter &quot;class&quot;
  68  * of a MIME type as <B>a representation class</b>.
  69  * The representation class reflects the class of the object being
  70  * transferred. In other words, the representation class is the type of
  71  * object returned by {@link Transferable#getTransferData}.
  72  * For example, the MIME type of {@link #imageFlavor} is
  73  * {@code "image/x-java-image;class=java.awt.Image"},
  74  * the primary type is {@code image}, the subtype is
  75  * {@code x-java-image}, and the representation class is
  76  * {@code java.awt.Image}. When {@code getTransferData} is invoked
  77  * with a {@code DataFlavor} of {@code imageFlavor}, an instance of
  78  * {@code java.awt.Image} is returned.
  79  * It's important to note that {@code DataFlavor} does no error checking
  80  * against the representation class. It is up to consumers of
  81  * {@code DataFlavor}, such as {@code Transferable}, to honor the representation
  82  * class.
  83  * <br>
  84  * Note, if you do not specify a representation class when
  85  * creating a {@code DataFlavor}, the default
  86  * representation class is used. See appropriate documentation for
  87  * {@code DataFlavor}'s constructors.
  88  * <p>
  89  * Also, {@code DataFlavor} instances with the &quot;text&quot; primary
  90  * MIME type may have a &quot;charset&quot; parameter. Refer to
  91  * <a href="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</a> and
  92  * {@link #selectBestTextFlavor} for details on &quot;text&quot; MIME types
  93  * and the &quot;charset&quot; parameter.
  94  * <p>
  95  * Equality of {@code DataFlavors} is determined by the primary type,
  96  * subtype, and representation class. Refer to {@link #equals(DataFlavor)} for
  97  * details. When determining equality, any optional parameters are ignored.
  98  * For example, the following produces two {@code DataFlavors} that
  99  * are considered identical:
 100  * <pre>
 101  *   DataFlavor flavor1 = new DataFlavor(Object.class, &quot;X-test/test; class=&lt;java.lang.Object&gt;; foo=bar&quot;);
 102  *   DataFlavor flavor2 = new DataFlavor(Object.class, &quot;X-test/test; class=&lt;java.lang.Object&gt;; x=y&quot;);
 103  *   // The following returns true.
 104  *   flavor1.equals(flavor2);
 105  * </pre>
 106  * As mentioned, {@code flavor1} and {@code flavor2} are considered identical.
 107  * As such, asking a {@code Transferable} for either {@code DataFlavor} returns
 108  * the same results.
 109  * <p>
 110  * For more information on the using data transfer with Swing see
 111  * the <a href="https://docs.oracle.com/javase/tutorial/uiswing/dnd/index.html">
 112  * How to Use Drag and Drop and Data Transfer</a>,
 113  * section in <em>Java Tutorial</em>.
 114  *
 115  * @author      Blake Sullivan
 116  * @author      Laurence P. G. Cable
 117  * @author      Jeff Dunn
 118  */
 119 public class DataFlavor implements Externalizable, Cloneable {
 120 
 121     private static final long serialVersionUID = 8367026044764648243L;
 122     private static final Class<InputStream> ioInputStreamClass = InputStream.class;
 123 
 124     /**
 125      * Tries to load a class from: the bootstrap loader, the system loader,
 126      * the context loader (if one is present) and finally the loader specified.
 127      *
 128      * @param className the name of the class to be loaded
 129      * @param fallback the fallback loader
 130      * @return the class loaded
 131      * @exception ClassNotFoundException if class is not found
 132      */
 133     protected final static Class<?> tryToLoadClass(String className,
 134                                                    ClassLoader fallback)
 135         throws ClassNotFoundException
 136     {
 137         ReflectUtil.checkPackageAccess(className);
 138         try {
 139             SecurityManager sm = System.getSecurityManager();
 140             if (sm != null) {
 141                 sm.checkPermission(GET_CLASSLOADER_PERMISSION);
 142             }
 143             ClassLoader loader = ClassLoader.getSystemClassLoader();
 144             try {
 145                 // bootstrap class loader and system class loader if present
 146                 return Class.forName(className, true, loader);
 147             }
 148             catch (ClassNotFoundException exception) {
 149                 // thread context class loader if and only if present
 150                 loader = Thread.currentThread().getContextClassLoader();
 151                 if (loader != null) {
 152                     try {
 153                         return Class.forName(className, true, loader);
 154                     }
 155                     catch (ClassNotFoundException e) {
 156                         // fallback to user's class loader
 157                     }
 158                 }
 159             }
 160         } catch (SecurityException exception) {
 161             // ignore secured class loaders
 162         }
 163         return Class.forName(className, true, fallback);
 164     }
 165 
 166     /*
 167      * private initializer
 168      */
 169     static private DataFlavor createConstant(Class<?> rc, String prn) {
 170         try {
 171             return new DataFlavor(rc, prn);
 172         } catch (Exception e) {
 173             return null;
 174         }
 175     }
 176 
 177     /*
 178      * private initializer
 179      */
 180     static private DataFlavor createConstant(String mt, String prn) {
 181         try {
 182             return new DataFlavor(mt, prn);
 183         } catch (Exception e) {
 184             return null;
 185         }
 186     }
 187 
 188     /*
 189      * private initializer
 190      */
 191     static private DataFlavor initHtmlDataFlavor(String htmlFlavorType) {
 192         try {
 193             return new DataFlavor ("text/html; class=java.lang.String;document=" +
 194                                        htmlFlavorType + ";charset=Unicode");
 195         } catch (Exception e) {
 196             return null;
 197         }
 198     }
 199 
 200     /**
 201      * The <code>DataFlavor</code> representing a Java Unicode String class,
 202      * where:
 203      * <pre>
 204      *     representationClass = java.lang.String
 205      *     mimeType           = "application/x-java-serialized-object"
 206      * </pre>
 207      */
 208     public static final DataFlavor stringFlavor = createConstant(java.lang.String.class, "Unicode String");
 209 
 210     /**
 211      * The <code>DataFlavor</code> representing a Java Image class,
 212      * where:
 213      * <pre>
 214      *     representationClass = java.awt.Image
 215      *     mimeType            = "image/x-java-image"
 216      * </pre>
 217      */
 218     public static final DataFlavor imageFlavor = createConstant("image/x-java-image; class=java.awt.Image", "Image");
 219 
 220     /**
 221      * The <code>DataFlavor</code> representing plain text with Unicode
 222      * encoding, where:
 223      * <pre>
 224      *     representationClass = InputStream
 225      *     mimeType            = "text/plain; charset=unicode"
 226      * </pre>
 227      * This <code>DataFlavor</code> has been <b>deprecated</b> because
 228      * (1) Its representation is an InputStream, an 8-bit based representation,
 229      * while Unicode is a 16-bit character set; and (2) The charset "unicode"
 230      * is not well-defined. "unicode" implies a particular platform's
 231      * implementation of Unicode, not a cross-platform implementation.
 232      *
 233      * @deprecated as of 1.3. Use <code>DataFlavor.getReaderForText(Transferable)</code>
 234      *             instead of <code>Transferable.getTransferData(DataFlavor.plainTextFlavor)</code>.
 235      */
 236     @Deprecated
 237     public static final DataFlavor plainTextFlavor = createConstant("text/plain; charset=unicode; class=java.io.InputStream", "Plain Text");
 238 
 239     /**
 240      * A MIME Content-Type of application/x-java-serialized-object represents
 241      * a graph of Java object(s) that have been made persistent.
 242      *
 243      * The representation class associated with this <code>DataFlavor</code>
 244      * identifies the Java type of an object returned as a reference
 245      * from an invocation <code>java.awt.datatransfer.getTransferData</code>.
 246      */
 247     public static final String javaSerializedObjectMimeType = "application/x-java-serialized-object";
 248 
 249     /**
 250      * To transfer a list of files to/from Java (and the underlying
 251      * platform) a <code>DataFlavor</code> of this type/subtype and
 252      * representation class of <code>java.util.List</code> is used.
 253      * Each element of the list is required/guaranteed to be of type
 254      * <code>java.io.File</code>.
 255      */
 256     public static final DataFlavor javaFileListFlavor = createConstant("application/x-java-file-list;class=java.util.List", null);
 257 
 258     /**
 259      * To transfer a reference to an arbitrary Java object reference that
 260      * has no associated MIME Content-type, across a <code>Transferable</code>
 261      * interface WITHIN THE SAME JVM, a <code>DataFlavor</code>
 262      * with this type/subtype is used, with a <code>representationClass</code>
 263      * equal to the type of the class/interface being passed across the
 264      * <code>Transferable</code>.
 265      * <p>
 266      * The object reference returned from
 267      * <code>Transferable.getTransferData</code> for a <code>DataFlavor</code>
 268      * with this MIME Content-Type is required to be
 269      * an instance of the representation Class of the <code>DataFlavor</code>.
 270      */
 271     public static final String javaJVMLocalObjectMimeType = "application/x-java-jvm-local-objectref";
 272 
 273     /**
 274      * In order to pass a live link to a Remote object via a Drag and Drop
 275      * <code>ACTION_LINK</code> operation a Mime Content Type of
 276      * application/x-java-remote-object should be used,
 277      * where the representation class of the <code>DataFlavor</code>
 278      * represents the type of the <code>Remote</code> interface to be
 279      * transferred.
 280      */
 281     public static final String javaRemoteObjectMimeType = "application/x-java-remote-object";
 282 
 283     /**
 284      * Represents a piece of an HTML markup. The markup consists of the part
 285      * selected on the source side. Therefore some tags in the markup may be
 286      * unpaired. If the flavor is used to represent the data in
 287      * a {@link Transferable} instance, no additional changes will be made.
 288      * This DataFlavor instance represents the same HTML markup as DataFlavor
 289      * instances which content MIME type does not contain document parameter
 290      * and representation class is the String class.
 291      * <pre>
 292      *     representationClass = String
 293      *     mimeType           = "text/html"
 294      * </pre>
 295      */
 296     public static DataFlavor selectionHtmlFlavor = initHtmlDataFlavor("selection");
 297 
 298     /**
 299      * Represents a piece of an HTML markup. If possible, the markup received
 300      * from a native system is supplemented with pair tags to be
 301      * a well-formed HTML markup. If the flavor is used to represent the data in
 302      * a {@link Transferable} instance, no additional changes will be made.
 303      * <pre>
 304      *     representationClass = String
 305      *     mimeType           = "text/html"
 306      * </pre>
 307      */
 308     public static DataFlavor fragmentHtmlFlavor = initHtmlDataFlavor("fragment");
 309 
 310     /**
 311      * Represents a piece of an HTML markup. If possible, the markup
 312      * received from a native system is supplemented with additional
 313      * tags to make up a well-formed HTML document. If the flavor is used to
 314      * represent the data in a {@link Transferable} instance,
 315      * no additional changes will be made.
 316      * <pre>
 317      *     representationClass = String
 318      *     mimeType           = "text/html"
 319      * </pre>
 320      */
 321     public static  DataFlavor allHtmlFlavor = initHtmlDataFlavor("all");
 322 
 323     /**
 324      * Constructs a new <code>DataFlavor</code>.  This constructor is
 325      * provided only for the purpose of supporting the
 326      * <code>Externalizable</code> interface.  It is not
 327      * intended for public (client) use.
 328      *
 329      * @since 1.2
 330      */
 331     public DataFlavor() {
 332         super();
 333     }
 334 
 335     /**
 336      * Constructs a fully specified <code>DataFlavor</code>.
 337      *
 338      * @exception NullPointerException if either <code>primaryType</code>,
 339      *            <code>subType</code> or <code>representationClass</code> is null
 340      */
 341     private DataFlavor(String primaryType, String subType, MimeTypeParameterList params, Class<?> representationClass, String humanPresentableName) {
 342         super();
 343         if (primaryType == null) {
 344             throw new NullPointerException("primaryType");
 345         }
 346         if (subType == null) {
 347             throw new NullPointerException("subType");
 348         }
 349         if (representationClass == null) {
 350             throw new NullPointerException("representationClass");
 351         }
 352 
 353         if (params == null) params = new MimeTypeParameterList();
 354 
 355         params.set("class", representationClass.getName());
 356 
 357         if (humanPresentableName == null) {
 358             humanPresentableName = params.get("humanPresentableName");
 359 
 360             if (humanPresentableName == null)
 361                 humanPresentableName = primaryType + "/" + subType;
 362         }
 363 
 364         try {
 365             mimeType = new MimeType(primaryType, subType, params);
 366         } catch (MimeTypeParseException mtpe) {
 367             throw new IllegalArgumentException("MimeType Parse Exception: " + mtpe.getMessage());
 368         }
 369 
 370         this.representationClass  = representationClass;
 371         this.humanPresentableName = humanPresentableName;
 372 
 373         mimeType.removeParameter("humanPresentableName");
 374     }
 375 
 376     /**
 377      * Constructs a <code>DataFlavor</code> that represents a Java class.
 378      * <p>
 379      * The returned <code>DataFlavor</code> will have the following
 380      * characteristics:
 381      * <pre>
 382      *    representationClass = representationClass
 383      *    mimeType            = application/x-java-serialized-object
 384      * </pre>
 385      * @param representationClass the class used to transfer data in this flavor
 386      * @param humanPresentableName the human-readable string used to identify
 387      *                 this flavor; if this parameter is <code>null</code>
 388      *                 then the value of the the MIME Content Type is used
 389      * @exception NullPointerException if <code>representationClass</code> is null
 390      */
 391     public DataFlavor(Class<?> representationClass, String humanPresentableName) {
 392         this("application", "x-java-serialized-object", null, representationClass, humanPresentableName);
 393         if (representationClass == null) {
 394             throw new NullPointerException("representationClass");
 395         }
 396     }
 397 
 398     /**
 399      * Constructs a <code>DataFlavor</code> that represents a
 400      * <code>MimeType</code>.
 401      * <p>
 402      * The returned <code>DataFlavor</code> will have the following
 403      * characteristics:
 404      * <p>
 405      * If the <code>mimeType</code> is
 406      * "application/x-java-serialized-object; class=&lt;representation class&gt;",
 407      * the result is the same as calling
 408      * <code>new DataFlavor(Class:forName(&lt;representation class&gt;)</code>.
 409      * <p>
 410      * Otherwise:
 411      * <pre>
 412      *     representationClass = InputStream
 413      *     mimeType            = mimeType
 414      * </pre>
 415      * @param mimeType the string used to identify the MIME type for this flavor;
 416      *                 if the the <code>mimeType</code> does not specify a
 417      *                 "class=" parameter, or if the class is not successfully
 418      *                 loaded, then an <code>IllegalArgumentException</code>
 419      *                 is thrown
 420      * @param humanPresentableName the human-readable string used to identify
 421      *                 this flavor; if this parameter is <code>null</code>
 422      *                 then the value of the the MIME Content Type is used
 423      * @exception IllegalArgumentException if <code>mimeType</code> is
 424      *                 invalid or if the class is not successfully loaded
 425      * @exception NullPointerException if <code>mimeType</code> is null
 426      */
 427     public DataFlavor(String mimeType, String humanPresentableName) {
 428         super();
 429         if (mimeType == null) {
 430             throw new NullPointerException("mimeType");
 431         }
 432         try {
 433             initialize(mimeType, humanPresentableName, this.getClass().getClassLoader());
 434         } catch (MimeTypeParseException mtpe) {
 435             throw new IllegalArgumentException("failed to parse:" + mimeType);
 436         } catch (ClassNotFoundException cnfe) {
 437             throw new IllegalArgumentException("can't find specified class: " + cnfe.getMessage());
 438         }
 439     }
 440 
 441     /**
 442      * Constructs a <code>DataFlavor</code> that represents a
 443      * <code>MimeType</code>.
 444      * <p>
 445      * The returned <code>DataFlavor</code> will have the following
 446      * characteristics:
 447      * <p>
 448      * If the mimeType is
 449      * "application/x-java-serialized-object; class=&lt;representation class&gt;",
 450      * the result is the same as calling
 451      * <code>new DataFlavor(Class:forName(&lt;representation class&gt;)</code>.
 452      * <p>
 453      * Otherwise:
 454      * <pre>
 455      *     representationClass = InputStream
 456      *     mimeType            = mimeType
 457      * </pre>
 458      * @param mimeType the string used to identify the MIME type for this flavor
 459      * @param humanPresentableName the human-readable string used to
 460      *          identify this flavor
 461      * @param classLoader the class loader to use
 462      * @exception ClassNotFoundException if the class is not loaded
 463      * @exception IllegalArgumentException if <code>mimeType</code> is
 464      *                 invalid
 465      * @exception NullPointerException if <code>mimeType</code> is null
 466      */
 467     public DataFlavor(String mimeType, String humanPresentableName, ClassLoader classLoader) throws ClassNotFoundException {
 468         super();
 469         if (mimeType == null) {
 470             throw new NullPointerException("mimeType");
 471         }
 472         try {
 473             initialize(mimeType, humanPresentableName, classLoader);
 474         } catch (MimeTypeParseException mtpe) {
 475             throw new IllegalArgumentException("failed to parse:" + mimeType);
 476         }
 477     }
 478 
 479     /**
 480      * Constructs a <code>DataFlavor</code> from a <code>mimeType</code> string.
 481      * The string can specify a "class=&lt;fully specified Java class name&gt;"
 482      * parameter to create a <code>DataFlavor</code> with the desired
 483      * representation class. If the string does not contain "class=" parameter,
 484      * <code>java.io.InputStream</code> is used as default.
 485      *
 486      * @param mimeType the string used to identify the MIME type for this flavor;
 487      *                 if the class specified by "class=" parameter is not
 488      *                 successfully loaded, then an
 489      *                 <code>ClassNotFoundException</code> is thrown
 490      * @exception ClassNotFoundException if the class is not loaded
 491      * @exception IllegalArgumentException if <code>mimeType</code> is
 492      *                 invalid
 493      * @exception NullPointerException if <code>mimeType</code> is null
 494      */
 495     public DataFlavor(String mimeType) throws ClassNotFoundException {
 496         super();
 497         if (mimeType == null) {
 498             throw new NullPointerException("mimeType");
 499         }
 500         try {
 501             initialize(mimeType, null, this.getClass().getClassLoader());
 502         } catch (MimeTypeParseException mtpe) {
 503             throw new IllegalArgumentException("failed to parse:" + mimeType);
 504         }
 505     }
 506 
 507    /**
 508     * Common initialization code called from various constructors.
 509     *
 510     * @param mimeType the MIME Content Type (must have a class= param)
 511     * @param humanPresentableName the human Presentable Name or
 512     *                 <code>null</code>
 513     * @param classLoader the fallback class loader to resolve against
 514     *
 515     * @throws MimeTypeParseException
 516     * @throws ClassNotFoundException
 517     * @throws  NullPointerException if <code>mimeType</code> is null
 518     *
 519     * @see #tryToLoadClass
 520     */
 521     private void initialize(String mimeType, String humanPresentableName, ClassLoader classLoader) throws MimeTypeParseException, ClassNotFoundException {
 522         if (mimeType == null) {
 523             throw new NullPointerException("mimeType");
 524         }
 525 
 526         this.mimeType = new MimeType(mimeType); // throws
 527 
 528         String rcn = getParameter("class");
 529 
 530         if (rcn == null) {
 531             if ("application/x-java-serialized-object".equals(this.mimeType.getBaseType()))
 532 
 533                 throw new IllegalArgumentException("no representation class specified for:" + mimeType);
 534             else
 535                 representationClass = java.io.InputStream.class; // default
 536         } else { // got a class name
 537             representationClass = DataFlavor.tryToLoadClass(rcn, classLoader);
 538         }
 539 
 540         this.mimeType.setParameter("class", representationClass.getName());
 541 
 542         if (humanPresentableName == null) {
 543             humanPresentableName = this.mimeType.getParameter("humanPresentableName");
 544             if (humanPresentableName == null)
 545                 humanPresentableName = this.mimeType.getPrimaryType() + "/" + this.mimeType.getSubType();
 546         }
 547 
 548         this.humanPresentableName = humanPresentableName; // set it.
 549 
 550         this.mimeType.removeParameter("humanPresentableName"); // just in case
 551     }
 552 
 553     /**
 554      * String representation of this <code>DataFlavor</code> and its
 555      * parameters. The resulting <code>String</code> contains the name of
 556      * the <code>DataFlavor</code> class, this flavor's MIME type, and its
 557      * representation class. If this flavor has a primary MIME type of "text",
 558      * supports the charset parameter, and has an encoded representation, the
 559      * flavor's charset is also included. See <code>selectBestTextFlavor</code>
 560      * for a list of text flavors which support the charset parameter.
 561      *
 562      * @return  string representation of this <code>DataFlavor</code>
 563      * @see #selectBestTextFlavor
 564      */
 565     public String toString() {
 566         String string = getClass().getName();
 567         string += "["+paramString()+"]";
 568         return string;
 569     }
 570 
 571     private String paramString() {
 572         String params = "";
 573         params += "mimetype=";
 574         if (mimeType == null) {
 575             params += "null";
 576         } else {
 577             params += mimeType.getBaseType();
 578         }
 579         params += ";representationclass=";
 580         if (representationClass == null) {
 581            params += "null";
 582         } else {
 583            params += representationClass.getName();
 584         }
 585         if (DataTransferer.isFlavorCharsetTextType(this) &&
 586             (isRepresentationClassInputStream() ||
 587              isRepresentationClassByteBuffer() ||
 588              byte[].class.equals(representationClass)))
 589         {
 590             params += ";charset=" + DataTransferer.getTextCharset(this);
 591         }
 592         return params;
 593     }
 594 
 595     /**
 596      * Returns a <code>DataFlavor</code> representing plain text with Unicode
 597      * encoding, where:
 598      * <pre>
 599      *     representationClass = java.io.InputStream
 600      *     mimeType            = "text/plain;
 601      *                            charset=&lt;platform default Unicode encoding&gt;"
 602      * </pre>
 603      * Sun's implementation for Microsoft Windows uses the encoding <code>utf-16le</code>.
 604      * Sun's implementation for Solaris and Linux uses the encoding
 605      * <code>iso-10646-ucs-2</code>.
 606      *
 607      * @return a <code>DataFlavor</code> representing plain text
 608      *    with Unicode encoding
 609      * @since 1.3
 610      */
 611     public static final DataFlavor getTextPlainUnicodeFlavor() {
 612         String encoding = null;
 613         DataTransferer transferer = DataTransferer.getInstance();
 614         if (transferer != null) {
 615             encoding = transferer.getDefaultUnicodeEncoding();
 616         }
 617         return new DataFlavor(
 618             "text/plain;charset="+encoding
 619             +";class=java.io.InputStream", "Plain Text");
 620     }
 621 
 622     /**
 623      * Selects the best text <code>DataFlavor</code> from an array of <code>
 624      * DataFlavor</code>s. Only <code>DataFlavor.stringFlavor</code>, and
 625      * equivalent flavors, and flavors that have a primary MIME type of "text",
 626      * are considered for selection.
 627      * <p>
 628      * Flavors are first sorted by their MIME types in the following order:
 629      * <ul>
 630      * <li>"text/sgml"
 631      * <li>"text/xml"
 632      * <li>"text/html"
 633      * <li>"text/rtf"
 634      * <li>"text/enriched"
 635      * <li>"text/richtext"
 636      * <li>"text/uri-list"
 637      * <li>"text/tab-separated-values"
 638      * <li>"text/t140"
 639      * <li>"text/rfc822-headers"
 640      * <li>"text/parityfec"
 641      * <li>"text/directory"
 642      * <li>"text/css"
 643      * <li>"text/calendar"
 644      * <li>"application/x-java-serialized-object"
 645      * <li>"text/plain"
 646      * <li>"text/&lt;other&gt;"
 647      * </ul>
 648      * <p>For example, "text/sgml" will be selected over
 649      * "text/html", and <code>DataFlavor.stringFlavor</code> will be chosen
 650      * over <code>DataFlavor.plainTextFlavor</code>.
 651      * <p>
 652      * If two or more flavors share the best MIME type in the array, then that
 653      * MIME type will be checked to see if it supports the charset parameter.
 654      * <p>
 655      * The following MIME types support, or are treated as though they support,
 656      * the charset parameter:
 657      * <ul>
 658      * <li>"text/sgml"
 659      * <li>"text/xml"
 660      * <li>"text/html"
 661      * <li>"text/enriched"
 662      * <li>"text/richtext"
 663      * <li>"text/uri-list"
 664      * <li>"text/directory"
 665      * <li>"text/css"
 666      * <li>"text/calendar"
 667      * <li>"application/x-java-serialized-object"
 668      * <li>"text/plain"
 669      * </ul>
 670      * The following MIME types do not support, or are treated as though they
 671      * do not support, the charset parameter:
 672      * <ul>
 673      * <li>"text/rtf"
 674      * <li>"text/tab-separated-values"
 675      * <li>"text/t140"
 676      * <li>"text/rfc822-headers"
 677      * <li>"text/parityfec"
 678      * </ul>
 679      * For "text/&lt;other&gt;" MIME types, the first time the JRE needs to
 680      * determine whether the MIME type supports the charset parameter, it will
 681      * check whether the parameter is explicitly listed in an arbitrarily
 682      * chosen <code>DataFlavor</code> which uses that MIME type. If so, the JRE
 683      * will assume from that point on that the MIME type supports the charset
 684      * parameter and will not check again. If the parameter is not explicitly
 685      * listed, the JRE will assume from that point on that the MIME type does
 686      * not support the charset parameter and will not check again. Because
 687      * this check is performed on an arbitrarily chosen
 688      * <code>DataFlavor</code>, developers must ensure that all
 689      * <code>DataFlavor</code>s with a "text/&lt;other&gt;" MIME type specify
 690      * the charset parameter if it is supported by that MIME type. Developers
 691      * should never rely on the JRE to substitute the platform's default
 692      * charset for a "text/&lt;other&gt;" DataFlavor. Failure to adhere to this
 693      * restriction will lead to undefined behavior.
 694      * <p>
 695      * If the best MIME type in the array does not support the charset
 696      * parameter, the flavors which share that MIME type will then be sorted by
 697      * their representation classes in the following order:
 698      * <code>java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>,
 699      * <code>[B</code>, &lt;all others&gt;.
 700      * <p>
 701      * If two or more flavors share the best representation class, or if no
 702      * flavor has one of the three specified representations, then one of those
 703      * flavors will be chosen non-deterministically.
 704      * <p>
 705      * If the best MIME type in the array does support the charset parameter,
 706      * the flavors which share that MIME type will then be sorted by their
 707      * representation classes in the following order:
 708      * <code>java.io.Reader</code>, <code>java.lang.String</code>,
 709      * <code>java.nio.CharBuffer</code>, <code>[C</code>, &lt;all others&gt;.
 710      * <p>
 711      * If two or more flavors share the best representation class, and that
 712      * representation is one of the four explicitly listed, then one of those
 713      * flavors will be chosen non-deterministically. If, however, no flavor has
 714      * one of the four specified representations, the flavors will then be
 715      * sorted by their charsets. Unicode charsets, such as "UTF-16", "UTF-8",
 716      * "UTF-16BE", "UTF-16LE", and their aliases, are considered best. After
 717      * them, the platform default charset and its aliases are selected.
 718      * "US-ASCII" and its aliases are worst. All other charsets are chosen in
 719      * alphabetical order, but only charsets supported by this implementation
 720      * of the Java platform will be considered.
 721      * <p>
 722      * If two or more flavors share the best charset, the flavors will then
 723      * again be sorted by their representation classes in the following order:
 724      * <code>java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>,
 725      * <code>[B</code>, &lt;all others&gt;.
 726      * <p>
 727      * If two or more flavors share the best representation class, or if no
 728      * flavor has one of the three specified representations, then one of those
 729      * flavors will be chosen non-deterministically.
 730      *
 731      * @param availableFlavors an array of available <code>DataFlavor</code>s
 732      * @return the best (highest fidelity) flavor according to the rules
 733      *         specified above, or <code>null</code>,
 734      *         if <code>availableFlavors</code> is <code>null</code>,
 735      *         has zero length, or contains no text flavors
 736      * @since 1.3
 737      */
 738     public static final DataFlavor selectBestTextFlavor(
 739                                        DataFlavor[] availableFlavors) {
 740         if (availableFlavors == null || availableFlavors.length == 0) {
 741             return null;
 742         }
 743 
 744         if (textFlavorComparator == null) {
 745             textFlavorComparator = new TextFlavorComparator();
 746         }
 747 
 748         DataFlavor bestFlavor =
 749             (DataFlavor)Collections.max(Arrays.asList(availableFlavors),
 750                                         textFlavorComparator);
 751 
 752         if (!bestFlavor.isFlavorTextType()) {
 753             return null;
 754         }
 755 
 756         return bestFlavor;
 757     }
 758 
 759     private static Comparator<DataFlavor> textFlavorComparator;
 760 
 761     static class TextFlavorComparator
 762         extends DataTransferer.DataFlavorComparator {
 763 
 764         /**
 765          * Compares two <code>DataFlavor</code> objects. Returns a negative
 766          * integer, zero, or a positive integer as the first
 767          * <code>DataFlavor</code> is worse than, equal to, or better than the
 768          * second.
 769          * <p>
 770          * <code>DataFlavor</code>s are ordered according to the rules outlined
 771          * for <code>selectBestTextFlavor</code>.
 772          *
 773          * @param obj1 the first <code>DataFlavor</code> to be compared
 774          * @param obj2 the second <code>DataFlavor</code> to be compared
 775          * @return a negative integer, zero, or a positive integer as the first
 776          *         argument is worse, equal to, or better than the second
 777          * @throws ClassCastException if either of the arguments is not an
 778          *         instance of <code>DataFlavor</code>
 779          * @throws NullPointerException if either of the arguments is
 780          *         <code>null</code>
 781          *
 782          * @see #selectBestTextFlavor
 783          */
 784         public int compare(Object obj1, Object obj2) {
 785             DataFlavor flavor1 = (DataFlavor)obj1;
 786             DataFlavor flavor2 = (DataFlavor)obj2;
 787 
 788             if (flavor1.isFlavorTextType()) {
 789                 if (flavor2.isFlavorTextType()) {
 790                     return super.compare(obj1, obj2);
 791                 } else {
 792                     return 1;
 793                 }
 794             } else if (flavor2.isFlavorTextType()) {
 795                 return -1;
 796             } else {
 797                 return 0;
 798             }
 799         }
 800     }
 801 
 802     /**
 803      * Gets a Reader for a text flavor, decoded, if necessary, for the expected
 804      * charset (encoding). The supported representation classes are
 805      * <code>java.io.Reader</code>, <code>java.lang.String</code>,
 806      * <code>java.nio.CharBuffer</code>, <code>[C</code>,
 807      * <code>java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>,
 808      * and <code>[B</code>.
 809      * <p>
 810      * Because text flavors which do not support the charset parameter are
 811      * encoded in a non-standard format, this method should not be called for
 812      * such flavors. However, in order to maintain backward-compatibility,
 813      * if this method is called for such a flavor, this method will treat the
 814      * flavor as though it supports the charset parameter and attempt to
 815      * decode it accordingly. See <code>selectBestTextFlavor</code> for a list
 816      * of text flavors which do not support the charset parameter.
 817      *
 818      * @param transferable the <code>Transferable</code> whose data will be
 819      *        requested in this flavor
 820      *
 821      * @return a <code>Reader</code> to read the <code>Transferable</code>'s
 822      *         data
 823      *
 824      * @exception IllegalArgumentException if the representation class
 825      *            is not one of the seven listed above
 826      * @exception IllegalArgumentException if the <code>Transferable</code>
 827      *            has <code>null</code> data
 828      * @exception NullPointerException if the <code>Transferable</code> is
 829      *            <code>null</code>
 830      * @exception UnsupportedEncodingException if this flavor's representation
 831      *            is <code>java.io.InputStream</code>,
 832      *            <code>java.nio.ByteBuffer</code>, or <code>[B</code> and
 833      *            this flavor's encoding is not supported by this
 834      *            implementation of the Java platform
 835      * @exception UnsupportedFlavorException if the <code>Transferable</code>
 836      *            does not support this flavor
 837      * @exception IOException if the data cannot be read because of an
 838      *            I/O error
 839      * @see #selectBestTextFlavor
 840      * @since 1.3
 841      */
 842     public Reader getReaderForText(Transferable transferable)
 843         throws UnsupportedFlavorException, IOException
 844     {
 845         Object transferObject = transferable.getTransferData(this);
 846         if (transferObject == null) {
 847             throw new IllegalArgumentException
 848                 ("getTransferData() returned null");
 849         }
 850 
 851         if (transferObject instanceof Reader) {
 852             return (Reader)transferObject;
 853         } else if (transferObject instanceof String) {
 854             return new StringReader((String)transferObject);
 855         } else if (transferObject instanceof CharBuffer) {
 856             CharBuffer buffer = (CharBuffer)transferObject;
 857             int size = buffer.remaining();
 858             char[] chars = new char[size];
 859             buffer.get(chars, 0, size);
 860             return new CharArrayReader(chars);
 861         } else if (transferObject instanceof char[]) {
 862             return new CharArrayReader((char[])transferObject);
 863         }
 864 
 865         InputStream stream = null;
 866 
 867         if (transferObject instanceof InputStream) {
 868             stream = (InputStream)transferObject;
 869         } else if (transferObject instanceof ByteBuffer) {
 870             ByteBuffer buffer = (ByteBuffer)transferObject;
 871             int size = buffer.remaining();
 872             byte[] bytes = new byte[size];
 873             buffer.get(bytes, 0, size);
 874             stream = new ByteArrayInputStream(bytes);
 875         } else if (transferObject instanceof byte[]) {
 876             stream = new ByteArrayInputStream((byte[])transferObject);
 877         }
 878 
 879         if (stream == null) {
 880             throw new IllegalArgumentException("transfer data is not Reader, String, CharBuffer, char array, InputStream, ByteBuffer, or byte array");
 881         }
 882 
 883         String encoding = getParameter("charset");
 884         return (encoding == null)
 885             ? new InputStreamReader(stream)
 886             : new InputStreamReader(stream, encoding);
 887     }
 888 
 889     /**
 890      * Returns the MIME type string for this <code>DataFlavor</code>.
 891      * @return the MIME type string for this flavor
 892      */
 893     public String getMimeType() {
 894         return (mimeType != null) ? mimeType.toString() : null;
 895     }
 896 
 897     /**
 898      * Returns the <code>Class</code> which objects supporting this
 899      * <code>DataFlavor</code> will return when this <code>DataFlavor</code>
 900      * is requested.
 901      * @return the <code>Class</code> which objects supporting this
 902      * <code>DataFlavor</code> will return when this <code>DataFlavor</code>
 903      * is requested
 904      */
 905     public Class<?> getRepresentationClass() {
 906         return representationClass;
 907     }
 908 
 909     /**
 910      * Returns the human presentable name for the data format that this
 911      * <code>DataFlavor</code> represents.  This name would be localized
 912      * for different countries.
 913      * @return the human presentable name for the data format that this
 914      *    <code>DataFlavor</code> represents
 915      */
 916     public String getHumanPresentableName() {
 917         return humanPresentableName;
 918     }
 919 
 920     /**
 921      * Returns the primary MIME type for this <code>DataFlavor</code>.
 922      * @return the primary MIME type of this <code>DataFlavor</code>
 923      */
 924     public String getPrimaryType() {
 925         return (mimeType != null) ? mimeType.getPrimaryType() : null;
 926     }
 927 
 928     /**
 929      * Returns the sub MIME type of this <code>DataFlavor</code>.
 930      * @return the Sub MIME type of this <code>DataFlavor</code>
 931      */
 932     public String getSubType() {
 933         return (mimeType != null) ? mimeType.getSubType() : null;
 934     }
 935 
 936     /**
 937      * Returns the human presentable name for this <code>DataFlavor</code>
 938      * if <code>paramName</code> equals "humanPresentableName".  Otherwise
 939      * returns the MIME type value associated with <code>paramName</code>.
 940      *
 941      * @param paramName the parameter name requested
 942      * @return the value of the name parameter, or <code>null</code>
 943      *  if there is no associated value
 944      */
 945     public String getParameter(String paramName) {
 946         if (paramName.equals("humanPresentableName")) {
 947             return humanPresentableName;
 948         } else {
 949             return (mimeType != null)
 950                 ? mimeType.getParameter(paramName) : null;
 951         }
 952     }
 953 
 954     /**
 955      * Sets the human presentable name for the data format that this
 956      * <code>DataFlavor</code> represents. This name would be localized
 957      * for different countries.
 958      * @param humanPresentableName the new human presentable name
 959      */
 960     public void setHumanPresentableName(String humanPresentableName) {
 961         this.humanPresentableName = humanPresentableName;
 962     }
 963 
 964     /**
 965      * {@inheritDoc}
 966      * <p>
 967      * The equals comparison for the {@code DataFlavor} class is implemented
 968      * as follows: Two <code>DataFlavor</code>s are considered equal if and
 969      * only if their MIME primary type and subtype and representation class are
 970      * equal. Additionally, if the primary type is "text", the subtype denotes
 971      * a text flavor which supports the charset parameter, and the
 972      * representation class is not <code>java.io.Reader</code>,
 973      * <code>java.lang.String</code>, <code>java.nio.CharBuffer</code>, or
 974      * <code>[C</code>, the <code>charset</code> parameter must also be equal.
 975      * If a charset is not explicitly specified for one or both
 976      * <code>DataFlavor</code>s, the platform default encoding is assumed. See
 977      * <code>selectBestTextFlavor</code> for a list of text flavors which
 978      * support the charset parameter.
 979      *
 980      * @param o the <code>Object</code> to compare with <code>this</code>
 981      * @return <code>true</code> if <code>that</code> is equivalent to this
 982      *         <code>DataFlavor</code>; <code>false</code> otherwise
 983      * @see #selectBestTextFlavor
 984      */
 985     public boolean equals(Object o) {
 986         return ((o instanceof DataFlavor) && equals((DataFlavor)o));
 987     }
 988 
 989     /**
 990      * This method has the same behavior as {@link #equals(Object)}.
 991      * The only difference being that it takes a {@code DataFlavor} instance
 992      * as a parameter.
 993      *
 994      * @param that the <code>DataFlavor</code> to compare with
 995      *        <code>this</code>
 996      * @return <code>true</code> if <code>that</code> is equivalent to this
 997      *         <code>DataFlavor</code>; <code>false</code> otherwise
 998      * @see #selectBestTextFlavor
 999      */
1000     public boolean equals(DataFlavor that) {
1001         if (that == null) {
1002             return false;
1003         }
1004         if (this == that) {
1005             return true;
1006         }
1007 
1008         if (!Objects.equals(this.getRepresentationClass(), that.getRepresentationClass())) {
1009             return false;
1010         }
1011 
1012         if (mimeType == null) {
1013             if (that.mimeType != null) {
1014                 return false;
1015             }
1016         } else {
1017             if (!mimeType.match(that.mimeType)) {
1018                 return false;
1019             }
1020 
1021             if ("text".equals(getPrimaryType())) {
1022                 if (DataTransferer.doesSubtypeSupportCharset(this)
1023                         && representationClass != null
1024                         && !isStandardTextRepresentationClass()) {
1025                     String thisCharset =
1026                             DataTransferer.canonicalName(this.getParameter("charset"));
1027                     String thatCharset =
1028                             DataTransferer.canonicalName(that.getParameter("charset"));
1029                     if (!Objects.equals(thisCharset, thatCharset)) {
1030                         return false;
1031                     }
1032                 }
1033 
1034                 if ("html".equals(getSubType())) {
1035                     String thisDocument = this.getParameter("document");
1036                     String thatDocument = that.getParameter("document");
1037                     if (!Objects.equals(thisDocument, thatDocument)) {
1038                         return false;
1039                     }
1040                 }
1041             }
1042         }
1043 
1044         return true;
1045     }
1046 
1047     /**
1048      * Compares only the <code>mimeType</code> against the passed in
1049      * <code>String</code> and <code>representationClass</code> is
1050      * not considered in the comparison.
1051      *
1052      * If <code>representationClass</code> needs to be compared, then
1053      * <code>equals(new DataFlavor(s))</code> may be used.
1054      * @deprecated As inconsistent with <code>hashCode()</code> contract,
1055      *             use <code>isMimeTypeEqual(String)</code> instead.
1056      * @param s the {@code mimeType} to compare.
1057      * @return true if the String (MimeType) is equal; false otherwise or if
1058      *         {@code s} is {@code null}
1059      */
1060     @Deprecated
1061     public boolean equals(String s) {
1062         if (s == null || mimeType == null)
1063             return false;
1064         return isMimeTypeEqual(s);
1065     }
1066 
1067     /**
1068      * Returns hash code for this <code>DataFlavor</code>.
1069      * For two equal <code>DataFlavor</code>s, hash codes are equal.
1070      * For the <code>String</code>
1071      * that matches <code>DataFlavor.equals(String)</code>, it is not
1072      * guaranteed that <code>DataFlavor</code>'s hash code is equal
1073      * to the hash code of the <code>String</code>.
1074      *
1075      * @return a hash code for this <code>DataFlavor</code>
1076      */
1077     public int hashCode() {
1078         int total = 0;
1079 
1080         if (representationClass != null) {
1081             total += representationClass.hashCode();
1082         }
1083 
1084         if (mimeType != null) {
1085             String primaryType = mimeType.getPrimaryType();
1086             if (primaryType != null) {
1087                 total += primaryType.hashCode();
1088             }
1089 
1090             // Do not add subType.hashCode() to the total. equals uses
1091             // MimeType.match which reports a match if one or both of the
1092             // subTypes is '*', regardless of the other subType.
1093 
1094             if ("text".equals(primaryType)) {
1095                 if (DataTransferer.doesSubtypeSupportCharset(this)
1096                         && representationClass != null
1097                         && !isStandardTextRepresentationClass()) {
1098                     String charset = DataTransferer.canonicalName(getParameter("charset"));
1099                     if (charset != null) {
1100                         total += charset.hashCode();
1101                     }
1102                 }
1103 
1104                 if ("html".equals(getSubType())) {
1105                     String document = this.getParameter("document");
1106                     if (document != null) {
1107                         total += document.hashCode();
1108                     }
1109                 }
1110             }
1111         }
1112 
1113         return total;
1114     }
1115 
1116     /**
1117      * Identical to {@link #equals(DataFlavor)}.
1118      *
1119      * @param that the <code>DataFlavor</code> to compare with
1120      *        <code>this</code>
1121      * @return <code>true</code> if <code>that</code> is equivalent to this
1122      *         <code>DataFlavor</code>; <code>false</code> otherwise
1123      * @see #selectBestTextFlavor
1124      * @since 1.3
1125      */
1126     public boolean match(DataFlavor that) {
1127         return equals(that);
1128     }
1129 
1130     /**
1131      * Returns whether the string representation of the MIME type passed in
1132      * is equivalent to the MIME type of this <code>DataFlavor</code>.
1133      * Parameters are not included in the comparison.
1134      *
1135      * @param mimeType the string representation of the MIME type
1136      * @return true if the string representation of the MIME type passed in is
1137      *         equivalent to the MIME type of this <code>DataFlavor</code>;
1138      *         false otherwise
1139      * @throws NullPointerException if mimeType is <code>null</code>
1140      */
1141     public boolean isMimeTypeEqual(String mimeType) {
1142         // JCK Test DataFlavor0117: if 'mimeType' is null, throw NPE
1143         if (mimeType == null) {
1144             throw new NullPointerException("mimeType");
1145         }
1146         if (this.mimeType == null) {
1147             return false;
1148         }
1149         try {
1150             return this.mimeType.match(new MimeType(mimeType));
1151         } catch (MimeTypeParseException mtpe) {
1152             return false;
1153         }
1154     }
1155 
1156     /**
1157      * Compares the <code>mimeType</code> of two <code>DataFlavor</code>
1158      * objects. No parameters are considered.
1159      *
1160      * @param dataFlavor the <code>DataFlavor</code> to be compared
1161      * @return true if the <code>MimeType</code>s are equal,
1162      *  otherwise false
1163      */
1164 
1165     public final boolean isMimeTypeEqual(DataFlavor dataFlavor) {
1166         return isMimeTypeEqual(dataFlavor.mimeType);
1167     }
1168 
1169     /**
1170      * Compares the <code>mimeType</code> of two <code>DataFlavor</code>
1171      * objects.  No parameters are considered.
1172      *
1173      * @return true if the <code>MimeType</code>s are equal,
1174      *  otherwise false
1175      */
1176 
1177     private boolean isMimeTypeEqual(MimeType mtype) {
1178         if (this.mimeType == null) {
1179             return (mtype == null);
1180         }
1181         return mimeType.match(mtype);
1182     }
1183 
1184     /**
1185      * Checks if the representation class is one of the standard text
1186      * representation classes.
1187      *
1188      * @return true if the representation class is one of the standard text
1189      *              representation classes, otherwise false
1190      */
1191     private boolean isStandardTextRepresentationClass() {
1192         return isRepresentationClassReader()
1193                 || String.class.equals(representationClass)
1194                 || isRepresentationClassCharBuffer()
1195                 || char[].class.equals(representationClass);
1196     }
1197 
1198    /**
1199     * Does the <code>DataFlavor</code> represent a serialized object?
1200     */
1201 
1202     public boolean isMimeTypeSerializedObject() {
1203         return isMimeTypeEqual(javaSerializedObjectMimeType);
1204     }
1205 
1206     public final Class<?> getDefaultRepresentationClass() {
1207         return ioInputStreamClass;
1208     }
1209 
1210     public final String getDefaultRepresentationClassAsString() {
1211         return getDefaultRepresentationClass().getName();
1212     }
1213 
1214    /**
1215     * Does the <code>DataFlavor</code> represent a
1216     * <code>java.io.InputStream</code>?
1217     */
1218 
1219     public boolean isRepresentationClassInputStream() {
1220         return ioInputStreamClass.isAssignableFrom(representationClass);
1221     }
1222 
1223     /**
1224      * Returns whether the representation class for this
1225      * <code>DataFlavor</code> is <code>java.io.Reader</code> or a subclass
1226      * thereof.
1227      *
1228      * @since 1.4
1229      */
1230     public boolean isRepresentationClassReader() {
1231         return java.io.Reader.class.isAssignableFrom(representationClass);
1232     }
1233 
1234     /**
1235      * Returns whether the representation class for this
1236      * <code>DataFlavor</code> is <code>java.nio.CharBuffer</code> or a
1237      * subclass thereof.
1238      *
1239      * @since 1.4
1240      */
1241     public boolean isRepresentationClassCharBuffer() {
1242         return java.nio.CharBuffer.class.isAssignableFrom(representationClass);
1243     }
1244 
1245     /**
1246      * Returns whether the representation class for this
1247      * <code>DataFlavor</code> is <code>java.nio.ByteBuffer</code> or a
1248      * subclass thereof.
1249      *
1250      * @since 1.4
1251      */
1252     public boolean isRepresentationClassByteBuffer() {
1253         return java.nio.ByteBuffer.class.isAssignableFrom(representationClass);
1254     }
1255 
1256    /**
1257     * Returns true if the representation class can be serialized.
1258     * @return true if the representation class can be serialized
1259     */
1260 
1261     public boolean isRepresentationClassSerializable() {
1262         return java.io.Serializable.class.isAssignableFrom(representationClass);
1263     }
1264 
1265    /**
1266     * Returns true if the representation class is <code>Remote</code>.
1267     * @return true if the representation class is <code>Remote</code>
1268     */
1269 
1270     public boolean isRepresentationClassRemote() {
1271         return DataTransferer.isRemote(representationClass);
1272     }
1273 
1274    /**
1275     * Returns true if the <code>DataFlavor</code> specified represents
1276     * a serialized object.
1277     * @return true if the <code>DataFlavor</code> specified represents
1278     *   a Serialized Object
1279     */
1280 
1281     public boolean isFlavorSerializedObjectType() {
1282         return isRepresentationClassSerializable() && isMimeTypeEqual(javaSerializedObjectMimeType);
1283     }
1284 
1285     /**
1286      * Returns true if the <code>DataFlavor</code> specified represents
1287      * a remote object.
1288      * @return true if the <code>DataFlavor</code> specified represents
1289      *  a Remote Object
1290      */
1291 
1292     public boolean isFlavorRemoteObjectType() {
1293         return isRepresentationClassRemote()
1294             && isRepresentationClassSerializable()
1295             && isMimeTypeEqual(javaRemoteObjectMimeType);
1296     }
1297 
1298 
1299    /**
1300     * Returns true if the <code>DataFlavor</code> specified represents
1301     * a list of file objects.
1302     * @return true if the <code>DataFlavor</code> specified represents
1303     *   a List of File objects
1304     */
1305 
1306    public boolean isFlavorJavaFileListType() {
1307         if (mimeType == null || representationClass == null)
1308             return false;
1309         return java.util.List.class.isAssignableFrom(representationClass) &&
1310                mimeType.match(javaFileListFlavor.mimeType);
1311 
1312    }
1313 
1314     /**
1315      * Returns whether this <code>DataFlavor</code> is a valid text flavor for
1316      * this implementation of the Java platform. Only flavors equivalent to
1317      * <code>DataFlavor.stringFlavor</code> and <code>DataFlavor</code>s with
1318      * a primary MIME type of "text" can be valid text flavors.
1319      * <p>
1320      * If this flavor supports the charset parameter, it must be equivalent to
1321      * <code>DataFlavor.stringFlavor</code>, or its representation must be
1322      * <code>java.io.Reader</code>, <code>java.lang.String</code>,
1323      * <code>java.nio.CharBuffer</code>, <code>[C</code>,
1324      * <code>java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>, or
1325      * <code>[B</code>. If the representation is
1326      * <code>java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>, or
1327      * <code>[B</code>, then this flavor's <code>charset</code> parameter must
1328      * be supported by this implementation of the Java platform. If a charset
1329      * is not specified, then the platform default charset, which is always
1330      * supported, is assumed.
1331      * <p>
1332      * If this flavor does not support the charset parameter, its
1333      * representation must be <code>java.io.InputStream</code>,
1334      * <code>java.nio.ByteBuffer</code>, or <code>[B</code>.
1335      * <p>
1336      * See <code>selectBestTextFlavor</code> for a list of text flavors which
1337      * support the charset parameter.
1338      *
1339      * @return <code>true</code> if this <code>DataFlavor</code> is a valid
1340      *         text flavor as described above; <code>false</code> otherwise
1341      * @see #selectBestTextFlavor
1342      * @since 1.4
1343      */
1344     public boolean isFlavorTextType() {
1345         return (DataTransferer.isFlavorCharsetTextType(this) ||
1346                 DataTransferer.isFlavorNoncharsetTextType(this));
1347     }
1348 
1349    /**
1350     * Serializes this <code>DataFlavor</code>.
1351     */
1352 
1353    public synchronized void writeExternal(ObjectOutput os) throws IOException {
1354        if (mimeType != null) {
1355            mimeType.setParameter("humanPresentableName", humanPresentableName);
1356            os.writeObject(mimeType);
1357            mimeType.removeParameter("humanPresentableName");
1358        } else {
1359            os.writeObject(null);
1360        }
1361 
1362        os.writeObject(representationClass);
1363    }
1364 
1365    /**
1366     * Restores this <code>DataFlavor</code> from a Serialized state.
1367     */
1368 
1369    public synchronized void readExternal(ObjectInput is) throws IOException , ClassNotFoundException {
1370        String rcn = null;
1371         mimeType = (MimeType)is.readObject();
1372 
1373         if (mimeType != null) {
1374             humanPresentableName =
1375                 mimeType.getParameter("humanPresentableName");
1376             mimeType.removeParameter("humanPresentableName");
1377             rcn = mimeType.getParameter("class");
1378             if (rcn == null) {
1379                 throw new IOException("no class parameter specified in: " +
1380                                       mimeType);
1381             }
1382         }
1383 
1384         try {
1385             representationClass = (Class)is.readObject();
1386         } catch (OptionalDataException ode) {
1387             if (!ode.eof || ode.length != 0) {
1388                 throw ode;
1389             }
1390             // Ensure backward compatibility.
1391             // Old versions didn't write the representation class to the stream.
1392             if (rcn != null) {
1393                 representationClass =
1394                     DataFlavor.tryToLoadClass(rcn, getClass().getClassLoader());
1395             }
1396         }
1397    }
1398 
1399    /**
1400     * Returns a clone of this <code>DataFlavor</code>.
1401     * @return a clone of this <code>DataFlavor</code>
1402     */
1403 
1404     public Object clone() throws CloneNotSupportedException {
1405         Object newObj = super.clone();
1406         if (mimeType != null) {
1407             ((DataFlavor)newObj).mimeType = (MimeType)mimeType.clone();
1408         }
1409         return newObj;
1410     } // clone()
1411 
1412    /**
1413     * Called on <code>DataFlavor</code> for every MIME Type parameter
1414     * to allow <code>DataFlavor</code> subclasses to handle special
1415     * parameters like the text/plain <code>charset</code>
1416     * parameters, whose values are case insensitive.  (MIME type parameter
1417     * values are supposed to be case sensitive.
1418     * <p>
1419     * This method is called for each parameter name/value pair and should
1420     * return the normalized representation of the <code>parameterValue</code>.
1421     *
1422     * This method is never invoked by this implementation from 1.1 onwards.
1423     *
1424     * @deprecated
1425     */
1426     @Deprecated
1427     protected String normalizeMimeTypeParameter(String parameterName, String parameterValue) {
1428         return parameterValue;
1429     }
1430 
1431    /**
1432     * Called for each MIME type string to give <code>DataFlavor</code> subtypes
1433     * the opportunity to change how the normalization of MIME types is
1434     * accomplished.  One possible use would be to add default
1435     * parameter/value pairs in cases where none are present in the MIME
1436     * type string passed in.
1437     *
1438     * This method is never invoked by this implementation from 1.1 onwards.
1439     *
1440     * @deprecated
1441     */
1442     @Deprecated
1443     protected String normalizeMimeType(String mimeType) {
1444         return mimeType;
1445     }
1446 
1447     /*
1448      * fields
1449      */
1450 
1451     /* placeholder for caching any platform-specific data for flavor */
1452 
1453     transient int       atom;
1454 
1455     /* Mime Type of DataFlavor */
1456 
1457     MimeType            mimeType;
1458 
1459     private String      humanPresentableName;
1460 
1461     /** Java class of objects this DataFlavor represents **/
1462 
1463     private Class<?>       representationClass;
1464 
1465 } // class DataFlavor