History

My first initial commit with all of mine experimental changes.

Dmitry Kabak (userdima committed 13 years ago

Commit d37b88d1 parent 3f5b46618352 files · +2598093 −-8690Browse files

Showing the changes to java/pkg/sun/awt/datatransfer/DataTransferer.java (1 of 18352 files). Show all

Unified · Split

java/pkg/sun/awt/datatransfer/DataTransferer.java+3090−0
@@ -0,0 +1,3090 @@
1/*
2 * Copyright (c) 2000, 2008, 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
26package sun.awt.datatransfer;
27
28import java.awt.AWTError;
29import java.awt.EventQueue;
30import java.awt.Image;
31import java.awt.Graphics;
32
33import java.awt.datatransfer.DataFlavor;
34import java.awt.datatransfer.FlavorMap;
35import java.awt.datatransfer.FlavorTable;
36import java.awt.datatransfer.Transferable;
37import java.awt.datatransfer.UnsupportedFlavorException;
38
39import java.io.BufferedReader;
40import java.io.ByteArrayInputStream;
41import java.io.ByteArrayOutputStream;
42import java.io.File;
43import java.io.InputStream;
44import java.io.InputStreamReader;
45import java.io.IOException;
46import java.io.ObjectInputStream;
47import java.io.ObjectOutputStream;
48import java.io.Reader;
49import java.io.SequenceInputStream;
50import java.io.StringReader;
51
52import java.net.URI;
53import java.net.URISyntaxException;
54
55import java.nio.ByteBuffer;
56import java.nio.CharBuffer;
57import java.nio.charset.Charset;
58import java.nio.charset.CharsetEncoder;
59import java.nio.charset.IllegalCharsetNameException;
60import java.nio.charset.UnsupportedCharsetException;
61
62import java.lang.reflect.Constructor;
63import java.lang.reflect.InvocationTargetException;
64import java.lang.reflect.Method;
65import java.lang.reflect.Modifier;
66
67import java.security.AccessController;
68import java.security.PrivilegedAction;
69import java.security.PrivilegedActionException;
70import java.security.PrivilegedExceptionAction;
71import java.security.ProtectionDomain;
72
73import java.util.ArrayList;
74import java.util.Arrays;
75import java.util.Collections;
76import java.util.Comparator;
77import java.util.HashMap;
78import java.util.HashSet;
79import java.util.Iterator;
80import java.util.List;
81import java.util.Map;
82import java.util.SortedMap;
83import java.util.SortedSet;
84import java.util.Set;
85import java.util.Stack;
86import java.util.TreeMap;
87import java.util.TreeSet;
88
89import sun.util.logging.PlatformLogger;
90
91import sun.awt.AppContext;
92import sun.awt.SunToolkit;
93
94import java.awt.image.BufferedImage;
95import java.awt.image.ImageObserver;
96import java.awt.image.RenderedImage;
97import java.awt.image.WritableRaster;
98import java.awt.image.ColorModel;
99
100import javax.imageio.ImageIO;
101import javax.imageio.ImageReader;
102import javax.imageio.ImageReadParam;
103import javax.imageio.ImageWriter;
104import javax.imageio.ImageTypeSpecifier;
105
106import javax.imageio.spi.ImageWriterSpi;
107
108import javax.imageio.stream.ImageInputStream;
109import javax.imageio.stream.ImageOutputStream;
110
111import sun.awt.image.ImageRepresentation;
112import sun.awt.image.ToolkitImage;
113
114import java.io.FilePermission;
115
116
117/**
118 * Provides a set of functions to be shared among the DataFlavor class and
119 * platform-specific data transfer implementations.
120 *
121 * The concept of "flavors" and "natives" is extended to include "formats",
122 * which are the numeric values Win32 and X11 use to express particular data
123 * types. Like FlavorMap, which provides getNativesForFlavors(DataFlavor[]) and
124 * getFlavorsForNatives(String[]) functions, DataTransferer provides a set
125 * of getFormatsFor(Transferable|Flavor|Flavors) and
126 * getFlavorsFor(Format|Formats) functions.
127 *
128 * Also provided are functions for translating a Transferable into a byte
129 * array, given a source DataFlavor and a target format, and for translating
130 * a byte array or InputStream into an Object, given a source format and
131 * a target DataFlavor.
132 *
133 * @author David Mendenhall
134 * @author Danila Sinopalnikov
135 *
136 * @since 1.3.1
137 */
138public abstract class DataTransferer {
139
140 /**
141 * Cached value of Class.forName("[C");
142 */
143 public static final Class charArrayClass;
144
145 /**
146 * Cached value of Class.forName("[B");
147 */
148 public static final Class byteArrayClass;
149
150 /**
151 * The <code>DataFlavor</code> representing plain text with Unicode
152 * encoding, where:
153 * <pre>
154 * representationClass = java.lang.String
155 * mimeType = "text/plain; charset=Unicode"
156 * </pre>
157 */
158 public static final DataFlavor plainTextStringFlavor;
159
160 /**
161 * The <code>DataFlavor</code> representing a Java text encoding String
162 * encoded in UTF-8, where
163 * <pre>
164 * representationClass = [B
165 * mimeType = "application/x-java-text-encoding"
166 * </pre>
167 */
168 public static final DataFlavor javaTextEncodingFlavor;
169
170 /**
171 * Lazy initialization of Standard Encodings.
172 */
173 private static class StandardEncodingsHolder {
174 private static final SortedSet standardEncodings = load();
175
176 private static SortedSet load() {
177 final Comparator comparator =
178 new CharsetComparator(IndexedComparator.SELECT_WORST);
179 final SortedSet tempSet = new TreeSet(comparator);
180 tempSet.add("US-ASCII");
181 tempSet.add("ISO-8859-1");
182 tempSet.add("UTF-8");
183 tempSet.add("UTF-16BE");
184 tempSet.add("UTF-16LE");
185 tempSet.add("UTF-16");
186 tempSet.add(getDefaultTextCharset());
187 return Collections.unmodifiableSortedSet(tempSet);
188 }
189 }
190
191 /**
192 * Tracks whether a particular text/* MIME type supports the charset
193 * parameter. The Map is initialized with all of the standard MIME types
194 * listed in the DataFlavor.selectBestTextFlavor method comment. Additional
195 * entries may be added during the life of the JRE for text/<other> types.
196 */
197 private static final Map textMIMESubtypeCharsetSupport;
198
199 /**
200 * Cache of the platform default encoding as specified in the
201 * "file.encoding" system property.
202 */
203 private static String defaultEncoding;
204
205 /**
206 * A collection of all natives listed in flavormap.properties with
207 * a primary MIME type of "text".
208 */
209 private static final Set textNatives =
210 Collections.synchronizedSet(new HashSet());
211
212 /**
213 * The native encodings/charsets for the Set of textNatives.
214 */
215 private static final Map nativeCharsets =
216 Collections.synchronizedMap(new HashMap());
217
218 /**
219 * The end-of-line markers for the Set of textNatives.
220 */
221 private static final Map nativeEOLNs =
222 Collections.synchronizedMap(new HashMap());
223
224 /**
225 * The number of terminating NUL bytes for the Set of textNatives.
226 */
227 private static final Map nativeTerminators =
228 Collections.synchronizedMap(new HashMap());
229
230 /**
231 * The key used to store pending data conversion requests for an AppContext.
232 */
233 private static final String DATA_CONVERTER_KEY = "DATA_CONVERTER_KEY";
234
235 /**
236 * The singleton DataTransferer instance. It is created during MToolkit
237 * or WToolkit initialization.
238 */
239 private static DataTransferer transferer;
240
241 private static final PlatformLogger dtLog = PlatformLogger.getLogger("sun.awt.datatransfer.DataTransfer");
242
243 static {
244 Class tCharArrayClass = null, tByteArrayClass = null;
245 try {
246 tCharArrayClass = Class.forName("[C");
247 tByteArrayClass = Class.forName("[B");
248 } catch (ClassNotFoundException cannotHappen) {
249 }
250 charArrayClass = tCharArrayClass;
251 byteArrayClass = tByteArrayClass;
252
253 DataFlavor tPlainTextStringFlavor = null;
254 try {
255 tPlainTextStringFlavor = new DataFlavor
256 ("text/plain;charset=Unicode;class=java.lang.String");
257 } catch (ClassNotFoundException cannotHappen) {
258 }
259 plainTextStringFlavor = tPlainTextStringFlavor;
260
261 DataFlavor tJavaTextEncodingFlavor = null;
262 try {
263 tJavaTextEncodingFlavor = new DataFlavor
264 ("application/x-java-text-encoding;class=\"[B\"");
265 } catch (ClassNotFoundException cannotHappen) {
266 }
267 javaTextEncodingFlavor = tJavaTextEncodingFlavor;
268
269 Map tempMap = new HashMap(17);
270 tempMap.put("sgml", Boolean.TRUE);
271 tempMap.put("xml", Boolean.TRUE);
272 tempMap.put("html", Boolean.TRUE);
273 tempMap.put("enriched", Boolean.TRUE);
274 tempMap.put("richtext", Boolean.TRUE);
275 tempMap.put("uri-list", Boolean.TRUE);
276 tempMap.put("directory", Boolean.TRUE);
277 tempMap.put("css", Boolean.TRUE);
278 tempMap.put("calendar", Boolean.TRUE);
279 tempMap.put("plain", Boolean.TRUE);
280 tempMap.put("rtf", Boolean.FALSE);
281 tempMap.put("tab-separated-values", Boolean.FALSE);
282 tempMap.put("t140", Boolean.FALSE);
283 tempMap.put("rfc822-headers", Boolean.FALSE);
284 tempMap.put("parityfec", Boolean.FALSE);
285 textMIMESubtypeCharsetSupport = Collections.synchronizedMap(tempMap);
286 }
287
288 /**
289 * The accessor method for the singleton DataTransferer instance. Note
290 * that in a headless environment, there may be no DataTransferer instance;
291 * instead, null will be returned.
292 */
293 public static DataTransferer getInstance() {
294 synchronized (DataTransferer.class) {
295 if (transferer == null) {
296 final String name = SunToolkit.getDataTransfererClassName();
297 if (name != null) {
298 PrivilegedAction<DataTransferer> action = new PrivilegedAction<DataTransferer>()
299 {
300 public DataTransferer run() {
301 Class cls = null;
302 Method method = null;
303 DataTransferer ret = null;
304
305 try {
306 cls = Class.forName(name);
307 } catch (ClassNotFoundException e) {
308 ClassLoader cl = ClassLoader.
309 getSystemClassLoader();
310 if (cl != null) {
311 try {
312 cls = cl.loadClass(name);
313 } catch (ClassNotFoundException ee) {
314 ee.printStackTrace();
315 throw new AWTError("DataTransferer not found: " + name);
316 }
317 }
318 }
319 if (cls != null) {
320 try {
321 method = cls.getDeclaredMethod("getInstanceImpl");
322 method.setAccessible(true);
323 } catch (NoSuchMethodException e) {
324 e.printStackTrace();
325 throw new AWTError("Cannot instantiate DataTransferer: " + name);
326 } catch (SecurityException e) {
327 e.printStackTrace();
328 throw new AWTError("Access is denied for DataTransferer: " + name);
329 }
330 }
331 if (method != null) {
332 try {
333 ret = (DataTransferer) method.invoke(null);
334 } catch (InvocationTargetException e) {
335 e.printStackTrace();
336 throw new AWTError("Cannot instantiate DataTransferer: " + name);
337 } catch (IllegalAccessException e) {
338 e.printStackTrace();
339 throw new AWTError("Cannot access DataTransferer: " + name);
340 }
341 }
342 return ret;
343 }
344 };
345 transferer = AccessController.doPrivileged(action);
346 }
347 }
348 }
349 return transferer;
350 }
351
352 /**
353 * Converts an arbitrary text encoding to its canonical name.
354 */
355 public static String canonicalName(String encoding) {
356 if (encoding == null) {
357 return null;
358 }
359 try {
360 return Charset.forName(encoding).name();
361 } catch (IllegalCharsetNameException icne) {
362 return encoding;
363 } catch (UnsupportedCharsetException uce) {
364 return encoding;
365 }
366 }
367
368 /**
369 * If the specified flavor is a text flavor which supports the "charset"
370 * parameter, then this method returns that parameter, or the default
371 * charset if no such parameter was specified at construction. For non-
372 * text DataFlavors, and for non-charset text flavors, this method returns
373 * null.
374 */
375 public static String getTextCharset(DataFlavor flavor) {
376 if (!isFlavorCharsetTextType(flavor)) {
377 return null;
378 }
379
380 String encoding = flavor.getParameter("charset");
381
382 return (encoding != null) ? encoding : getDefaultTextCharset();
383 }
384
385 /**
386 * Returns the platform's default character encoding.
387 */
388 public static String getDefaultTextCharset() {
389 if (defaultEncoding != null) {
390 return defaultEncoding;
391 }
392 return defaultEncoding = Charset.defaultCharset().name();
393 }
394
395 /**
396 * Tests only whether the flavor's MIME type supports the charset
397 * parameter. Must only be called for flavors with a primary type of
398 * "text".
399 */
400 public static boolean doesSubtypeSupportCharset(DataFlavor flavor) {
401 if (dtLog.isLoggable(PlatformLogger.FINE)) {
402 if (!"text".equals(flavor.getPrimaryType())) {
403 dtLog.fine("Assertion (\"text\".equals(flavor.getPrimaryType())) failed");
404 }
405 }
406
407 String subType = flavor.getSubType();
408 if (subType == null) {
409 return false;
410 }
411
412 Object support = textMIMESubtypeCharsetSupport.get(subType);
413
414 if (support != null) {
415 return (support == Boolean.TRUE);
416 }
417
418 boolean ret_val = (flavor.getParameter("charset") != null);
419 textMIMESubtypeCharsetSupport.put
420 (subType, (ret_val) ? Boolean.TRUE : Boolean.FALSE);
421 return ret_val;
422 }
423 public static boolean doesSubtypeSupportCharset(String subType,
424 String charset)
425 {
426 Object support = textMIMESubtypeCharsetSupport.get(subType);
427
428 if (support != null) {
429 return (support == Boolean.TRUE);
430 }
431
432 boolean ret_val = (charset != null);
433 textMIMESubtypeCharsetSupport.put
434 (subType, (ret_val) ? Boolean.TRUE : Boolean.FALSE);
435 return ret_val;
436 }
437
438 /**
439 * Returns whether this flavor is a text type which supports the
440 * 'charset' parameter.
441 */
442 public static boolean isFlavorCharsetTextType(DataFlavor flavor) {
443 // Although stringFlavor doesn't actually support the charset
444 // parameter (because its primary MIME type is not "text"), it should
445 // be treated as though it does. stringFlavor is semantically
446 // equivalent to "text/plain" data.
447 if (DataFlavor.stringFlavor.equals(flavor)) {
448 return true;
449 }
450
451 if (!"text".equals(flavor.getPrimaryType()) ||
452 !doesSubtypeSupportCharset(flavor))
453 {
454 return false;
455 }
456
457 Class rep_class = flavor.getRepresentationClass();
458
459 if (flavor.isRepresentationClassReader() ||
460 String.class.equals(rep_class) ||
461 flavor.isRepresentationClassCharBuffer() ||
462 DataTransferer.charArrayClass.equals(rep_class))
463 {
464 return true;
465 }
466
467 if (!(flavor.isRepresentationClassInputStream() ||
468 flavor.isRepresentationClassByteBuffer() ||
469 DataTransferer.byteArrayClass.equals(rep_class))) {
470 return false;
471 }
472
473 String charset = flavor.getParameter("charset");
474
475 return (charset != null)
476 ? DataTransferer.isEncodingSupported(charset)
477 : true; // null equals default encoding which is always supported
478 }
479
480 /**
481 * Returns whether this flavor is a text type which does not support the
482 * 'charset' parameter.
483 */
484 public static boolean isFlavorNoncharsetTextType(DataFlavor flavor) {
485 if (!"text".equals(flavor.getPrimaryType()) ||
486 doesSubtypeSupportCharset(flavor))
487 {
488 return false;
489 }
490
491 return (flavor.isRepresentationClassInputStream() ||
492 flavor.isRepresentationClassByteBuffer() ||
493 DataTransferer.byteArrayClass.
494 equals(flavor.getRepresentationClass()));
495 }
496
497 /**
498 * Determines whether this JRE can both encode and decode text in the
499 * specified encoding.
500 */
501 public static boolean isEncodingSupported(String encoding) {
502 if (encoding == null) {
503 return false;
504 }
505 try {
506 return Charset.isSupported(encoding);
507 } catch (IllegalCharsetNameException icne) {
508 return false;
509 }
510 }
511
512 /**
513 * Returns {@code true} if the given type is a java.rmi.Remote.
514 */
515 public static boolean isRemote(Class<?> type) {
516 return RMI.isRemote(type);
517 }
518
519 /**
520 * Returns an Iterator which traverses a SortedSet of Strings which are
521 * a total order of the standard character sets supported by the JRE. The
522 * ordering follows the same principles as DataFlavor.selectBestTextFlavor.
523 * So as to avoid loading all available character converters, optional,
524 * non-standard, character sets are not included.
525 */
526 public static Iterator standardEncodings() {
527 return StandardEncodingsHolder.standardEncodings.iterator();
528 }
529
530 /**
531 * Converts a FlavorMap to a FlavorTable.
532 */
533 public static FlavorTable adaptFlavorMap(final FlavorMap map) {
534 if (map instanceof FlavorTable) {
535 return (FlavorTable)map;
536 }
537
538 return new FlavorTable() {
539 public Map getNativesForFlavors(DataFlavor[] flavors) {
540 return map.getNativesForFlavors(flavors);
541 }
542 public Map getFlavorsForNatives(String[] natives) {
543 return map.getFlavorsForNatives(natives);
544 }
545 public List getNativesForFlavor(DataFlavor flav) {
546 Map natives =
547 getNativesForFlavors(new DataFlavor[] { flav } );
548 String nat = (String)natives.get(flav);
549 if (nat != null) {
550 List list = new ArrayList(1);
551 list.add(nat);
552 return list;
553 } else {
554 return Collections.EMPTY_LIST;
555 }
556 }
557 public List getFlavorsForNative(String nat) {
558 Map flavors =
559 getFlavorsForNatives(new String[] { nat } );
560 DataFlavor flavor = (DataFlavor)flavors.get(nat);
561 if (flavor != null) {
562 List list = new ArrayList(1);
563 list.add(flavor);
564 return list;
565 } else {
566 return Collections.EMPTY_LIST;
567 }
568 }
569 };
570 }
571
572 /**
573 * Returns the default Unicode encoding for the platform. The encoding
574 * need not be canonical. This method is only used by the archaic function
575 * DataFlavor.getTextPlainUnicodeFlavor().
576 */
577 public abstract String getDefaultUnicodeEncoding();
578
579 /**
580 * This method is called for text flavor mappings established while parsing
581 * the flavormap.properties file. It stores the "eoln" and "terminators"
582 * parameters which are not officially part of the MIME type. They are
583 * MIME parameters specific to the flavormap.properties file format.
584 */
585 public void registerTextFlavorProperties(String nat, String charset,
586 String eoln, String terminators) {
587 Long format = getFormatForNativeAsLong(nat);
588
589 textNatives.add(format);
590 nativeCharsets.put(format, (charset != null && charset.length() != 0)
591 ? charset : getDefaultTextCharset());
592 if (eoln != null && eoln.length() != 0 && !eoln.equals("\n")) {
593 nativeEOLNs.put(format, eoln);
594 }
595 if (terminators != null && terminators.length() != 0) {
596 Integer iTerminators = Integer.valueOf(terminators);
597 if (iTerminators.intValue() > 0) {
598 nativeTerminators.put(format, iTerminators);
599 }
600 }
601 }
602
603 /**
604 * Determines whether the native corresponding to the specified long format
605 * was listed in the flavormap.properties file.
606 */
607 protected boolean isTextFormat(long format) {
608 return textNatives.contains(Long.valueOf(format));
609 }
610
611 protected String getCharsetForTextFormat(Long lFormat) {
612 return (String)nativeCharsets.get(lFormat);
613 }
614
615 /**
616 * Specifies whether text imported from the native system in the specified
617 * format is locale-dependent. If so, when decoding such text,
618 * 'nativeCharsets' should be ignored, and instead, the Transferable should
619 * be queried for its javaTextEncodingFlavor data for the correct encoding.
620 */
621 public abstract boolean isLocaleDependentTextFormat(long format);
622
623 /**
624 * Determines whether the DataFlavor corresponding to the specified long
625 * format is DataFlavor.javaFileListFlavor.
626 */
627 public abstract boolean isFileFormat(long format);
628
629 /**
630 * Determines whether the DataFlavor corresponding to the specified long
631 * format is DataFlavor.imageFlavor.
632 */
633 public abstract boolean isImageFormat(long format);
634
635 /**
636 * Determines whether the format is a URI list we can convert to
637 * a DataFlavor.javaFileListFlavor.
638 */
639 protected boolean isURIListFormat(long format) {
640 return false;
641 }
642
643 /**
644 * Returns a Map whose keys are all of the possible formats into which the
645 * Transferable's transfer data flavors can be translated. The value of
646 * each key is the DataFlavor in which the Transferable's data should be
647 * requested when converting to the format.
648 * <p>
649 * The map keys are sorted according to the native formats preference
650 * order.
651 */
652 public SortedMap getFormatsForTransferable(Transferable contents,
653 FlavorTable map) {
654 DataFlavor[] flavors = contents.getTransferDataFlavors();
655 if (flavors == null) {
656 return new TreeMap();
657 }
658 return getFormatsForFlavors(flavors, map);
659 }
660
661 /**
662 * Returns a Map whose keys are all of the possible formats into which data
663 * in the specified DataFlavor can be translated. The value of each key
664 * is the DataFlavor in which a Transferable's data should be requested
665 * when converting to the format.
666 * <p>
667 * The map keys are sorted according to the native formats preference
668 * order.
669 */
670 public SortedMap getFormatsForFlavor(DataFlavor flavor, FlavorTable map) {
671 return getFormatsForFlavors(new DataFlavor[] { flavor },
672 map);
673 }
674
675 /**
676 * Returns a Map whose keys are all of the possible formats into which data
677 * in the specified DataFlavors can be translated. The value of each key
678 * is the DataFlavor in which the Transferable's data should be requested
679 * when converting to the format.
680 * <p>
681 * The map keys are sorted according to the native formats preference
682 * order.
683 *
684 * @param flavors the data flavors
685 * @param map the FlavorTable which contains mappings between
686 * DataFlavors and data formats
687 * @throws NullPointerException if flavors or map is <code>null</code>
688 */
689 public SortedMap getFormatsForFlavors(DataFlavor[] flavors, FlavorTable map) {
690 Map formatMap = new HashMap(flavors.length);
691 Map textPlainMap = new HashMap(flavors.length);
692 // Maps formats to indices that will be used to sort the formats
693 // according to the preference order.
694 // Larger index value corresponds to the more preferable format.
695 Map indexMap = new HashMap(flavors.length);
696 Map textPlainIndexMap = new HashMap(flavors.length);
697
698 int currentIndex = 0;
699
700 // Iterate backwards so that preferred DataFlavors are used over
701 // other DataFlavors. (See javadoc for
702 // Transferable.getTransferDataFlavors.)
703 for (int i = flavors.length - 1; i >= 0; i--) {
704 DataFlavor flavor = flavors[i];
705 if (flavor == null) continue;
706
707 // Don't explicitly test for String, since it is just a special
708 // case of Serializable
709 if (flavor.isFlavorTextType() ||
710 flavor.isFlavorJavaFileListType() ||
711 DataFlavor.imageFlavor.equals(flavor) ||
712 flavor.isRepresentationClassSerializable() ||
713 flavor.isRepresentationClassInputStream() ||
714 flavor.isRepresentationClassRemote())
715 {
716 List natives = map.getNativesForFlavor(flavor);
717
718 currentIndex += natives.size();
719
720 for (Iterator iter = natives.iterator(); iter.hasNext(); ) {
721 Long lFormat =
722 getFormatForNativeAsLong((String)iter.next());
723 Integer index = Integer.valueOf(currentIndex--);
724
725 formatMap.put(lFormat, flavor);
726 indexMap.put(lFormat, index);
727
728 // SystemFlavorMap.getNativesForFlavor will return
729 // text/plain natives for all text/*. While this is good
730 // for a single text/* flavor, we would prefer that
731 // text/plain native data come from a text/plain flavor.
732 if (("text".equals(flavor.getPrimaryType()) &&
733 "plain".equals(flavor.getSubType())) ||
734 flavor.equals(DataFlavor.stringFlavor))
735 {
736 textPlainMap.put(lFormat, flavor);
737 textPlainIndexMap.put(lFormat, index);
738 }
739 }
740
741 currentIndex += natives.size();
742 }
743 }
744
745 formatMap.putAll(textPlainMap);
746 indexMap.putAll(textPlainIndexMap);
747
748 // Sort the map keys according to the formats preference order.
749 Comparator comparator =
750 new IndexOrderComparator(indexMap, IndexedComparator.SELECT_WORST);
751 SortedMap sortedMap = new TreeMap(comparator);
752 sortedMap.putAll(formatMap);
753
754 return sortedMap;
755 }
756
757 /**
758 * Reduces the Map output for the root function to an array of the
759 * Map's keys.
760 */
761 public long[] getFormatsForTransferableAsArray(Transferable contents,
762 FlavorTable map) {
763 return keysToLongArray(getFormatsForTransferable(contents, map));
764 }
765 public long[] getFormatsForFlavorAsArray(DataFlavor flavor,
766 FlavorTable map) {
767 return keysToLongArray(getFormatsForFlavor(flavor, map));
768 }
769 public long[] getFormatsForFlavorsAsArray(DataFlavor[] flavors,
770 FlavorTable map) {
771 return keysToLongArray(getFormatsForFlavors(flavors, map));
772 }
773
774 /**
775 * Returns a Map whose keys are all of the possible DataFlavors into which
776 * data in the specified format can be translated. The value of each key
777 * is the format in which the Clipboard or dropped data should be requested
778 * when converting to the DataFlavor.
779 */
780 public Map getFlavorsForFormat(long format, FlavorTable map) {
781 return getFlavorsForFormats(new long[] { format }, map);
782 }
783
784 /**
785 * Returns a Map whose keys are all of the possible DataFlavors into which
786 * data in the specified formats can be translated. The value of each key
787 * is the format in which the Clipboard or dropped data should be requested
788 * when converting to the DataFlavor.
789 */
790 public Map getFlavorsForFormats(long[] formats, FlavorTable map) {
791 Map flavorMap = new HashMap(formats.length);
792 Set mappingSet = new HashSet(formats.length);
793 Set flavorSet = new HashSet(formats.length);
794
795 // First step: build flavorSet, mappingSet and initial flavorMap
796 // flavorSet - the set of all the DataFlavors into which
797 // data in the specified formats can be translated;
798 // mappingSet - the set of all the mappings from the specified formats
799 // into any DataFlavor;
800 // flavorMap - after this step, this map maps each of the DataFlavors
801 // from flavorSet to any of the specified formats.
802 for (int i = 0; i < formats.length; i++) {
803 long format = formats[i];
804 String nat = getNativeForFormat(format);
805 List flavors = map.getFlavorsForNative(nat);
806
807 for (Iterator iter = flavors.iterator(); iter.hasNext(); ) {
808 DataFlavor flavor = (DataFlavor)iter.next();
809
810 // Don't explicitly test for String, since it is just a special
811 // case of Serializable
812 if (flavor.isFlavorTextType() ||
813 flavor.isFlavorJavaFileListType() ||
814 DataFlavor.imageFlavor.equals(flavor) ||
815 flavor.isRepresentationClassSerializable() ||
816 flavor.isRepresentationClassInputStream() ||
817 flavor.isRepresentationClassRemote())
818 {
819 Long lFormat = Long.valueOf(format);
820 Object mapping =
821 DataTransferer.createMapping(lFormat, flavor);
822 flavorMap.put(flavor, lFormat);
823 mappingSet.add(mapping);
824 flavorSet.add(flavor);
825 }
826 }
827 }
828
829 // Second step: for each DataFlavor try to figure out which of the
830 // specified formats is the best to translate to this flavor.
831 // Then map each flavor to the best format.
832 // For the given flavor, FlavorTable indicates which native will
833 // best reflect data in the specified flavor to the underlying native
834 // platform. We assume that this native is the best to translate
835 // to this flavor.
836 // Note: FlavorTable allows one-way mappings, so we can occasionally
837 // map a flavor to the format for which the corresponding
838 // format-to-flavor mapping doesn't exist. For this reason we have built
839 // a mappingSet of all format-to-flavor mappings for the specified formats
840 // and check if the format-to-flavor mapping exists for the
841 // (flavor,format) pair being added.
842 for (Iterator flavorIter = flavorSet.iterator();
843 flavorIter.hasNext(); ) {
844 DataFlavor flavor = (DataFlavor)flavorIter.next();
845
846 List natives = map.getNativesForFlavor(flavor);
847
848 for (Iterator nativeIter = natives.iterator();
849 nativeIter.hasNext(); ) {
850 Long lFormat =
851 getFormatForNativeAsLong((String)nativeIter.next());
852 Object mapping = DataTransferer.createMapping(lFormat, flavor);
853
854 if (mappingSet.contains(mapping)) {
855 flavorMap.put(flavor, lFormat);
856 break;
857 }
858 }
859 }
860
861 return flavorMap;
862 }
863
864 /**
865 * Returns a Set of all DataFlavors for which
866 * 1) a mapping from at least one of the specified formats exists in the
867 * specified map and
868 * 2) the data translation for this mapping can be performed by the data
869 * transfer subsystem.
870 *
871 * @param formats the data formats
872 * @param map the FlavorTable which contains mappings between
873 * DataFlavors and data formats
874 * @throws NullPointerException if formats or map is <code>null</code>
875 */
876 public Set getFlavorsForFormatsAsSet(long[] formats, FlavorTable map) {
877 Set flavorSet = new HashSet(formats.length);
878
879 for (int i = 0; i < formats.length; i++) {
880 String nat = getNativeForFormat(formats[i]);
881 List flavors = map.getFlavorsForNative(nat);
882
883 for (Iterator iter = flavors.iterator(); iter.hasNext(); ) {
884 DataFlavor flavor = (DataFlavor)iter.next();
885
886 // Don't explicitly test for String, since it is just a special
887 // case of Serializable
888 if (flavor.isFlavorTextType() ||
889 flavor.isFlavorJavaFileListType() ||
890 DataFlavor.imageFlavor.equals(flavor) ||
891 flavor.isRepresentationClassSerializable() ||
892 flavor.isRepresentationClassInputStream() ||
893 flavor.isRepresentationClassRemote())
894 {
895 flavorSet.add(flavor);
896 }
897 }
898 }
899
900 return flavorSet;
901 }
902
903 /**
904 * Returns an array of all DataFlavors for which
905 * 1) a mapping from the specified format exists in the specified map and
906 * 2) the data translation for this mapping can be performed by the data
907 * transfer subsystem.
908 * The array will be sorted according to a
909 * <code>DataFlavorComparator</code> created with the specified
910 * map as an argument.
911 *
912 * @param format the data format
913 * @param map the FlavorTable which contains mappings between
914 * DataFlavors and data formats
915 * @throws NullPointerException if map is <code>null</code>
916 */
917 public DataFlavor[] getFlavorsForFormatAsArray(long format,
918 FlavorTable map) {
919 return getFlavorsForFormatsAsArray(new long[] { format }, map);
920 }
921
922 /**
923 * Returns an array of all DataFlavors for which
924 * 1) a mapping from at least one of the specified formats exists in the
925 * specified map and
926 * 2) the data translation for this mapping can be performed by the data
927 * transfer subsystem.
928 * The array will be sorted according to a
929 * <code>DataFlavorComparator</code> created with the specified
930 * map as an argument.
931 *
932 * @param formats the data formats
933 * @param map the FlavorTable which contains mappings between
934 * DataFlavors and data formats
935 * @throws NullPointerException if formats or map is <code>null</code>
936 */
937 public DataFlavor[] getFlavorsForFormatsAsArray(long[] formats,
938 FlavorTable map) {
939 // getFlavorsForFormatsAsSet() is less expensive than
940 // getFlavorsForFormats().
941 return setToSortedDataFlavorArray(getFlavorsForFormatsAsSet(formats, map));
942 }
943
944 /**
945 * Returns an object that represents a mapping between the specified
946 * key and value. <tt>null</tt> values and the <tt>null</tt> keys are
947 * permitted. The internal representation of the mapping object is
948 * irrelevant. The only requrement is that the two mapping objects are equal
949 * if and only if their keys are equal and their values are equal.
950 * More formally, the two mapping objects are equal if and only if
951 * <tt>(value1 == null ? value2 == null : value1.equals(value2))
952 * && (key1 == null ? key2 == null : key1.equals(key2))</tt>.
953 */
954 private static Object createMapping(Object key, Object value) {
955 // NOTE: Should be updated to use AbstractMap.SimpleEntry as
956 // soon as it is made public.
957 return Arrays.asList(new Object[] { key, value });
958 }
959
960 /**
961 * Looks-up or registers the String native with the native data transfer
962 * system and returns a long format corresponding to that native.
963 */
964 protected abstract Long getFormatForNativeAsLong(String str);
965
966 /**
967 * Looks-up the String native corresponding to the specified long format in
968 * the native data transfer system.
969 */
970 protected abstract String getNativeForFormat(long format);
971
972 /* Contains common code for finding the best charset for
973 * clipboard string encoding/decoding, basing on clipboard
974 * format and localeTransferable(on decoding, if available)
975 */
976 private String getBestCharsetForTextFormat(Long lFormat,
977 Transferable localeTransferable) throws IOException
978 {
979 String charset = null;
980 if (localeTransferable != null &&
981 isLocaleDependentTextFormat(lFormat) &&
982 localeTransferable.isDataFlavorSupported(javaTextEncodingFlavor))
983 {
984 try {
985 charset = new String(
986 (byte[])localeTransferable.getTransferData(javaTextEncodingFlavor),
987 "UTF-8"
988 );
989 } catch (UnsupportedFlavorException cannotHappen) {
990 }
991 } else {
992 charset = getCharsetForTextFormat(lFormat);
993 }
994 if (charset == null) {
995 // Only happens when we have a custom text type.
996 charset = getDefaultTextCharset();
997 }
998 return charset;
999 }
1000
1001 /**
1002 * Translation function for converting string into
1003 * a byte array. Search-and-replace EOLN. Encode into the
1004 * target format. Append terminating NUL bytes.
1005 *
1006 * Java to Native string conversion
1007 */
1008 private byte[] translateTransferableString(String str,
1009 long format) throws IOException
1010 {
1011 Long lFormat = Long.valueOf(format);
1012 String charset = getBestCharsetForTextFormat(lFormat, null);
1013 // Search and replace EOLN. Note that if EOLN is "\n", then we
1014 // never added an entry to nativeEOLNs anyway, so we'll skip this
1015 // code altogether.
1016 // windows: "abc\nde"->"abc\r\nde"
1017 String eoln = (String)nativeEOLNs.get(lFormat);
1018 if (eoln != null) {
1019 int length = str.length();
1020 StringBuffer buffer =
1021 new StringBuffer(length * 2); // 2 is a heuristic
1022 for (int i = 0; i < length; i++) {
1023 // Fix for 4914613 - skip native EOLN
1024 if (str.startsWith(eoln, i)) {
1025 buffer.append(eoln);
1026 i += eoln.length() - 1;
1027 continue;
1028 }
1029 char c = str.charAt(i);
1030 if (c == '\n') {
1031 buffer.append(eoln);
1032 } else {
1033 buffer.append(c);
1034 }
1035 }
1036 str = buffer.toString();
1037 }
1038
1039 // Encode text in target format.
1040 byte[] bytes = str.getBytes(charset);
1041
1042 // Append terminating NUL bytes. Note that if terminators is 0,
1043 // the we never added an entry to nativeTerminators anyway, so
1044 // we'll skip code altogether.
1045 // "abcde" -> "abcde\0"
1046 Integer terminators = (Integer)nativeTerminators.get(lFormat);
1047 if (terminators != null) {
1048 int numTerminators = terminators.intValue();
1049 byte[] terminatedBytes =
1050 new byte[bytes.length + numTerminators];
1051 System.arraycopy(bytes, 0, terminatedBytes, 0, bytes.length);
1052 for (int i = bytes.length; i < terminatedBytes.length; i++) {
1053 terminatedBytes[i] = 0x0;
1054 }
1055 bytes = terminatedBytes;
1056 }
1057 return bytes;
1058 }
1059
1060 /**
1061 * Translating either a byte array or an InputStream into an String.
1062 * Strip terminators and search-and-replace EOLN.
1063 *
1064 * Native to Java string conversion
1065 */
1066 private String translateBytesOrStreamToString(InputStream str, byte[] bytes,
1067 long format,
1068 Transferable localeTransferable)
1069 throws IOException
1070 {
1071 // A String holds all of its data in memory at one time, so
1072 // we can't avoid reading the entire InputStream at this point.
1073 if (bytes == null) {
1074 bytes = inputStreamToByteArray(str);
1075 }
1076 str.close();
1077
1078 Long lFormat = Long.valueOf(format);
1079 String charset = getBestCharsetForTextFormat(lFormat, localeTransferable);
1080
1081 // Locate terminating NUL bytes. Note that if terminators is 0,
1082 // the we never added an entry to nativeTerminators anyway, so
1083 // we'll skip code altogether.
1084
1085 // In other words: we are doing char alignment here basing on suggestion
1086 // that count of zero-'terminators' is a number of bytes in one symbol
1087 // for selected charset (clipboard format). It is not complitly true for
1088 // multibyte coding like UTF-8, but helps understand the procedure.
1089 // "abcde\0" -> "abcde"
1090
1091 String eoln = (String)nativeEOLNs.get(lFormat);
1092 Integer terminators = (Integer)nativeTerminators.get(lFormat);
1093 int count;
1094 if (terminators != null) {
1095 int numTerminators = terminators.intValue();
1096search:
1097 for (count = 0; count < (bytes.length - numTerminators + 1); count += numTerminators) {
1098 for (int i = count; i < count + numTerminators; i++) {
1099 if (bytes[i] != 0x0) {
1100 continue search;
1101 }
1102 }
1103 // found terminators
1104 break search;
1105 }
1106 } else {
1107 count = bytes.length;
1108 }
1109
1110 // Decode text to chars. Don't include any terminators.
1111 String converted = new String(bytes, 0, count, charset);
1112
1113 // Search and replace EOLN. Note that if EOLN is "\n", then we
1114 // never added an entry to nativeEOLNs anyway, so we'll skip this
1115 // code altogether.
1116 // Count of NUL-terminators and EOLN coding are platform-specific and
1117 // loaded from flavormap.properties file
1118 // windows: "abc\r\nde" -> "abc\nde"
1119
1120 if (eoln != null) {
1121
1122 /* Fix for 4463560: replace EOLNs symbol-by-symbol instead
1123 * of using buf.replace()
1124 */
1125
1126 char[] buf = converted.toCharArray();
1127 char[] eoln_arr = eoln.toCharArray();
1128 converted = null;
1129 int j = 0;
1130 boolean match;
1131
1132 for (int i = 0; i < buf.length; ) {
1133 // Catch last few bytes
1134 if (i + eoln_arr.length > buf.length) {
1135 buf[j++] = buf[i++];
1136 continue;
1137 }
1138
1139 match = true;
1140 for (int k = 0, l = i; k < eoln_arr.length; k++, l++) {
1141 if (eoln_arr[k] != buf[l]) {
1142 match = false;
1143 break;
1144 }
1145 }
1146 if (match) {
1147 buf[j++] = '\n';
1148 i += eoln_arr.length;
1149 } else {
1150 buf[j++] = buf[i++];
1151 }
1152 }
1153 converted = new String(buf, 0, j);
1154 }
1155
1156 return converted;
1157 }
1158
1159
1160 /**
1161 * Primary translation function for translating a Transferable into
1162 * a byte array, given a source DataFlavor and target format.
1163 */
1164 public byte[] translateTransferable(Transferable contents,
1165 DataFlavor flavor,
1166 long format) throws IOException
1167 {
1168 // Obtain the transfer data in the source DataFlavor.
1169 //
1170 // Note that we special case DataFlavor.plainTextFlavor because
1171 // StringSelection supports this flavor incorrectly -- instead of
1172 // returning an InputStream as the DataFlavor representation class
1173 // states, it returns a Reader. Instead of using this broken
1174 // functionality, we request the data in stringFlavor (the other
1175 // DataFlavor which StringSelection supports) and use the String
1176 // translator.
1177 Object obj;
1178 boolean stringSelectionHack;
1179 try {
1180 obj = contents.getTransferData(flavor);
1181 if (obj == null) {
1182 return null;
1183 }
1184 if (flavor.equals(DataFlavor.plainTextFlavor) &&
1185 !(obj instanceof InputStream))
1186 {
1187 obj = contents.getTransferData(DataFlavor.stringFlavor);
1188 if (obj == null) {
1189 return null;
1190 }
1191 stringSelectionHack = true;
1192 } else {
1193 stringSelectionHack = false;
1194 }
1195 } catch (UnsupportedFlavorException e) {
1196 throw new IOException(e.getMessage());
1197 }
1198
1199 // Source data is a String. Search-and-replace EOLN. Encode into the
1200 // target format. Append terminating NUL bytes.
1201 if (stringSelectionHack ||
1202 (String.class.equals(flavor.getRepresentationClass()) &&
1203 isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1204
1205 String str = removeSuspectedData(flavor, contents, (String)obj);
1206
1207 return translateTransferableString(
1208 str,
1209 format);
1210
1211 // Source data is a Reader. Convert to a String and recur. In the
1212 // future, we may want to rewrite this so that we encode on demand.
1213 } else if (flavor.isRepresentationClassReader()) {
1214 if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1215 throw new IOException
1216 ("cannot transfer non-text data as Reader");
1217 }
1218
1219 Reader r = (Reader)obj;
1220 StringBuffer buf = new StringBuffer();
1221 int c;
1222 while ((c = r.read()) != -1) {
1223 buf.append((char)c);
1224 }
1225 r.close();
1226
1227 return translateTransferableString(
1228 buf.toString(),
1229 format);
1230
1231 // Source data is a CharBuffer. Convert to a String and recur.
1232 } else if (flavor.isRepresentationClassCharBuffer()) {
1233 if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1234 throw new IOException
1235 ("cannot transfer non-text data as CharBuffer");
1236 }
1237
1238 CharBuffer buffer = (CharBuffer)obj;
1239 int size = buffer.remaining();
1240 char[] chars = new char[size];
1241 buffer.get(chars, 0, size);
1242
1243 return translateTransferableString(
1244 new String(chars),
1245 format);
1246
1247 // Source data is a char array. Convert to a String and recur.
1248 } else if (charArrayClass.equals(flavor.getRepresentationClass())) {
1249 if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1250 throw new IOException
1251 ("cannot transfer non-text data as char array");
1252 }
1253
1254 return translateTransferableString(
1255 new String((char[])obj),
1256 format);
1257
1258 // Source data is a ByteBuffer. For arbitrary flavors, simply return
1259 // the array. For text flavors, decode back to a String and recur to
1260 // reencode according to the requested format.
1261 } else if (flavor.isRepresentationClassByteBuffer()) {
1262 ByteBuffer buffer = (ByteBuffer)obj;
1263 int size = buffer.remaining();
1264 byte[] bytes = new byte[size];
1265 buffer.get(bytes, 0, size);
1266
1267 if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1268 String sourceEncoding = DataTransferer.getTextCharset(flavor);
1269 return translateTransferableString(
1270 new String(bytes, sourceEncoding),
1271 format);
1272 } else {
1273 return bytes;
1274 }
1275
1276 // Source data is a byte array. For arbitrary flavors, simply return
1277 // the array. For text flavors, decode back to a String and recur to
1278 // reencode according to the requested format.
1279 } else if (byteArrayClass.equals(flavor.getRepresentationClass())) {
1280 byte[] bytes = (byte[])obj;
1281
1282 if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1283 String sourceEncoding = DataTransferer.getTextCharset(flavor);
1284 return translateTransferableString(
1285 new String(bytes, sourceEncoding),
1286 format);
1287 } else {
1288 return bytes;
1289 }
1290 // Source data is Image
1291 } else if (DataFlavor.imageFlavor.equals(flavor)) {
1292 if (!isImageFormat(format)) {
1293 throw new IOException("Data translation failed: " +
1294 "not an image format");
1295 }
1296
1297 Image image = (Image)obj;
1298 byte[] bytes = imageToPlatformBytes(image, format);
1299
1300 if (bytes == null) {
1301 throw new IOException("Data translation failed: " +
1302 "cannot convert java image to native format");
1303 }
1304 return bytes;
1305 }
1306
1307 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1308
1309 // Target data is a file list. Source data must be a
1310 // java.util.List which contains java.io.File or String instances.
1311 if (isFileFormat(format)) {
1312 if (!DataFlavor.javaFileListFlavor.equals(flavor)) {
1313 throw new IOException("data translation failed");
1314 }
1315
1316 final List list = (List)obj;
1317
1318 final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
1319
1320 final ArrayList<String> fileList = castToFiles(list, userProtectionDomain);
1321
1322 bos = convertFileListToBytes(fileList);
1323
1324
1325 // Target data is a URI list. Source data must be a
1326 // java.util.List which contains java.io.File or String instances.
1327 } else if (isURIListFormat(format)) {
1328 if (!DataFlavor.javaFileListFlavor.equals(flavor)) {
1329 throw new IOException("data translation failed");
1330 }
1331 String nat = getNativeForFormat(format);
1332 String targetCharset = null;
1333 if (nat != null) {
1334 try {
1335 targetCharset = new DataFlavor(nat).getParameter("charset");
1336 } catch (ClassNotFoundException cnfe) {
1337 throw new IOException(cnfe);
1338 }
1339 }
1340 if (targetCharset == null) {
1341 targetCharset = "UTF-8";
1342 }
1343 final List list = (List)obj;
1344 final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
1345 final ArrayList<String> fileList = castToFiles(list, userProtectionDomain);
1346 final ArrayList<String> uriList = new ArrayList<String>(fileList.size());
1347 for (String fileObject : fileList) {
1348 final URI uri = new File(fileObject).toURI();
1349 // Some implementations are fussy about the number of slashes (file:///path/to/file is best)
1350 try {
1351 uriList.add(new URI(uri.getScheme(), "", uri.getPath(), uri.getFragment()).toString());
1352 } catch (URISyntaxException uriSyntaxException) {
1353 throw new IOException(uriSyntaxException);
1354 }
1355 }
1356
1357 byte[] eoln = "\r\n".getBytes(targetCharset);
1358 for (int i = 0; i < uriList.size(); i++) {
1359 byte[] bytes = uriList.get(i).getBytes(targetCharset);
1360 bos.write(bytes, 0, bytes.length);
1361 bos.write(eoln, 0, eoln.length);
1362 }
1363
1364 // Source data is an InputStream. For arbitrary flavors, just grab the
1365 // bytes and dump them into a byte array. For text flavors, decode back
1366 // to a String and recur to reencode according to the requested format.
1367 } else if (flavor.isRepresentationClassInputStream()) {
1368 InputStream is = (InputStream)obj;
1369 boolean eof = false;
1370 int avail = is.available();
1371 byte[] tmp = new byte[avail > 8192 ? avail : 8192];
1372 do {
1373 int ret;
1374 if (!(eof = (ret = is.read(tmp, 0, tmp.length)) == -1)) {
1375 bos.write(tmp, 0, ret);
1376 }
1377 } while (!eof);
1378 is.close();
1379
1380 if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1381 byte[] bytes = bos.toByteArray();
1382 bos.close();
1383 String sourceEncoding = DataTransferer.getTextCharset(flavor);
1384 return translateTransferableString(
1385 new String(bytes, sourceEncoding),
1386 format);
1387 }
1388
1389 // Source data is an RMI object
1390 } else if (flavor.isRepresentationClassRemote()) {
1391 Object mo = RMI.newMarshalledObject(obj);
1392 ObjectOutputStream oos = new ObjectOutputStream(bos);
1393 oos.writeObject(mo);
1394 oos.close();
1395
1396 // Source data is Serializable
1397 } else if (flavor.isRepresentationClassSerializable()) {
1398 ObjectOutputStream oos = new ObjectOutputStream(bos);
1399 oos.writeObject(obj);
1400 oos.close();
1401
1402 } else {
1403 throw new IOException("data translation failed");
1404 }
1405
1406 byte[] ret = bos.toByteArray();
1407 bos.close();
1408 return ret;
1409 }
1410
1411 protected abstract ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList) throws IOException;
1412
1413 private String removeSuspectedData(DataFlavor flavor, final Transferable contents, final String str)
1414 throws IOException
1415 {
1416 if (null == System.getSecurityManager()
1417 || !flavor.isMimeTypeEqual("text/uri-list"))
1418 {
1419 return str;
1420 }
1421
1422
1423 String ret_val = "";
1424 final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
1425
1426 try {
1427 ret_val = (String) AccessController.doPrivileged(new PrivilegedExceptionAction() {
1428 public Object run() {
1429
1430 StringBuffer allowedFiles = new StringBuffer(str.length());
1431 String [] uriArray = str.split("(\\s)+");
1432
1433 for (String fileName : uriArray)
1434 {
1435 File file = new File(fileName);
1436 if (file.exists() &&
1437 !(isFileInWebstartedCache(file) ||
1438 isForbiddenToRead(file, userProtectionDomain)))
1439 {
1440
1441 if (0 != allowedFiles.length())
1442 {
1443 allowedFiles.append("\\r\\n");
1444 }
1445
1446 allowedFiles.append(fileName);
1447 }
1448 }
1449
1450 return allowedFiles.toString();
1451 }
1452 });
1453 } catch (PrivilegedActionException pae) {
1454 throw new IOException(pae.getMessage(), pae);
1455 }
1456
1457 return ret_val;
1458 }
1459
1460 private static ProtectionDomain getUserProtectionDomain(Transferable contents) {
1461 return contents.getClass().getProtectionDomain();
1462 }
1463
1464 private boolean isForbiddenToRead (File file, ProtectionDomain protectionDomain)
1465 {
1466 if (null == protectionDomain) {
1467 return false;
1468 }
1469 try {
1470 FilePermission filePermission =
1471 new FilePermission(file.getCanonicalPath(), "read, delete");
1472 if (protectionDomain.implies(filePermission)) {
1473 return false;
1474 }
1475 } catch (IOException e) {}
1476
1477 return true;
1478 }
1479
1480 private ArrayList<String> castToFiles(final List files,
1481 final ProtectionDomain userProtectionDomain) throws IOException
1482 {
1483 final ArrayList<String> fileList = new ArrayList<String>();
1484 try {
1485 AccessController.doPrivileged(new PrivilegedExceptionAction() {
1486 public Object run() throws IOException {
1487 for (Object fileObject : files)
1488 {
1489 File file = castToFile(fileObject);
1490 if (file != null &&
1491 (null == System.getSecurityManager() ||
1492 !(isFileInWebstartedCache(file) ||
1493 isForbiddenToRead(file, userProtectionDomain))))
1494 {
1495 fileList.add(file.getCanonicalPath());
1496 }
1497 }
1498 return null;
1499 }
1500 });
1501 } catch (PrivilegedActionException pae) {
1502 throw new IOException(pae.getMessage());
1503 }
1504 return fileList;
1505 }
1506
1507 // It is important do not use user's successors
1508 // of File class.
1509 private File castToFile(Object fileObject) throws IOException {
1510 String filePath = null;
1511 if (fileObject instanceof File) {
1512 filePath = ((File)fileObject).getCanonicalPath();
1513 } else if (fileObject instanceof String) {
1514 filePath = (String) fileObject;
1515 } else {
1516 return null;
1517 }
1518 return new File(filePath);
1519 }
1520
1521 private final static String[] DEPLOYMENT_CACHE_PROPERTIES = {
1522 "deployment.system.cachedir",
1523 "deployment.user.cachedir",
1524 "deployment.javaws.cachedir",
1525 "deployment.javapi.cachedir"
1526 };
1527
1528 private final static ArrayList <File> deploymentCacheDirectoryList =
1529 new ArrayList<File>();
1530
1531 private static boolean isFileInWebstartedCache(File f) {
1532
1533 if (deploymentCacheDirectoryList.isEmpty()) {
1534 for (String cacheDirectoryProperty : DEPLOYMENT_CACHE_PROPERTIES) {
1535 String cacheDirectoryPath = System.getProperty(cacheDirectoryProperty);
1536 if (cacheDirectoryPath != null) {
1537 try {
1538 File cacheDirectory = (new File(cacheDirectoryPath)).getCanonicalFile();
1539 if (cacheDirectory != null) {
1540 deploymentCacheDirectoryList.add(cacheDirectory);
1541 }
1542 } catch (IOException ioe) {}
1543 }
1544 }
1545 }
1546
1547 for (File deploymentCacheDirectory : deploymentCacheDirectoryList) {
1548 for (File dir = f; dir != null; dir = dir.getParentFile()) {
1549 if (dir.equals(deploymentCacheDirectory)) {
1550 return true;
1551 }
1552 }
1553 }
1554
1555 return false;
1556 }
1557
1558
1559 public Object translateBytes(byte[] bytes, DataFlavor flavor,
1560 long format, Transferable localeTransferable)
1561 throws IOException
1562 {
1563 return translateBytesOrStream(null, bytes, flavor, format,
1564 localeTransferable);
1565 }
1566
1567 public Object translateStream(InputStream str, DataFlavor flavor,
1568 long format, Transferable localeTransferable)
1569 throws IOException
1570 {
1571 return translateBytesOrStream(str, null, flavor, format,
1572 localeTransferable);
1573 }
1574
1575
1576 /**
1577 * Primary translation function for translating either a byte array or
1578 * an InputStream into an Object, given a source format and a target
1579 * DataFlavor.
1580 *
1581 * One of str/bytes is non-null; the other is null.
1582 * The conversion from byte[] to InputStream is cheap, so do that
1583 * immediately if necessary. The opposite conversion is expensive,
1584 * so avoid it if possible.
1585 */
1586 protected Object translateBytesOrStream(InputStream str, byte[] bytes,
1587 DataFlavor flavor, long format,
1588 Transferable localeTransferable)
1589 throws IOException
1590 {
1591
1592 if (str == null) {
1593 str = new ByteArrayInputStream(bytes);
1594 }
1595
1596 // Source data is a file list. Use the dragQueryFile native function to
1597 // do most of the decoding. Then wrap File objects around the String
1598 // filenames and return a List.
1599 if (isFileFormat(format)) {
1600 if (!DataFlavor.javaFileListFlavor.equals(flavor)) {
1601 throw new IOException("data translation failed");
1602 }
1603 if (bytes == null) {
1604 bytes = inputStreamToByteArray(str);
1605 }
1606 String[] filenames = dragQueryFile(bytes);
1607 if (filenames == null) {
1608 str.close();
1609 return null;
1610 }
1611
1612 // Convert the strings to File objects
1613 File[] files = new File[filenames.length];
1614 for (int i = 0; i < filenames.length; i++) {
1615 files[i] = new File(filenames[i]);
1616 }
1617 str.close();
1618
1619 // Turn the list of Files into a List and return
1620 return Arrays.asList(files);
1621
1622 // Source data is a URI list. Convert to DataFlavor.javaFileListFlavor
1623 // where possible.
1624 } else if (isURIListFormat(format) && DataFlavor.javaFileListFlavor.equals(flavor)) {
1625 try {
1626 URI uris[] = dragQueryURIs(str, bytes, format, localeTransferable);
1627 if (uris == null) {
1628 return null;
1629 }
1630 ArrayList files = new ArrayList();
1631 for (URI uri : uris) {
1632 try {
1633 files.add(new File(uri));
1634 } catch (IllegalArgumentException illegalArg) {
1635 // When converting from URIs to less generic files,
1636 // common practice (Wine, SWT) seems to be to
1637 // silently drop the URIs that aren't local files.
1638 }
1639 }
1640 return files;
1641 } finally {
1642 str.close();
1643 }
1644
1645 // Target data is a String. Strip terminating NUL bytes. Decode bytes
1646 // into characters. Search-and-replace EOLN.
1647 } else if (String.class.equals(flavor.getRepresentationClass()) &&
1648 isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1649
1650 return translateBytesOrStreamToString(
1651 str, bytes,
1652 format, localeTransferable);
1653
1654 // Special hack to maintain backwards-compatibility with the brokenness
1655 // of StringSelection. Return a StringReader instead of an InputStream.
1656 // Recur to obtain String and encapsulate.
1657 } else if (DataFlavor.plainTextFlavor.equals(flavor)) {
1658 return new StringReader(translateBytesOrStreamToString(
1659 str, bytes,
1660 format, localeTransferable));
1661
1662 // Target data is an InputStream. For arbitrary flavors, just return
1663 // the raw bytes. For text flavors, decode to strip terminators and
1664 // search-and-replace EOLN, then reencode according to the requested
1665 // flavor.
1666 } else if (flavor.isRepresentationClassInputStream()) {
1667 return translateBytesOrStreamToInputStream(str, flavor, format,
1668 localeTransferable);
1669
1670 // Target data is a Reader. Obtain data in InputStream format, encoded
1671 // as "Unicode" (utf-16be). Then use an InputStreamReader to decode
1672 // back to chars on demand.
1673 } else if (flavor.isRepresentationClassReader()) {
1674 if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1675 throw new IOException
1676 ("cannot transfer non-text data as Reader");
1677 }
1678
1679 InputStream is = (InputStream)
1680 translateBytesOrStreamToInputStream
1681 (str, DataFlavor.plainTextFlavor, format,
1682 localeTransferable);
1683 String unicode =
1684 DataTransferer.getTextCharset(DataFlavor.plainTextFlavor);
1685 Reader reader = new InputStreamReader(is, unicode);
1686
1687 return constructFlavoredObject(reader, flavor, Reader.class);
1688
1689 // Target data is a CharBuffer. Recur to obtain String and wrap.
1690 } else if (flavor.isRepresentationClassCharBuffer()) {
1691 if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1692 throw new IOException
1693 ("cannot transfer non-text data as CharBuffer");
1694 }
1695
1696 CharBuffer buffer = CharBuffer.wrap(translateBytesOrStreamToString(
1697 str, bytes,
1698 format, localeTransferable));
1699
1700 return constructFlavoredObject(buffer, flavor, CharBuffer.class);
1701
1702 // Target data is a char array. Recur to obtain String and convert to
1703 // char array.
1704 } else if (charArrayClass.equals(flavor.getRepresentationClass())) {
1705 if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1706 throw new IOException
1707 ("cannot transfer non-text data as char array");
1708 }
1709
1710 return translateBytesOrStreamToString(
1711 str, bytes,
1712 format, localeTransferable).toCharArray();
1713
1714 // Target data is a ByteBuffer. For arbitrary flavors, just return
1715 // the raw bytes. For text flavors, convert to a String to strip
1716 // terminators and search-and-replace EOLN, then reencode according to
1717 // the requested flavor.
1718 } else if (flavor.isRepresentationClassByteBuffer()) {
1719 if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1720 bytes = translateBytesOrStreamToString(
1721 str, bytes,
1722 format, localeTransferable
1723 ).getBytes(
1724 DataTransferer.getTextCharset(flavor)
1725 );
1726 } else {
1727 if (bytes == null) {
1728 bytes = inputStreamToByteArray(str);
1729 }
1730 }
1731
1732 ByteBuffer buffer = ByteBuffer.wrap(bytes);
1733 return constructFlavoredObject(buffer, flavor, ByteBuffer.class);
1734
1735 // Target data is a byte array. For arbitrary flavors, just return
1736 // the raw bytes. For text flavors, convert to a String to strip
1737 // terminators and search-and-replace EOLN, then reencode according to
1738 // the requested flavor.
1739 } else if (byteArrayClass.equals(flavor.getRepresentationClass())) {
1740 if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1741 return translateBytesOrStreamToString(
1742 str, bytes,
1743 format, localeTransferable
1744 ).getBytes(
1745 DataTransferer.getTextCharset(flavor)
1746 );
1747 } else {
1748 return (bytes != null) ? bytes : inputStreamToByteArray(str);
1749 }
1750
1751 // Target data is an RMI object
1752 } else if (flavor.isRepresentationClassRemote()) {
1753 try {
1754 byte[] ba = inputStreamToByteArray(str);
1755 ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(ba));
1756 Object ret = RMI.getMarshalledObject(ois.readObject());
1757 ois.close();
1758 str.close();
1759 return ret;
1760 } catch (Exception e) {
1761 throw new IOException(e.getMessage());
1762 }
1763
1764 // Target data is Serializable
1765 } else if (flavor.isRepresentationClassSerializable()) {
1766 try {
1767 byte[] ba = inputStreamToByteArray(str);
1768 ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(ba));
1769 Object ret = ois.readObject();
1770 ois.close();
1771 str.close();
1772 return ret;
1773 } catch (Exception e) {
1774 throw new IOException(e.getMessage());
1775 }
1776
1777 // Target data is Image
1778 } else if (DataFlavor.imageFlavor.equals(flavor)) {
1779 if (!isImageFormat(format)) {
1780 throw new IOException("data translation failed");
1781 }
1782
1783 Image image = platformImageBytesOrStreamToImage(str, bytes, format);
1784 str.close();
1785 return image;
1786 }
1787
1788 throw new IOException("data translation failed");
1789 }
1790
1791 /**
1792 * For arbitrary flavors, just use the raw InputStream. For text flavors,
1793 * ReencodingInputStream will decode and reencode the InputStream on demand
1794 * so that we can strip terminators and search-and-replace EOLN.
1795 */
1796 private Object translateBytesOrStreamToInputStream
1797 (InputStream str, DataFlavor flavor, long format,
1798 Transferable localeTransferable) throws IOException
1799 {
1800 if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1801 str = new ReencodingInputStream
1802 (str, format, DataTransferer.getTextCharset(flavor),
1803 localeTransferable);
1804 }
1805
1806 return constructFlavoredObject(str, flavor, InputStream.class);
1807 }
1808
1809 /**
1810 * We support representations which are exactly of the specified Class,
1811 * and also arbitrary Objects which have a constructor which takes an
1812 * instance of the Class as its sole parameter.
1813 */
1814 private Object constructFlavoredObject(Object arg, DataFlavor flavor,
1815 Class clazz)
1816 throws IOException
1817 {
1818 final Class dfrc = flavor.getRepresentationClass();
1819
1820 if (clazz.equals(dfrc)) {
1821 return arg; // simple case
1822 } else {
1823 Constructor[] constructors = null;
1824
1825 try {
1826 constructors = (Constructor[])
1827 AccessController.doPrivileged(new PrivilegedAction() {
1828 public Object run() {
1829 return dfrc.getConstructors();
1830 }
1831 });
1832 } catch (SecurityException se) {
1833 throw new IOException(se.getMessage());
1834 }
1835
1836 Constructor constructor = null;
1837
1838 for (int j = 0; j < constructors.length; j++) {
1839 if (!Modifier.isPublic(constructors[j].getModifiers())) {
1840 continue;
1841 }
1842
1843 Class[] ptypes = constructors[j].getParameterTypes();
1844
1845 if (ptypes != null && ptypes.length == 1 &&
1846 clazz.equals(ptypes[0])) {
1847 constructor = constructors[j];
1848 break;
1849 }
1850 }
1851
1852 if (constructor == null) {
1853 throw new IOException("can't find <init>(L"+ clazz +
1854 ";)V for class: " + dfrc.getName());
1855 }
1856
1857 try {
1858 return constructor.newInstance(new Object[] { arg } );
1859 } catch (Exception e) {
1860 throw new IOException(e.getMessage());
1861 }
1862 }
1863 }
1864
1865 /**
1866 * Used for decoding and reencoding an InputStream on demand so that we
1867 * can strip NUL terminators and perform EOLN search-and-replace.
1868 */
1869 public class ReencodingInputStream extends InputStream {
1870 protected BufferedReader wrapped;
1871 protected final char[] in = new char[1];
1872 protected byte[] out;
1873
1874 protected CharsetEncoder encoder;
1875 protected CharBuffer inBuf;
1876 protected ByteBuffer outBuf;
1877
1878 protected char[] eoln;
1879 protected int numTerminators;
1880
1881 protected boolean eos;
1882 protected int index, limit;
1883
1884 public ReencodingInputStream(InputStream bytestream, long format,
1885 String targetEncoding,
1886 Transferable localeTransferable)
1887 throws IOException
1888 {
1889 Long lFormat = Long.valueOf(format);
1890
1891 String sourceEncoding = null;
1892 if (isLocaleDependentTextFormat(format) &&
1893 localeTransferable != null &&
1894 localeTransferable.
1895 isDataFlavorSupported(javaTextEncodingFlavor))
1896 {
1897 try {
1898 sourceEncoding = new String((byte[])localeTransferable.
1899 getTransferData(javaTextEncodingFlavor),
1900 "UTF-8");
1901 } catch (UnsupportedFlavorException cannotHappen) {
1902 }
1903 } else {
1904 sourceEncoding = getCharsetForTextFormat(lFormat);
1905 }
1906
1907 if (sourceEncoding == null) {
1908 // Only happens when we have a custom text type.
1909 sourceEncoding = getDefaultTextCharset();
1910 }
1911 wrapped = new BufferedReader
1912 (new InputStreamReader(bytestream, sourceEncoding));
1913
1914 if (targetEncoding == null) {
1915 // Throw NullPointerException for compatibility with the former
1916 // call to sun.io.CharToByteConverter.getConverter(null)
1917 // (Charset.forName(null) throws unspecified IllegalArgumentException
1918 // now; see 6228568)
1919 throw new NullPointerException("null target encoding");
1920 }
1921
1922 try {
1923 encoder = Charset.forName(targetEncoding).newEncoder();
1924 out = new byte[(int)(encoder.maxBytesPerChar() + 0.5)];
1925 inBuf = CharBuffer.wrap(in);
1926 outBuf = ByteBuffer.wrap(out);
1927 } catch (IllegalCharsetNameException e) {
1928 throw new IOException(e.toString());
1929 } catch (UnsupportedCharsetException e) {
1930 throw new IOException(e.toString());
1931 } catch (UnsupportedOperationException e) {
1932 throw new IOException(e.toString());
1933 }
1934
1935 String sEoln = (String)nativeEOLNs.get(lFormat);
1936 if (sEoln != null) {
1937 eoln = sEoln.toCharArray();
1938 }
1939
1940 // A hope and a prayer that this works generically. This will
1941 // definitely work on Win32.
1942 Integer terminators = (Integer)nativeTerminators.get(lFormat);
1943 if (terminators != null) {
1944 numTerminators = terminators.intValue();
1945 }
1946 }
1947
1948 public int read() throws IOException {
1949 if (eos) {
1950 return -1;
1951 }
1952
1953 if (index >= limit) {
1954 int c = wrapped.read();
1955
1956 if (c == -1) { // -1 is EOS
1957 eos = true;
1958 return -1;
1959 }
1960
1961 // "c == 0" is not quite correct, but good enough on Windows.
1962 if (numTerminators > 0 && c == 0) {
1963 eos = true;
1964 return -1;
1965 } else if (eoln != null && matchCharArray(eoln, c)) {
1966 c = '\n' & 0xFFFF;
1967 }
1968
1969 in[0] = (char)c;
1970
1971 inBuf.rewind();
1972 outBuf.rewind();
1973 encoder.encode(inBuf, outBuf, false);
1974 outBuf.flip();
1975 limit = outBuf.limit();
1976
1977 index = 0;
1978
1979 return read();
1980 } else {
1981 return out[index++] & 0xFF;
1982 }
1983 }
1984
1985 public int available() throws IOException {
1986 return ((eos) ? 0 : (limit - index));
1987 }
1988
1989 public void close() throws IOException {
1990 wrapped.close();
1991 }
1992
1993 /**
1994 * Checks to see if the next array.length characters in wrapped
1995 * match array. The first character is provided as c. Subsequent
1996 * characters are read from wrapped itself. When this method returns,
1997 * the wrapped index may be different from what it was when this
1998 * method was called.
1999 */
2000 private boolean matchCharArray(char[] array, int c)
2001 throws IOException
2002 {
2003 wrapped.mark(array.length); // BufferedReader supports mark
2004
2005 int count = 0;
2006 if ((char)c == array[0]) {
2007 for (count = 1; count < array.length; count++) {
2008 c = wrapped.read();
2009 if (c == -1 || ((char)c) != array[count]) {
2010 break;
2011 }
2012 }
2013 }
2014
2015 if (count == array.length) {
2016 return true;
2017 } else {
2018 wrapped.reset();
2019 return false;
2020 }
2021 }
2022 }
2023
2024 /**
2025 * Decodes a byte array into a set of String filenames.
2026 */
2027 protected abstract String[] dragQueryFile(byte[] bytes);
2028
2029 /**
2030 * Decodes URIs from either a byte array or a stream.
2031 */
2032 protected URI[] dragQueryURIs(InputStream stream,
2033 byte[] bytes,
2034 long format,
2035 Transferable localeTransferable)
2036 throws IOException
2037 {
2038 throw new IOException(
2039 new UnsupportedOperationException("not implemented on this platform"));
2040 }
2041
2042 /**
2043 * Translates either a byte array or an input stream which contain
2044 * platform-specific image data in the given format into an Image.
2045 */
2046 protected abstract Image platformImageBytesOrStreamToImage(InputStream str,
2047 byte[] bytes,
2048 long format)
2049 throws IOException;
2050
2051 /**
2052 * Translates either a byte array or an input stream which contain
2053 * an image data in the given standard format into an Image.
2054 *
2055 * @param mimeType image MIME type, such as: image/png, image/jpeg, image/gif
2056 */
2057 protected Image standardImageBytesOrStreamToImage(InputStream inputStream,
2058 byte[] bytes,
2059 String mimeType)
2060 throws IOException {
2061 if (inputStream == null) {
2062 inputStream = new ByteArrayInputStream(bytes);
2063 }
2064
2065 Iterator readerIterator = ImageIO.getImageReadersByMIMEType(mimeType);
2066
2067 if (!readerIterator.hasNext()) {
2068 throw new IOException("No registered service provider can decode " +
2069 " an image from " + mimeType);
2070 }
2071
2072 IOException ioe = null;
2073
2074 while (readerIterator.hasNext()) {
2075 ImageReader imageReader = (ImageReader)readerIterator.next();
2076 try {
2077 ImageInputStream imageInputStream =
2078 ImageIO.createImageInputStream(inputStream);
2079
2080 try {
2081 ImageReadParam param = imageReader.getDefaultReadParam();
2082 imageReader.setInput(imageInputStream, true, true);
2083 BufferedImage bufferedImage =
2084 imageReader.read(imageReader.getMinIndex(), param);
2085 if (bufferedImage != null) {
2086 return bufferedImage;
2087 }
2088 } finally {
2089 imageInputStream.close();
2090 imageReader.dispose();
2091 }
2092 } catch (IOException e) {
2093 ioe = e;
2094 continue;
2095 }
2096 }
2097
2098 if (ioe == null) {
2099 ioe = new IOException("Registered service providers failed to decode"
2100 + " an image from " + mimeType);
2101 }
2102
2103 throw ioe;
2104 }
2105
2106 /**
2107 * Translates a Java Image into a byte array which contains platform-
2108 * specific image data in the given format.
2109 */
2110 protected abstract byte[] imageToPlatformBytes(Image image, long format)
2111 throws IOException;
2112
2113 /**
2114 * Translates a Java Image into a byte array which contains
2115 * an image data in the given standard format.
2116 *
2117 * @param mimeType image MIME type, such as: image/png, image/jpeg
2118 */
2119 protected byte[] imageToStandardBytes(Image image, String mimeType)
2120 throws IOException {
2121 IOException originalIOE = null;
2122
2123 Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
2124
2125 if (!writerIterator.hasNext()) {
2126 throw new IOException("No registered service provider can encode " +
2127 " an image to " + mimeType);
2128 }
2129
2130 if (image instanceof RenderedImage) {
2131 // Try to encode the original image.
2132 try {
2133 return imageToStandardBytesImpl((RenderedImage)image, mimeType);
2134 } catch (IOException ioe) {
2135 originalIOE = ioe;
2136 }
2137 }
2138
2139 // Retry with a BufferedImage.
2140 int width = 0;
2141 int height = 0;
2142 if (image instanceof ToolkitImage) {
2143 ImageRepresentation ir = ((ToolkitImage)image).getImageRep();
2144 ir.reconstruct(ImageObserver.ALLBITS);
2145 width = ir.getWidth();
2146 height = ir.getHeight();
2147 } else {
2148 width = image.getWidth(null);
2149 height = image.getHeight(null);
2150 }
2151
2152 ColorModel model = ColorModel.getRGBdefault();
2153 WritableRaster raster =
2154 model.createCompatibleWritableRaster(width, height);
2155
2156 BufferedImage bufferedImage =
2157 new BufferedImage(model, raster, model.isAlphaPremultiplied(),
2158 null);
2159
2160 Graphics g = bufferedImage.getGraphics();
2161 try {
2162 g.drawImage(image, 0, 0, width, height, null);
2163 } finally {
2164 g.dispose();
2165 }
2166
2167 try {
2168 return imageToStandardBytesImpl(bufferedImage, mimeType);
2169 } catch (IOException ioe) {
2170 if (originalIOE != null) {
2171 throw originalIOE;
2172 } else {
2173 throw ioe;
2174 }
2175 }
2176 }
2177
2178 protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage,
2179 String mimeType)
2180 throws IOException {
2181
2182 Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
2183
2184 ImageTypeSpecifier typeSpecifier =
2185 new ImageTypeSpecifier(renderedImage);
2186
2187 ByteArrayOutputStream baos = new ByteArrayOutputStream();
2188 IOException ioe = null;
2189
2190 while (writerIterator.hasNext()) {
2191 ImageWriter imageWriter = (ImageWriter)writerIterator.next();
2192 ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
2193
2194 if (!writerSpi.canEncodeImage(typeSpecifier)) {
2195 continue;
2196 }
2197
2198 try {
2199 ImageOutputStream imageOutputStream =
2200 ImageIO.createImageOutputStream(baos);
2201 try {
2202 imageWriter.setOutput(imageOutputStream);
2203 imageWriter.write(renderedImage);
2204 imageOutputStream.flush();
2205 } finally {
2206 imageOutputStream.close();
2207 }
2208 } catch (IOException e) {
2209 imageWriter.dispose();
2210 baos.reset();
2211 ioe = e;
2212 continue;
2213 }
2214
2215 imageWriter.dispose();
2216 baos.close();
2217 return baos.toByteArray();
2218 }
2219
2220 baos.close();
2221
2222 if (ioe == null) {
2223 ioe = new IOException("Registered service providers failed to encode "
2224 + renderedImage + " to " + mimeType);
2225 }
2226
2227 throw ioe;
2228 }
2229
2230 /**
2231 * Concatenates the data represented by two objects. Objects can be either
2232 * byte arrays or instances of <code>InputStream</code>. If both arguments
2233 * are byte arrays byte array will be returned. Otherwise an
2234 * <code>InputStream</code> will be returned.
2235 * <p>
2236 * Currently is only called from native code to prepend palette data to
2237 * platform-specific image data during image transfer on Win32.
2238 *
2239 * @param obj1 the first object to be concatenated.
2240 * @param obj2 the second object to be concatenated.
2241 * @return a byte array or an <code>InputStream</code> which represents
2242 * a logical concatenation of the two arguments.
2243 * @throws NullPointerException is either of the arguments is
2244 * <code>null</code>
2245 * @throws ClassCastException is either of the arguments is
2246 * neither byte array nor an instance of <code>InputStream</code>.
2247 */
2248 private Object concatData(Object obj1, Object obj2) {
2249 InputStream str1 = null;
2250 InputStream str2 = null;
2251
2252 if (obj1 instanceof byte[]) {
2253 byte[] arr1 = (byte[])obj1;
2254 if (obj2 instanceof byte[]) {
2255 byte[] arr2 = (byte[])obj2;
2256 byte[] ret = new byte[arr1.length + arr2.length];
2257 System.arraycopy(arr1, 0, ret, 0, arr1.length);
2258 System.arraycopy(arr2, 0, ret, arr1.length, arr2.length);
2259 return ret;
2260 } else {
2261 str1 = new ByteArrayInputStream(arr1);
2262 str2 = (InputStream)obj2;
2263 }
2264 } else {
2265 str1 = (InputStream)obj1;
2266 if (obj2 instanceof byte[]) {
2267 str2 = new ByteArrayInputStream((byte[])obj2);
2268 } else {
2269 str2 = (InputStream)obj2;
2270 }
2271 }
2272
2273 return new SequenceInputStream(str1, str2);
2274 }
2275
2276 public byte[] convertData(final Object source,
2277 final Transferable contents,
2278 final long format,
2279 final Map formatMap,
2280 final boolean isToolkitThread)
2281 throws IOException
2282 {
2283 byte[] ret = null;
2284
2285 /*
2286 * If the current thread is the Toolkit thread we should post a
2287 * Runnable to the event dispatch thread associated with source Object,
2288 * since translateTransferable() calls Transferable.getTransferData()
2289 * that may contain client code.
2290 */
2291 if (isToolkitThread) try {
2292 final Stack stack = new Stack();
2293 final Runnable dataConverter = new Runnable() {
2294 // Guard against multiple executions.
2295 private boolean done = false;
2296 public void run() {
2297 if (done) {
2298 return;
2299 }
2300 byte[] data = null;
2301 try {
2302 DataFlavor flavor = (DataFlavor)formatMap.get(Long.valueOf(format));
2303 if (flavor != null) {
2304 data = translateTransferable(contents, flavor, format);
2305 }
2306 } catch (Exception e) {
2307 e.printStackTrace();
2308 data = null;
2309 }
2310 try {
2311 getToolkitThreadBlockedHandler().lock();
2312 stack.push(data);
2313 getToolkitThreadBlockedHandler().exit();
2314 } finally {
2315 getToolkitThreadBlockedHandler().unlock();
2316 done = true;
2317 }
2318 }
2319 };
2320
2321 final AppContext appContext = SunToolkit.targetToAppContext(source);
2322
2323 getToolkitThreadBlockedHandler().lock();
2324
2325 if (appContext != null) {
2326 appContext.put(DATA_CONVERTER_KEY, dataConverter);
2327 }
2328
2329 SunToolkit.executeOnEventHandlerThread(source, dataConverter);
2330
2331 while (stack.empty()) {
2332 getToolkitThreadBlockedHandler().enter();
2333 }
2334
2335 if (appContext != null) {
2336 appContext.remove(DATA_CONVERTER_KEY);
2337 }
2338
2339 ret = (byte[])stack.pop();
2340 } finally {
2341 getToolkitThreadBlockedHandler().unlock();
2342 } else {
2343 DataFlavor flavor = (DataFlavor)
2344 formatMap.get(Long.valueOf(format));
2345 if (flavor != null) {
2346 ret = translateTransferable(contents, flavor, format);
2347 }
2348 }
2349
2350 return ret;
2351 }
2352
2353 public void processDataConversionRequests() {
2354 if (EventQueue.isDispatchThread()) {
2355 AppContext appContext = AppContext.getAppContext();
2356 getToolkitThreadBlockedHandler().lock();
2357 try {
2358 Runnable dataConverter =
2359 (Runnable)appContext.get(DATA_CONVERTER_KEY);
2360 if (dataConverter != null) {
2361 dataConverter.run();
2362 appContext.remove(DATA_CONVERTER_KEY);
2363 }
2364 } finally {
2365 getToolkitThreadBlockedHandler().unlock();
2366 }
2367 }
2368 }
2369
2370 public abstract ToolkitThreadBlockedHandler
2371 getToolkitThreadBlockedHandler();
2372
2373 /**
2374 * Helper function to reduce a Map with Long keys to a long array.
2375 * <p>
2376 * The map keys are sorted according to the native formats preference
2377 * order.
2378 */
2379 public static long[] keysToLongArray(SortedMap map) {
2380 Set keySet = map.keySet();
2381 long[] retval = new long[keySet.size()];
2382 int i = 0;
2383 for (Iterator iter = keySet.iterator(); iter.hasNext(); i++) {
2384 retval[i] = ((Long)iter.next()).longValue();
2385 }
2386 return retval;
2387 }
2388
2389 /**
2390 * Helper function to reduce a Map with DataFlavor keys to a DataFlavor
2391 * array. The array will be sorted according to
2392 * <code>DataFlavorComparator</code>.
2393 */
2394 public static DataFlavor[] keysToDataFlavorArray(Map map) {
2395 return setToSortedDataFlavorArray(map.keySet(), map);
2396 }
2397
2398 /**
2399 * Helper function to convert a Set of DataFlavors to a sorted array.
2400 * The array will be sorted according to <code>DataFlavorComparator</code>.
2401 */
2402 public static DataFlavor[] setToSortedDataFlavorArray(Set flavorsSet) {
2403 DataFlavor[] flavors = new DataFlavor[flavorsSet.size()];
2404 flavorsSet.toArray(flavors);
2405 final Comparator comparator =
2406 new DataFlavorComparator(IndexedComparator.SELECT_WORST);
2407 Arrays.sort(flavors, comparator);
2408 return flavors;
2409 }
2410
2411 /**
2412 * Helper function to convert a Set of DataFlavors to a sorted array.
2413 * The array will be sorted according to a
2414 * <code>DataFlavorComparator</code> created with the specified
2415 * flavor-to-native map as an argument.
2416 */
2417 public static DataFlavor[] setToSortedDataFlavorArray
2418 (Set flavorsSet, Map flavorToNativeMap)
2419 {
2420 DataFlavor[] flavors = new DataFlavor[flavorsSet.size()];
2421 flavorsSet.toArray(flavors);
2422 Comparator comparator =
2423 new DataFlavorComparator(flavorToNativeMap,
2424 IndexedComparator.SELECT_WORST);
2425 Arrays.sort(flavors, comparator);
2426 return flavors;
2427 }
2428
2429 /**
2430 * Helper function to convert an InputStream to a byte[] array.
2431 */
2432 protected static byte[] inputStreamToByteArray(InputStream str)
2433 throws IOException
2434 {
2435 ByteArrayOutputStream baos = new ByteArrayOutputStream();
2436 int len = 0;
2437 byte[] buf = new byte[8192];
2438
2439 while ((len = str.read(buf)) != -1) {
2440 baos.write(buf, 0, len);
2441 }
2442
2443 return baos.toByteArray();
2444 }
2445
2446 /**
2447 * Returns platform-specific mappings for the specified native.
2448 * If there are no platform-specific mappings for this native, the method
2449 * returns an empty <code>List</code>.
2450 */
2451 public List getPlatformMappingsForNative(String nat) {
2452 return new ArrayList();
2453 }
2454
2455 /**
2456 * Returns platform-specific mappings for the specified flavor.
2457 * If there are no platform-specific mappings for this flavor, the method
2458 * returns an empty <code>List</code>.
2459 */
2460 public List getPlatformMappingsForFlavor(DataFlavor df) {
2461 return new ArrayList();
2462 }
2463
2464 /**
2465 * A Comparator which includes a helper function for comparing two Objects
2466 * which are likely to be keys in the specified Map.
2467 */
2468 public abstract static class IndexedComparator implements Comparator {
2469
2470 /**
2471 * The best Object (e.g., DataFlavor) will be the last in sequence.
2472 */
2473 public static final boolean SELECT_BEST = true;
2474
2475 /**
2476 * The best Object (e.g., DataFlavor) will be the first in sequence.
2477 */
2478 public static final boolean SELECT_WORST = false;
2479
2480 protected final boolean order;
2481
2482 public IndexedComparator() {
2483 this(SELECT_BEST);
2484 }
2485
2486 public IndexedComparator(boolean order) {
2487 this.order = order;
2488 }
2489
2490 /**
2491 * Helper method to compare two objects by their Integer indices in the
2492 * given map. If the map doesn't contain an entry for either of the
2493 * objects, the fallback index will be used for the object instead.
2494 *
2495 * @param indexMap the map which maps objects into Integer indexes.
2496 * @param obj1 the first object to be compared.
2497 * @param obj2 the second object to be compared.
2498 * @param fallbackIndex the Integer to be used as a fallback index.
2499 * @return a negative integer, zero, or a positive integer as the
2500 * first object is mapped to a less, equal to, or greater
2501 * index than the second.
2502 */
2503 protected static int compareIndices(Map indexMap,
2504 Object obj1, Object obj2,
2505 Integer fallbackIndex) {
2506 Integer index1 = (Integer)indexMap.get(obj1);
2507 Integer index2 = (Integer)indexMap.get(obj2);
2508
2509 if (index1 == null) {
2510 index1 = fallbackIndex;
2511 }
2512 if (index2 == null) {
2513 index2 = fallbackIndex;
2514 }
2515
2516 return index1.compareTo(index2);
2517 }
2518
2519 /**
2520 * Helper method to compare two objects by their Long indices in the
2521 * given map. If the map doesn't contain an entry for either of the
2522 * objects, the fallback index will be used for the object instead.
2523 *
2524 * @param indexMap the map which maps objects into Long indexes.
2525 * @param obj1 the first object to be compared.
2526 * @param obj2 the second object to be compared.
2527 * @param fallbackIndex the Long to be used as a fallback index.
2528 * @return a negative integer, zero, or a positive integer as the
2529 * first object is mapped to a less, equal to, or greater
2530 * index than the second.
2531 */
2532 protected static int compareLongs(Map indexMap,
2533 Object obj1, Object obj2,
2534 Long fallbackIndex) {
2535 Long index1 = (Long)indexMap.get(obj1);
2536 Long index2 = (Long)indexMap.get(obj2);
2537
2538 if (index1 == null) {
2539 index1 = fallbackIndex;
2540 }
2541 if (index2 == null) {
2542 index2 = fallbackIndex;
2543 }
2544
2545 return index1.compareTo(index2);
2546 }
2547 }
2548
2549 /**
2550 * An IndexedComparator which compares two String charsets. The comparison
2551 * follows the rules outlined in DataFlavor.selectBestTextFlavor. In order
2552 * to ensure that non-Unicode, non-ASCII, non-default charsets are sorted
2553 * in alphabetical order, charsets are not automatically converted to their
2554 * canonical forms.
2555 */
2556 public static class CharsetComparator extends IndexedComparator {
2557 private static final Map charsets;
2558 private static String defaultEncoding;
2559
2560 private static final Integer DEFAULT_CHARSET_INDEX = Integer.valueOf(2);
2561 private static final Integer OTHER_CHARSET_INDEX = Integer.valueOf(1);
2562 private static final Integer WORST_CHARSET_INDEX = Integer.valueOf(0);
2563 private static final Integer UNSUPPORTED_CHARSET_INDEX =
2564 Integer.valueOf(Integer.MIN_VALUE);
2565
2566 private static final String UNSUPPORTED_CHARSET = "UNSUPPORTED";
2567
2568 static {
2569 HashMap charsetsMap = new HashMap(8, 1.0f);
2570
2571 // we prefer Unicode charsets
2572 charsetsMap.put(canonicalName("UTF-16LE"), Integer.valueOf(4));
2573 charsetsMap.put(canonicalName("UTF-16BE"), Integer.valueOf(5));
2574 charsetsMap.put(canonicalName("UTF-8"), Integer.valueOf(6));
2575 charsetsMap.put(canonicalName("UTF-16"), Integer.valueOf(7));
2576
2577 // US-ASCII is the worst charset supported
2578 charsetsMap.put(canonicalName("US-ASCII"), WORST_CHARSET_INDEX);
2579
2580 String defEncoding = DataTransferer.canonicalName
2581 (DataTransferer.getDefaultTextCharset());
2582
2583 if (charsetsMap.get(defaultEncoding) == null) {
2584 charsetsMap.put(defaultEncoding, DEFAULT_CHARSET_INDEX);
2585 }
2586 charsetsMap.put(UNSUPPORTED_CHARSET, UNSUPPORTED_CHARSET_INDEX);
2587
2588 charsets = Collections.unmodifiableMap(charsetsMap);
2589 }
2590
2591 public CharsetComparator() {
2592 this(SELECT_BEST);
2593 }
2594
2595 public CharsetComparator(boolean order) {
2596 super(order);
2597 }
2598
2599 /**
2600 * Compares two String objects. Returns a negative integer, zero,
2601 * or a positive integer as the first charset is worse than, equal to,
2602 * or better than the second.
2603 *
2604 * @param obj1 the first charset to be compared
2605 * @param obj2 the second charset to be compared
2606 * @return a negative integer, zero, or a positive integer as the
2607 * first argument is worse, equal to, or better than the
2608 * second.
2609 * @throws ClassCastException if either of the arguments is not
2610 * instance of String
2611 * @throws NullPointerException if either of the arguments is
2612 * <code>null</code>.
2613 */
2614 public int compare(Object obj1, Object obj2) {
2615 String charset1 = null;
2616 String charset2 = null;
2617 if (order == SELECT_BEST) {
2618 charset1 = (String)obj1;
2619 charset2 = (String)obj2;
2620 } else {
2621 charset1 = (String)obj2;
2622 charset2 = (String)obj1;
2623 }
2624
2625 return compareCharsets(charset1, charset2);
2626 }
2627
2628 /**
2629 * Compares charsets. Returns a negative integer, zero, or a positive
2630 * integer as the first charset is worse than, equal to, or better than
2631 * the second.
2632 * <p>
2633 * Charsets are ordered according to the following rules:
2634 * <ul>
2635 * <li>All unsupported charsets are equal.
2636 * <li>Any unsupported charset is worse than any supported charset.
2637 * <li>Unicode charsets, such as "UTF-16", "UTF-8", "UTF-16BE" and
2638 * "UTF-16LE", are considered best.
2639 * <li>After them, platform default charset is selected.
2640 * <li>"US-ASCII" is the worst of supported charsets.
2641 * <li>For all other supported charsets, the lexicographically less
2642 * one is considered the better.
2643 * </ul>
2644 *
2645 * @param charset1 the first charset to be compared
2646 * @param charset2 the second charset to be compared.
2647 * @return a negative integer, zero, or a positive integer as the
2648 * first argument is worse, equal to, or better than the
2649 * second.
2650 */
2651 protected int compareCharsets(String charset1, String charset2) {
2652 charset1 = getEncoding(charset1);
2653 charset2 = getEncoding(charset2);
2654
2655 int comp = compareIndices(charsets, charset1, charset2,
2656 OTHER_CHARSET_INDEX);
2657
2658 if (comp == 0) {
2659 return charset2.compareTo(charset1);
2660 }
2661
2662 return comp;
2663 }
2664
2665 /**
2666 * Returns encoding for the specified charset according to the
2667 * following rules:
2668 * <ul>
2669 * <li>If the charset is <code>null</code>, then <code>null</code> will
2670 * be returned.
2671 * <li>Iff the charset specifies an encoding unsupported by this JRE,
2672 * <code>UNSUPPORTED_CHARSET</code> will be returned.
2673 * <li>If the charset specifies an alias name, the corresponding
2674 * canonical name will be returned iff the charset is a known
2675 * Unicode, ASCII, or default charset.
2676 * </ul>
2677 *
2678 * @param charset the charset.
2679 * @return an encoding for this charset.
2680 */
2681 protected static String getEncoding(String charset) {
2682 if (charset == null) {
2683 return null;
2684 } else if (!DataTransferer.isEncodingSupported(charset)) {
2685 return UNSUPPORTED_CHARSET;
2686 } else {
2687 // Only convert to canonical form if the charset is one
2688 // of the charsets explicitly listed in the known charsets
2689 // map. This will happen only for Unicode, ASCII, or default
2690 // charsets.
2691 String canonicalName = DataTransferer.canonicalName(charset);
2692 return (charsets.containsKey(canonicalName))
2693 ? canonicalName
2694 : charset;
2695 }
2696 }
2697 }
2698
2699 /**
2700 * An IndexedComparator which compares two DataFlavors. For text flavors,
2701 * the comparison follows the rules outlined in
2702 * DataFlavor.selectBestTextFlavor. For non-text flavors, unknown
2703 * application MIME types are preferred, followed by known
2704 * application/x-java-* MIME types. Unknown application types are preferred
2705 * because if the user provides his own data flavor, it will likely be the
2706 * most descriptive one. For flavors which are otherwise equal, the
2707 * flavors' native formats are compared, with greater long values
2708 * taking precedence.
2709 */
2710 public static class DataFlavorComparator extends IndexedComparator {
2711 protected final Map flavorToFormatMap;
2712
2713 private final CharsetComparator charsetComparator;
2714
2715 private static final Map exactTypes;
2716 private static final Map primaryTypes;
2717 private static final Map nonTextRepresentations;
2718 private static final Map textTypes;
2719 private static final Map decodedTextRepresentations;
2720 private static final Map encodedTextRepresentations;
2721
2722 private static final Integer UNKNOWN_OBJECT_LOSES =
2723 Integer.valueOf(Integer.MIN_VALUE);
2724 private static final Integer UNKNOWN_OBJECT_WINS =
2725 Integer.valueOf(Integer.MAX_VALUE);
2726
2727 private static final Long UNKNOWN_OBJECT_LOSES_L =
2728 Long.valueOf(Long.MIN_VALUE);
2729 private static final Long UNKNOWN_OBJECT_WINS_L =
2730 Long.valueOf(Long.MAX_VALUE);
2731
2732 static {
2733 {
2734 HashMap exactTypesMap = new HashMap(4, 1.0f);
2735
2736 // application/x-java-* MIME types
2737 exactTypesMap.put("application/x-java-file-list",
2738 Integer.valueOf(0));
2739 exactTypesMap.put("application/x-java-serialized-object",
2740 Integer.valueOf(1));
2741 exactTypesMap.put("application/x-java-jvm-local-objectref",
2742 Integer.valueOf(2));
2743 exactTypesMap.put("application/x-java-remote-object",
2744 Integer.valueOf(3));
2745
2746 exactTypes = Collections.unmodifiableMap(exactTypesMap);
2747 }
2748
2749 {
2750 HashMap primaryTypesMap = new HashMap(1, 1.0f);
2751
2752 primaryTypesMap.put("application", Integer.valueOf(0));
2753
2754 primaryTypes = Collections.unmodifiableMap(primaryTypesMap);
2755 }
2756
2757 {
2758 HashMap nonTextRepresentationsMap = new HashMap(3, 1.0f);
2759
2760 nonTextRepresentationsMap.put(java.io.InputStream.class,
2761 Integer.valueOf(0));
2762 nonTextRepresentationsMap.put(java.io.Serializable.class,
2763 Integer.valueOf(1));
2764
2765 Class<?> remoteClass = RMI.remoteClass();
2766 if (remoteClass != null) {
2767 nonTextRepresentationsMap.put(remoteClass,
2768 Integer.valueOf(2));
2769 }
2770
2771 nonTextRepresentations =
2772 Collections.unmodifiableMap(nonTextRepresentationsMap);
2773 }
2774
2775 {
2776 HashMap textTypesMap = new HashMap(16, 1.0f);
2777
2778 // plain text
2779 textTypesMap.put("text/plain", Integer.valueOf(0));
2780
2781 // stringFlavor
2782 textTypesMap.put("application/x-java-serialized-object",
2783 Integer.valueOf(1));
2784
2785 // misc
2786 textTypesMap.put("text/calendar", Integer.valueOf(2));
2787 textTypesMap.put("text/css", Integer.valueOf(3));
2788 textTypesMap.put("text/directory", Integer.valueOf(4));
2789 textTypesMap.put("text/parityfec", Integer.valueOf(5));
2790 textTypesMap.put("text/rfc822-headers", Integer.valueOf(6));
2791 textTypesMap.put("text/t140", Integer.valueOf(7));
2792 textTypesMap.put("text/tab-separated-values", Integer.valueOf(8));
2793 textTypesMap.put("text/uri-list", Integer.valueOf(9));
2794
2795 // enriched
2796 textTypesMap.put("text/richtext", Integer.valueOf(10));
2797 textTypesMap.put("text/enriched", Integer.valueOf(11));
2798 textTypesMap.put("text/rtf", Integer.valueOf(12));
2799
2800 // markup
2801 textTypesMap.put("text/html", Integer.valueOf(13));
2802 textTypesMap.put("text/xml", Integer.valueOf(14));
2803 textTypesMap.put("text/sgml", Integer.valueOf(15));
2804
2805 textTypes = Collections.unmodifiableMap(textTypesMap);
2806 }
2807
2808 {
2809 HashMap decodedTextRepresentationsMap = new HashMap(4, 1.0f);
2810
2811 decodedTextRepresentationsMap.put
2812 (DataTransferer.charArrayClass, Integer.valueOf(0));
2813 decodedTextRepresentationsMap.put
2814 (java.nio.CharBuffer.class, Integer.valueOf(1));
2815 decodedTextRepresentationsMap.put
2816 (java.lang.String.class, Integer.valueOf(2));
2817 decodedTextRepresentationsMap.put
2818 (java.io.Reader.class, Integer.valueOf(3));
2819
2820 decodedTextRepresentations =
2821 Collections.unmodifiableMap(decodedTextRepresentationsMap);
2822 }
2823
2824 {
2825 HashMap encodedTextRepresentationsMap = new HashMap(3, 1.0f);
2826
2827 encodedTextRepresentationsMap.put
2828 (DataTransferer.byteArrayClass, Integer.valueOf(0));
2829 encodedTextRepresentationsMap.put
2830 (java.nio.ByteBuffer.class, Integer.valueOf(1));
2831 encodedTextRepresentationsMap.put
2832 (java.io.InputStream.class, Integer.valueOf(2));
2833
2834 encodedTextRepresentations =
2835 Collections.unmodifiableMap(encodedTextRepresentationsMap);
2836 }
2837 }
2838
2839 public DataFlavorComparator() {
2840 this(SELECT_BEST);
2841 }
2842
2843 public DataFlavorComparator(boolean order) {
2844 super(order);
2845
2846 charsetComparator = new CharsetComparator(order);
2847 flavorToFormatMap = Collections.EMPTY_MAP;
2848 }
2849
2850 public DataFlavorComparator(Map map) {
2851 this(map, SELECT_BEST);
2852 }
2853
2854 public DataFlavorComparator(Map map, boolean order) {
2855 super(order);
2856
2857 charsetComparator = new CharsetComparator(order);
2858 HashMap hashMap = new HashMap(map.size());
2859 hashMap.putAll(map);
2860 flavorToFormatMap = Collections.unmodifiableMap(hashMap);
2861 }
2862
2863 public int compare(Object obj1, Object obj2) {
2864 DataFlavor flavor1 = null;
2865 DataFlavor flavor2 = null;
2866 if (order == SELECT_BEST) {
2867 flavor1 = (DataFlavor)obj1;
2868 flavor2 = (DataFlavor)obj2;
2869 } else {
2870 flavor1 = (DataFlavor)obj2;
2871 flavor2 = (DataFlavor)obj1;
2872 }
2873
2874 if (flavor1.equals(flavor2)) {
2875 return 0;
2876 }
2877
2878 int comp = 0;
2879
2880 String primaryType1 = flavor1.getPrimaryType();
2881 String subType1 = flavor1.getSubType();
2882 String mimeType1 = primaryType1 + "/" + subType1;
2883 Class class1 = flavor1.getRepresentationClass();
2884
2885 String primaryType2 = flavor2.getPrimaryType();
2886 String subType2 = flavor2.getSubType();
2887 String mimeType2 = primaryType2 + "/" + subType2;
2888 Class class2 = flavor2.getRepresentationClass();
2889
2890 if (flavor1.isFlavorTextType() && flavor2.isFlavorTextType()) {
2891 // First, compare MIME types
2892 comp = compareIndices(textTypes, mimeType1, mimeType2,
2893 UNKNOWN_OBJECT_LOSES);
2894 if (comp != 0) {
2895 return comp;
2896 }
2897
2898 // Only need to test one flavor because they both have the
2899 // same MIME type. Also don't need to worry about accidentally
2900 // passing stringFlavor because either
2901 // 1. Both flavors are stringFlavor, in which case the
2902 // equality test at the top of the function succeeded.
2903 // 2. Only one flavor is stringFlavor, in which case the MIME
2904 // type comparison returned a non-zero value.
2905 if (doesSubtypeSupportCharset(flavor1)) {
2906 // Next, prefer the decoded text representations of Reader,
2907 // String, CharBuffer, and [C, in that order.
2908 comp = compareIndices(decodedTextRepresentations, class1,
2909 class2, UNKNOWN_OBJECT_LOSES);
2910 if (comp != 0) {
2911 return comp;
2912 }
2913
2914 // Next, compare charsets
2915 comp = charsetComparator.compareCharsets
2916 (DataTransferer.getTextCharset(flavor1),
2917 DataTransferer.getTextCharset(flavor2));
2918 if (comp != 0) {
2919 return comp;
2920 }
2921 }
2922
2923 // Finally, prefer the encoded text representations of
2924 // InputStream, ByteBuffer, and [B, in that order.
2925 comp = compareIndices(encodedTextRepresentations, class1,
2926 class2, UNKNOWN_OBJECT_LOSES);
2927 if (comp != 0) {
2928 return comp;
2929 }
2930 } else {
2931 // First, prefer application types.
2932 comp = compareIndices(primaryTypes, primaryType1, primaryType2,
2933 UNKNOWN_OBJECT_LOSES);
2934 if (comp != 0) {
2935 return comp;
2936 }
2937
2938 // Next, look for application/x-java-* types. Prefer unknown
2939 // MIME types because if the user provides his own data flavor,
2940 // it will likely be the most descriptive one.
2941 comp = compareIndices(exactTypes, mimeType1, mimeType2,
2942 UNKNOWN_OBJECT_WINS);
2943 if (comp != 0) {
2944 return comp;
2945 }
2946
2947 // Finally, prefer the representation classes of Remote,
2948 // Serializable, and InputStream, in that order.
2949 comp = compareIndices(nonTextRepresentations, class1, class2,
2950 UNKNOWN_OBJECT_LOSES);
2951 if (comp != 0) {
2952 return comp;
2953 }
2954 }
2955
2956 // As a last resort, take the DataFlavor with the greater integer
2957 // format.
2958 return compareLongs(flavorToFormatMap, flavor1, flavor2,
2959 UNKNOWN_OBJECT_LOSES_L);
2960 }
2961 }
2962
2963 /*
2964 * Given the Map that maps objects to Integer indices and a boolean value,
2965 * this Comparator imposes a direct or reverse order on set of objects.
2966 * <p>
2967 * If the specified boolean value is SELECT_BEST, the Comparator imposes the
2968 * direct index-based order: an object A is greater than an object B if and
2969 * only if the index of A is greater than the index of B. An object that
2970 * doesn't have an associated index is less or equal than any other object.
2971 * <p>
2972 * If the specified boolean value is SELECT_WORST, the Comparator imposes the
2973 * reverse index-based order: an object A is greater than an object B if and
2974 * only if A is less than B with the direct index-based order.
2975 */
2976 public static class IndexOrderComparator extends IndexedComparator {
2977 private final Map indexMap;
2978 private static final Integer FALLBACK_INDEX =
2979 Integer.valueOf(Integer.MIN_VALUE);
2980
2981 public IndexOrderComparator(Map indexMap) {
2982 super(SELECT_BEST);
2983 this.indexMap = indexMap;
2984 }
2985
2986 public IndexOrderComparator(Map indexMap, boolean order) {
2987 super(order);
2988 this.indexMap = indexMap;
2989 }
2990
2991 public int compare(Object obj1, Object obj2) {
2992 if (order == SELECT_WORST) {
2993 return -compareIndices(indexMap, obj1, obj2, FALLBACK_INDEX);
2994 } else {
2995 return compareIndices(indexMap, obj1, obj2, FALLBACK_INDEX);
2996 }
2997 }
2998 }
2999
3000 /**
3001 * A class that provides access to java.rmi.Remote and java.rmi.MarshalledObject
3002 * without creating a static dependency.
3003 */
3004 private static class RMI {
3005 private static final Class<?> remoteClass = getClass("java.rmi.Remote");
3006 private static final Class<?> marshallObjectClass =
3007 getClass("java.rmi.MarshalledObject");
3008 private static final Constructor<?> marshallCtor =
3009 getConstructor(marshallObjectClass, Object.class);
3010 private static final Method marshallGet =
3011 getMethod(marshallObjectClass, "get");
3012
3013 private static Class<?> getClass(String name) {
3014 try {
3015 return Class.forName(name, true, null);
3016 } catch (ClassNotFoundException e) {
3017 return null;
3018 }
3019 }
3020
3021 private static Constructor<?> getConstructor(Class<?> c, Class<?>... types) {
3022 try {
3023 return (c == null) ? null : c.getDeclaredConstructor(types);
3024 } catch (NoSuchMethodException x) {
3025 throw new AssertionError(x);
3026 }
3027 }
3028
3029 private static Method getMethod(Class<?> c, String name, Class<?>... types) {
3030 try {
3031 return (c == null) ? null : c.getMethod(name, types);
3032 } catch (NoSuchMethodException e) {
3033 throw new AssertionError(e);
3034 }
3035 }
3036
3037 /**
3038 * Returns {@code true} if the given class is java.rmi.Remote.
3039 */
3040 static boolean isRemote(Class<?> c) {
3041 return (remoteClass == null) ? null : remoteClass.isAssignableFrom(c);
3042 }
3043
3044 /**
3045 * Returns java.rmi.Remote.class if RMI is present; otherwise {@code null}.
3046 */
3047 static Class<?> remoteClass() {
3048 return remoteClass;
3049 }
3050
3051 /**
3052 * Returns a new MarshalledObject containing the serialized representation
3053 * of the given object.
3054 */
3055 static Object newMarshalledObject(Object obj) throws IOException {
3056 try {
3057 return marshallCtor.newInstance(obj);
3058 } catch (InstantiationException x) {
3059 throw new AssertionError(x);
3060 } catch (IllegalAccessException x) {
3061 throw new AssertionError(x);
3062 } catch (InvocationTargetException x) {
3063 Throwable cause = x.getCause();
3064 if (cause instanceof IOException)
3065 throw (IOException)cause;
3066 throw new AssertionError(x);
3067 }
3068 }
3069
3070 /**
3071 * Returns a new copy of the contained marshalled object.
3072 */
3073 static Object getMarshalledObject(Object obj)
3074 throws IOException, ClassNotFoundException
3075 {
3076 try {
3077 return marshallGet.invoke(obj);
3078 } catch (IllegalAccessException x) {
3079 throw new AssertionError(x);
3080 } catch (InvocationTargetException x) {
3081 Throwable cause = x.getCause();
3082 if (cause instanceof IOException)
3083 throw (IOException)cause;
3084 if (cause instanceof ClassNotFoundException)
3085 throw (ClassNotFoundException)cause;
3086 throw new AssertionError(x);
3087 }
3088 }
3089 }
3090}

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t