1 /* DataFlavor.java -- A type of data to transfer via the clipboard.
2 Copyright (C) 1999, 2001 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package java.awt.datatransfer;
41 import java.io.ByteArrayInputStream;
42 import java.io.InputStream;
43 import java.io.InputStreamReader;
44 import java.io.IOException;
45 import java.io.ObjectOutput;
46 import java.io.ObjectInput;
47 import java.io.Reader;
48 import java.io.StringReader;
49 import java.io.UnsupportedEncodingException;
52 * This class represents a particular data format used for transferring
53 * data via the clipboard.
55 * @author Aaron M. Renn (arenn@urbanophile.com)
57 public class DataFlavor implements java.io.Externalizable, Cloneable
60 // FIXME: Serialization: Need to write methods for.
67 * This is the data flavor used for tranferring plain text. The MIME
68 * type is "text/plain; charset=unicode". The representation class
69 * is <code>java.io.InputStream</code>.
71 * @deprecated The charset unicode is platform specific and InputStream
72 * deals with bytes not chars. Use <code>getRederForText()</code>.
74 public static final DataFlavor plainTextFlavor;
77 * This is the data flavor used for transferring Java strings. The
78 * MIME type is "application/x-java-serialized-object" and the
79 * representation class is <code>java.lang.String</code>.
81 public static final DataFlavor stringFlavor;
84 * This is a data flavor used for transferring lists of files. The
85 * representation type is a <code>java.util.List</code>, with each element of
86 * the list being a <code>java.io.File</code>.
88 public static final DataFlavor javaFileListFlavor;
91 * This is the MIME type used for transferring a serialized object.
92 * The representation class is the type of object be deserialized.
94 public static final String javaSerializedObjectMimeType =
95 "application/x-java-serialized-object";
98 * This is the MIME type used to transfer a Java object reference within
99 * the same JVM. The representation class is the class of the object
102 public static final String javaJVMLocalObjectMimeType =
103 "application/x-java-jvm-local-object";
106 * This is the MIME type used to transfer a link to a remote object.
107 * The representation class is the type of object being linked to.
109 public static final String javaRemoteObjectMimeType =
110 "application/x-java-remote-object";
115 = new DataFlavor(java.io.InputStream.class,
116 "text/plain; charset=unicode",
117 "plain unicode text");
120 = new DataFlavor(java.lang.String.class,
121 "Java Unicode String");
124 = new DataFlavor(java.util.List.class,
127 // javaFileListFlavor.mimeType = "application/x-java-file-list";
130 /*************************************************************************/
136 // The MIME type for this flavor
137 private final String mimeType;
139 // The representation class for this flavor
140 private final Class representationClass;
142 // The human readable name of this flavor
143 private String humanPresentableName;
145 /*************************************************************************/
152 * This method attempts to load the named class. The following class
153 * loaders are searched in order: the bootstrap class loader, the
154 * system class loader, the context class loader (if it exists), and
155 * the specified fallback class loader.
157 * @param className The name of the class to load.
158 * @param classLoader The class loader to use if all others fail, which
159 * may be <code>null</code>.
161 * @exception ClassNotFoundException If the class cannot be loaded.
163 protected static final Class
164 tryToLoadClass(String className, ClassLoader classLoader)
165 throws ClassNotFoundException
169 return(Class.forName(className));
171 catch(Exception e) { ; }
172 // Commented out for Java 1.1
176 return(className.getClass().getClassLoader().findClass(className));
178 catch(Exception e) { ; }
182 return(ClassLoader.getSystemClassLoader().findClass(className));
184 catch(Exception e) { ; }
187 // FIXME: What is the context class loader?
192 catch(Exception e) { ; }
195 if (classLoader != null)
196 return(classLoader.loadClass(className));
198 throw new ClassNotFoundException(className);
201 /*************************************************************************/
208 * Empty public constructor needed for externalization.
209 * Should not be used for normal instantiation.
215 representationClass = null;
216 humanPresentableName = null;
219 /*************************************************************************/
222 * Private constructor.
225 DataFlavor(Class representationClass,
227 String humanPresentableName)
229 this.representationClass = representationClass;
230 this.mimeType = mimeType;
231 if (humanPresentableName != null)
232 this.humanPresentableName = humanPresentableName;
234 this.humanPresentableName = mimeType;
237 /*************************************************************************/
240 * Initializes a new instance of <code>DataFlavor</code>. The class
241 * and human readable name are specified, the MIME type will be
242 * "application/x-java-serialized-object". If the human readable name
243 * is not specified (<code>null</code>) then the human readable name
244 * will be the same as the MIME type.
246 * @param representationClass The representation class for this object.
247 * @param humanPresentableName The display name of the object.
250 DataFlavor(Class representationClass, String humanPresentableName)
252 this(representationClass,
253 "application/x-java-serialized-object"
255 + representationClass.getName(),
256 humanPresentableName);
259 /*************************************************************************/
262 * Initializes a new instance of <code>DataFlavor</code> with the
263 * specified MIME type and description. If the MIME type has a
264 * "class=<rep class>" parameter then the representation class will
265 * be the class name specified. Otherwise the class defaults to
266 * <code>java.io.InputStream</code>. If the human readable name
267 * is not specified (<code>null</code>) then the human readable name
268 * will be the same as the MIME type.
270 * @param mimeType The MIME type for this flavor.
271 * @param humanPresentableName The display name of this flavor.
272 * @param classLoader The class loader for finding classes if the default
273 * class loaders do not work.
275 * @exception IllegalArgumentException If the representation class
276 * specified cannot be loaded.
279 DataFlavor(String mimeType, String humanPresentableName,
280 ClassLoader classLoader) throws ClassNotFoundException
282 this(getRepresentationClassFromMime(mimeType, classLoader),
283 mimeType, humanPresentableName);
287 getRepresentationClassFromMime(String mimeString, ClassLoader classLoader)
289 String classname = getParameter("class", mimeString);
290 if (classname != null)
294 return tryToLoadClass(classname, classLoader);
298 throw new IllegalArgumentException("classname: " + e.getMessage());
303 return java.io.InputStream.class;
307 /*************************************************************************/
310 * Initializes a new instance of <code>DataFlavor</code> with the
311 * specified MIME type and description. If the MIME type has a
312 * "class=<rep class>" parameter then the representation class will
313 * be the class name specified. Otherwise the class defaults to
314 * <code>java.io.InputStream</code>. If the human readable name
315 * is not specified (<code>null</code>) then the human readable name
316 * will be the same as the MIME type. This is the same as calling
317 * <code>new DataFlavor(mimeType, humanPresentableName, null)</code>.
319 * @param mimeType The MIME type for this flavor.
320 * @param humanPresentableName The display name of this flavor.
321 * @param classLoader The class loader for finding classes.
323 * @exception IllegalArgumentException If the representation class
324 * specified cannot be loaded.
327 DataFlavor(String mimeType, String humanPresentableName)
328 throws ClassNotFoundException
330 this(mimeType, humanPresentableName, null);
333 /*************************************************************************/
336 * Initializes a new instance of <code>DataFlavor</code> with the specified
337 * MIME type. This type can have a "class=" parameter to specify the
338 * representation class, and then the class must exist or an exception will
339 * be thrown. If there is no "class=" parameter then the representation class
340 * will be <code>java.io.InputStream</code>. This is the same as calling
341 * <code>new DataFlavor(mimeType, null)</code>.
343 * @param mimeType The MIME type for this flavor.
345 * @exception IllegalArgumentException If a class is not specified in
347 * @exception ClassNotFoundException If the class cannot be loaded.
350 DataFlavor(String mimeType) throws ClassNotFoundException
352 this(mimeType, null);
355 /*************************************************************************/
358 * Returns the MIME type of this flavor.
360 * @return The MIME type for this flavor.
368 /*************************************************************************/
371 * Returns the representation class for this flavor.
373 * @return The representation class for this flavor.
376 getRepresentationClass()
378 return(representationClass);
381 /*************************************************************************/
384 * Returns the human presentable name for this flavor.
386 * @return The human presentable name for this flavor.
389 getHumanPresentableName()
391 return(humanPresentableName);
394 /*************************************************************************/
397 * Returns the primary MIME type for this flavor.
399 * @return The primary MIME type for this flavor.
404 int idx = mimeType.indexOf("/");
408 return(mimeType.substring(0, idx));
411 /*************************************************************************/
414 * Returns the MIME subtype for this flavor.
416 * @return The MIME subtype for this flavor.
421 int idx = mimeType.indexOf("/");
425 String subtype = mimeType.substring(idx + 1);
427 idx = subtype.indexOf(" ");
431 return(subtype.substring(0, idx));
434 /*************************************************************************/
437 * Returns the value of the named MIME type parameter, or <code>null</code>
438 * if the parameter does not exist. Given the parameter name and the mime
441 * @param paramName The name of the parameter.
442 * @param mimeString The mime string from where the name should be found.
444 * @return The value of the parameter or null.
446 private static String
447 getParameter(String paramName, String mimeString)
449 int idx = mimeString.indexOf(paramName + "=");
453 String value = mimeString.substring(idx + paramName.length() + 2);
455 idx = value.indexOf(" ");
459 return(value.substring(0, idx));
462 /*************************************************************************/
464 * Returns the value of the named MIME type parameter, or <code>null</code>
465 * if the parameter does not exist.
467 * @param paramName The name of the paramter.
469 * @return The value of the parameter.
472 getParameter(String paramName)
474 return getParameter(paramName, mimeType);
477 /*************************************************************************/
480 * Sets the human presentable name to the specified value.
482 * @param humanPresentableName The new display name.
485 setHumanPresentableName(String humanPresentableName)
487 this.humanPresentableName = humanPresentableName;
490 /*************************************************************************/
493 * Tests the MIME type of this object for equality against the specified
496 * @param mimeType The MIME type to test against.
498 * @return <code>true</code> if the MIME type is equal to this object's
499 * MIME type, <code>false</code> otherwise.
502 isMimeTypeEqual(String mimeType)
504 // FIXME: Need to handle default attributes and parameters
506 return(this.mimeType.equals(mimeType));
509 /*************************************************************************/
512 * Tests the MIME type of this object for equality against the specified
513 * data flavor's MIME type
515 * @param flavor The flavor to test against.
517 * @return <code>true</code> if the flavor's MIME type is equal to this
518 * object's MIME type, <code>false</code> otherwise.
521 isMimeTypeEqual(DataFlavor flavor)
523 return(isMimeTypeEqual(flavor.getMimeType()));
526 /*************************************************************************/
529 * Tests whether or not this flavor represents a serialized object.
531 * @return <code>true</code> if this flavor represents a serialized
532 * object, <code>false</code> otherwise.
535 isMimeTypeSerializedObject()
537 return(mimeType.startsWith(javaSerializedObjectMimeType));
540 /*************************************************************************/
543 * Tests whether or not this flavor has a representation class of
544 * <code>java.io.InputStream</code>.
546 * @param <code>true</code> if the representation class of this flavor
547 * is <code>java.io.InputStream</code>, <code>false</code> otherwise.
550 isRepresentationClassInputStream()
552 return(representationClass.getName().equals("java.io.InputStream"));
555 /*************************************************************************/
558 * Tests whether the representation class for this flavor is
561 * @param <code>true</code> if the representation class is serializable,
562 * <code>false</code> otherwise.
565 isRepresentationClassSerializable()
567 Class[] interfaces = representationClass.getInterfaces();
570 while (i < interfaces.length)
572 if (interfaces[i].getName().equals("java.io.Serializable"))
580 /*************************************************************************/
583 * Tests whether the representation class for his flavor is remote.
585 * @return <code>true</code> if the representation class is remote,
586 * <code>false</code> otherwise.
589 isRepresentationClassRemote()
592 throw new RuntimeException("Not implemented");
595 /*************************************************************************/
598 * Tests whether or not this flavor represents a serialized object.
600 * @return <code>true</code> if this flavor represents a serialized
601 * object, <code>false</code> otherwise.
604 isFlavorSerializedObjectType()
606 // FIXME: What is the diff between this and isMimeTypeSerializedObject?
607 return(mimeType.startsWith(javaSerializedObjectMimeType));
610 /*************************************************************************/
613 * Tests whether or not this flavor represents a remote object.
615 * @return <code>true</code> if this flavor represents a remote object,
616 * <code>false</code> otherwise.
619 isFlavorRemoteObjectType()
621 return(mimeType.startsWith(javaRemoteObjectMimeType));
624 /*************************************************************************/
627 * Tests whether or not this flavor represents a list of files.
629 * @return <code>true</code> if this flavor represents a list of files,
630 * <code>false</code> otherwise.
633 isFlavorJavaFileListType()
635 if (this.mimeType.equals(javaFileListFlavor.mimeType) &&
636 this.representationClass.equals(javaFileListFlavor.representationClass))
642 /*************************************************************************/
645 * Returns a copy of this object.
647 * @return A copy of this object.
654 return(super.clone());
662 /*************************************************************************/
665 * This method test the specified <code>DataFlavor</code> for equality
666 * against this object. This will be true if the MIME type and
667 * representation type are the equal.
669 * @param flavor The <code>DataFlavor</code> to test against.
671 * @return <code>true</code> if the flavor is equal to this object,
672 * <code>false</code> otherwise.
675 equals(DataFlavor flavor)
680 if (!this.mimeType.toLowerCase().equals(flavor.mimeType.toLowerCase()))
683 if (!this.representationClass.equals(flavor.representationClass))
689 /*************************************************************************/
692 * This method test the specified <code>Object</code> for equality
693 * against this object. This will be true if the following conditions
697 * <li>The object is not <code>null</code>.
698 * <li>The object is an instance of <code>DataFlavor</code>.
699 * <li>The object's MIME type and representation class are equal to
703 * @param obj The <code>Object</code> to test against.
705 * @return <code>true</code> if the flavor is equal to this object,
706 * <code>false</code> otherwise.
714 if (!(obj instanceof DataFlavor))
717 return(equals((DataFlavor)obj));
720 /*************************************************************************/
723 * Tests whether or not the specified string is equal to the MIME type
726 * @param str The string to test against.
728 * @return <code>true</code> if the string is equal to this object's MIME
729 * type, <code>false</code> otherwise.
731 * @deprecated Not compatible with <code>hashCode()</code>.
732 * Use <code>isMimeTypeEqual()</code>
737 return(isMimeTypeEqual(str));
740 /*************************************************************************/
743 * Returns the hash code for this data flavor.
744 * The hash code is based on the (lower case) mime type and the
745 * representation class.
750 return(mimeType.toLowerCase().hashCode()^representationClass.hashCode());
753 /*************************************************************************/
756 * Returns <code>true</code> when the given <code>DataFlavor</code>
760 match(DataFlavor dataFlavor)
762 // XXX - How is this different from equals?
763 return(equals(dataFlavor));
766 /*************************************************************************/
769 * This method exists for backward compatibility. It simply returns
770 * the same name/value pair passed in.
772 * @param name The parameter name.
773 * @param value The parameter value.
775 * @return The name/value pair.
780 normalizeMimeTypeParameter(String name, String value)
782 return(name + "=" + value);
785 /*************************************************************************/
788 * This method exists for backward compatibility. It simply returns
789 * the MIME type string unchanged.
791 * @param type The MIME type.
793 * @return The MIME type.
798 normalizeMimeType(String type)
803 /*************************************************************************/
806 * Serialize this class.
808 * @param stream The <code>ObjectOutput</code> stream to serialize to.
811 writeExternal(ObjectOutput stream) throws IOException
813 // FIXME: Implement me
816 /*************************************************************************/
819 * De-serialize this class.
821 * @param stream The <code>ObjectInput</code> stream to deserialize from.
824 readExternal(ObjectInput stream) throws IOException, ClassNotFoundException
826 // FIXME: Implement me
829 /*************************************************************************/
832 * Returns a string representation of this DataFlavor. Including the
833 * representation class name, MIME type and human presentable name.
838 return("DataFlavor[representationClass="
839 + representationClass.getName()
842 + "humanPresentableName="
843 + humanPresentableName);
846 /*************************************************************************/
849 * XXX - Currently returns <code>plainTextFlavor</code>.
851 public static final DataFlavor
852 getTextPlainUnicodeFlavor()
854 return(plainTextFlavor);
857 /*************************************************************************/
860 * XXX - Currently returns <code>java.io.InputStream</code>.
864 public static final Class
865 getDefaultRepresentationClass()
867 return(java.io.InputStream.class);
869 /*************************************************************************/
872 * XXX - Currently returns <code>java.io.InputStream</code>.
874 public static final String
875 getDefaultRepresentationClassAsString()
877 return(getDefaultRepresentationClass().getName());
880 /*************************************************************************/
883 * Selects the best supported text flavor on this implementation.
884 * Returns <code>null</code> when none of the given flavors is liked.
886 * The <code>DataFlavor</code> returned the first data flavor in the
887 * array that has either a representation class which is (a subclass of)
888 * <code>Reader</code> or <code>String</code>, or has a representation
889 * class which is (a subclass of) <code>InputStream</code> and has a
890 * primary MIME type of "text" and has an supported encoding.
892 public static final DataFlavor
893 selectBestTextFlavor(DataFlavor[] availableFlavors)
895 for(int i=0; i<availableFlavors.length; i++)
897 DataFlavor df = availableFlavors[i];
898 Class c = df.representationClass;
900 // A Reader or String is good.
901 if ((Reader.class.isAssignableFrom(c))
902 || (String.class.isAssignableFrom(c)))
907 // A InputStream is good if the mime primary type is "text"
908 if ((InputStream.class.isAssignableFrom(c))
909 && ("text".equals(df.getPrimaryType())))
911 String encoding = availableFlavors[i].getParameter("charset");
912 if (encoding == null)
913 encoding = "us-ascii";
917 // Try to construct a dummy reader with the found encoding
918 r = new InputStreamReader
919 (new ByteArrayInputStream(new byte[0]), encoding);
921 catch(UnsupportedEncodingException uee) { /* ignore */ }
931 /*************************************************************************/
934 * Creates a <code>Reader</code> for a given <code>Transferable</code>.
936 * If the representation class is a (subclass of) <code>Reader</code>
937 * then an instance of the representation class is returned. If the
938 * representatation class is a <code>String</code> then a
939 * <code>StringReader</code> is returned. And if the representation class
940 * is a (subclass of) <code>InputStream</code> and the primary MIME type
941 * is "text" then a <code>InputStreamReader</code> for the correct charset
942 * encoding is returned.
944 * @param transferable The <code>Transferable</code> for which a text
945 * <code>Reader</code> is requested.
946 * @exception UnsupportedFlavorException when the transferable doesn't
947 * support this <code>DataFlavor</code>. Or if the representable class
948 * isn't a (subclass of) <code>Reader</code>, <code>String</code>,
949 * <code>InputStream</code> and/or the primary MIME type isn't "text".
950 * @exception IOException when any IOException occurs.
951 * @exception UnsupportedEncodingException if the "charset" isn't supported
955 getReaderForText(Transferable transferable) throws UnsupportedFlavorException,
957 UnsupportedEncodingException
959 if (!transferable.isDataFlavorSupported(this))
960 throw new UnsupportedFlavorException(this);
962 if (Reader.class.isAssignableFrom(representationClass))
963 return((Reader)transferable.getTransferData(this));
965 if (String.class.isAssignableFrom(representationClass))
966 return(new StringReader((String)transferable.getTransferData(this)));
968 if (InputStream.class.isAssignableFrom(representationClass)
969 && "text".equals(getPrimaryType()))
971 InputStream in = (InputStream)transferable.getTransferData(this);
972 String encoding = getParameter("charset");
973 if (encoding == null)
974 encoding = "us-ascii";
975 return(new InputStreamReader(in, encoding));
978 throw new UnsupportedFlavorException(this);
981 } // class DataFlavor