1 /*
   2  * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.awt.datatransfer;
  27 
  28 import java.awt.EventQueue;
  29 import java.awt.Graphics;
  30 import java.awt.Image;
  31 import java.awt.Toolkit;
  32 
  33 import java.awt.datatransfer.DataFlavor;
  34 import java.awt.datatransfer.FlavorMap;
  35 import java.awt.datatransfer.FlavorTable;
  36 import java.awt.datatransfer.Transferable;
  37 import java.awt.datatransfer.UnsupportedFlavorException;
  38 
  39 import java.io.BufferedReader;
  40 import java.io.ByteArrayInputStream;
  41 import java.io.ByteArrayOutputStream;
  42 import java.io.File;
  43 import java.io.InputStream;
  44 import java.io.InputStreamReader;
  45 import java.io.IOException;
  46 import java.io.ObjectInputStream;
  47 import java.io.ObjectOutputStream;
  48 import java.io.Reader;
  49 import java.io.SequenceInputStream;
  50 import java.io.StringReader;
  51 
  52 import java.net.URI;
  53 import java.net.URISyntaxException;
  54 
  55 import java.nio.ByteBuffer;
  56 import java.nio.CharBuffer;
  57 import java.nio.charset.Charset;
  58 import java.nio.charset.CharsetEncoder;
  59 import java.nio.charset.IllegalCharsetNameException;
  60 import java.nio.charset.StandardCharsets;
  61 import java.nio.charset.UnsupportedCharsetException;
  62 
  63 import java.lang.reflect.Constructor;
  64 import java.lang.reflect.Modifier;
  65 
  66 import java.security.AccessController;
  67 import java.security.PrivilegedAction;
  68 import java.security.PrivilegedActionException;
  69 import java.security.PrivilegedExceptionAction;
  70 import java.security.ProtectionDomain;
  71 
  72 import java.util.*;
  73 
  74 import sun.datatransfer.DataFlavorUtil;
  75 
  76 import sun.awt.AppContext;
  77 import sun.awt.ComponentFactory;
  78 import sun.awt.SunToolkit;
  79 
  80 import java.awt.image.BufferedImage;
  81 import java.awt.image.ImageObserver;
  82 import java.awt.image.RenderedImage;
  83 import java.awt.image.WritableRaster;
  84 import java.awt.image.ColorModel;
  85 
  86 import javax.imageio.ImageIO;
  87 import javax.imageio.ImageReader;
  88 import javax.imageio.ImageReadParam;
  89 import javax.imageio.ImageWriter;
  90 import javax.imageio.ImageTypeSpecifier;
  91 
  92 import javax.imageio.spi.ImageWriterSpi;
  93 
  94 import javax.imageio.stream.ImageInputStream;
  95 import javax.imageio.stream.ImageOutputStream;
  96 
  97 import sun.awt.image.ImageRepresentation;
  98 import sun.awt.image.ToolkitImage;
  99 
 100 import java.io.FilePermission;
 101 import java.util.stream.Stream;
 102 
 103 
 104 /**
 105  * Provides a set of functions to be shared among the DataFlavor class and
 106  * platform-specific data transfer implementations.
 107  *
 108  * The concept of "flavors" and "natives" is extended to include "formats",
 109  * which are the numeric values Win32 and X11 use to express particular data
 110  * types. Like FlavorMap, which provides getNativesForFlavors(DataFlavor[]) and
 111  * getFlavorsForNatives(String[]) functions, DataTransferer provides a set
 112  * of getFormatsFor(Transferable|Flavor|Flavors) and
 113  * getFlavorsFor(Format|Formats) functions.
 114  *
 115  * Also provided are functions for translating a Transferable into a byte
 116  * array, given a source DataFlavor and a target format, and for translating
 117  * a byte array or InputStream into an Object, given a source format and
 118  * a target DataFlavor.
 119  *
 120  * @author David Mendenhall
 121  * @author Danila Sinopalnikov
 122  *
 123  * @since 1.3.1
 124  */
 125 public abstract class DataTransferer {
 126     /**
 127      * The <code>DataFlavor</code> representing a Java text encoding String
 128      * encoded in UTF-8, where
 129      * <pre>
 130      *     representationClass = [B
 131      *     mimeType            = "application/x-java-text-encoding"
 132      * </pre>
 133      */
 134     public static final DataFlavor javaTextEncodingFlavor;
 135 
 136     /**
 137      * A collection of all natives listed in flavormap.properties with
 138      * a primary MIME type of "text".
 139      */
 140     private static final Set<Long> textNatives =
 141             Collections.synchronizedSet(new HashSet<>());
 142 
 143     /**
 144      * The native encodings/charsets for the Set of textNatives.
 145      */
 146     private static final Map<Long, String> nativeCharsets =
 147             Collections.synchronizedMap(new HashMap<>());
 148 
 149     /**
 150      * The end-of-line markers for the Set of textNatives.
 151      */
 152     private static final Map<Long, String> nativeEOLNs =
 153             Collections.synchronizedMap(new HashMap<>());
 154 
 155     /**
 156      * The number of terminating NUL bytes for the Set of textNatives.
 157      */
 158     private static final Map<Long, Integer> nativeTerminators =
 159             Collections.synchronizedMap(new HashMap<>());
 160 
 161     /**
 162      * The key used to store pending data conversion requests for an AppContext.
 163      */
 164     private static final String DATA_CONVERTER_KEY = "DATA_CONVERTER_KEY";
 165 
 166     static {
 167         DataFlavor tJavaTextEncodingFlavor = null;
 168         try {
 169             tJavaTextEncodingFlavor = new DataFlavor("application/x-java-text-encoding;class=\"[B\"");
 170         } catch (ClassNotFoundException cannotHappen) {
 171         }
 172         javaTextEncodingFlavor = tJavaTextEncodingFlavor;
 173     }
 174 
 175     /**
 176      * The accessor method for the singleton DataTransferer instance. Note
 177      * that in a headless environment, there may be no DataTransferer instance;
 178      * instead, null will be returned.
 179      */
 180     public static synchronized DataTransferer getInstance() {
 181         return ((ComponentFactory) Toolkit.getDefaultToolkit()).getDataTransferer();
 182     }
 183 
 184     /**
 185      * Converts a FlavorMap to a FlavorTable.
 186      */
 187     public static FlavorTable adaptFlavorMap(final FlavorMap map) {
 188         if (map instanceof FlavorTable) {
 189             return (FlavorTable)map;
 190         }
 191 
 192         return new FlavorTable() {
 193             @Override
 194             public Map<DataFlavor, String> getNativesForFlavors(DataFlavor[] flavors) {
 195                 return map.getNativesForFlavors(flavors);
 196             }
 197             @Override
 198             public Map<String, DataFlavor> getFlavorsForNatives(String[] natives) {
 199                 return map.getFlavorsForNatives(natives);
 200             }
 201             @Override
 202             public List<String> getNativesForFlavor(DataFlavor flav) {
 203                 Map<DataFlavor, String> natives = getNativesForFlavors(new DataFlavor[]{flav});
 204                 String nat = natives.get(flav);
 205                 if (nat != null) {
 206                     return Collections.singletonList(nat);
 207                 } else {
 208                     return Collections.emptyList();
 209                 }
 210             }
 211             @Override
 212             public List<DataFlavor> getFlavorsForNative(String nat) {
 213                 Map<String, DataFlavor> flavors = getFlavorsForNatives(new String[]{nat});
 214                 DataFlavor flavor = flavors.get(nat);
 215                 if (flavor != null) {
 216                     return Collections.singletonList(flavor);
 217                 } else {
 218                     return Collections.emptyList();
 219                 }
 220             }
 221         };
 222     }
 223 
 224     /**
 225      * Returns the default Unicode encoding for the platform. The encoding
 226      * need not be canonical. This method is only used by the archaic function
 227      * DataFlavor.getTextPlainUnicodeFlavor().
 228      */
 229     public abstract String getDefaultUnicodeEncoding();
 230 
 231     /**
 232      * This method is called for text flavor mappings established while parsing
 233      * the flavormap.properties file. It stores the "eoln" and "terminators"
 234      * parameters which are not officially part of the MIME type. They are
 235      * MIME parameters specific to the flavormap.properties file format.
 236      */
 237     public void registerTextFlavorProperties(String nat, String charset,
 238                                              String eoln, String terminators) {
 239         Long format = getFormatForNativeAsLong(nat);
 240 
 241         textNatives.add(format);
 242         nativeCharsets.put(format, (charset != null && charset.length() != 0)
 243                 ? charset : Charset.defaultCharset().name());
 244         if (eoln != null && eoln.length() != 0 && !eoln.equals("\n")) {
 245             nativeEOLNs.put(format, eoln);
 246         }
 247         if (terminators != null && terminators.length() != 0) {
 248             Integer iTerminators = Integer.valueOf(terminators);
 249             if (iTerminators > 0) {
 250                 nativeTerminators.put(format, iTerminators);
 251             }
 252         }
 253     }
 254 
 255     /**
 256      * Determines whether the native corresponding to the specified long format
 257      * was listed in the flavormap.properties file.
 258      */
 259     protected boolean isTextFormat(long format) {
 260         return textNatives.contains(Long.valueOf(format));
 261     }
 262 
 263     protected String getCharsetForTextFormat(Long lFormat) {
 264         return nativeCharsets.get(lFormat);
 265     }
 266 
 267     /**
 268      * Specifies whether text imported from the native system in the specified
 269      * format is locale-dependent. If so, when decoding such text,
 270      * 'nativeCharsets' should be ignored, and instead, the Transferable should
 271      * be queried for its javaTextEncodingFlavor data for the correct encoding.
 272      */
 273     public abstract boolean isLocaleDependentTextFormat(long format);
 274 
 275     /**
 276      * Determines whether the DataFlavor corresponding to the specified long
 277      * format is DataFlavor.javaFileListFlavor.
 278      */
 279     public abstract boolean isFileFormat(long format);
 280 
 281     /**
 282      * Determines whether the DataFlavor corresponding to the specified long
 283      * format is DataFlavor.imageFlavor.
 284      */
 285     public abstract boolean isImageFormat(long format);
 286 
 287     /**
 288      * Determines whether the format is a URI list we can convert to
 289      * a DataFlavor.javaFileListFlavor.
 290      */
 291     protected boolean isURIListFormat(long format) {
 292         return false;
 293     }
 294 
 295     /**
 296      * Returns a Map whose keys are all of the possible formats into which the
 297      * Transferable's transfer data flavors can be translated. The value of
 298      * each key is the DataFlavor in which the Transferable's data should be
 299      * requested when converting to the format.
 300      * <p>
 301      * The map keys are sorted according to the native formats preference
 302      * order.
 303      */
 304     public SortedMap<Long,DataFlavor> getFormatsForTransferable(Transferable contents,
 305                                                                 FlavorTable map)
 306     {
 307         DataFlavor[] flavors = contents.getTransferDataFlavors();
 308         if (flavors == null) {
 309             return Collections.emptySortedMap();
 310         }
 311         return getFormatsForFlavors(flavors, map);
 312     }
 313 
 314     /**
 315      * Returns a Map whose keys are all of the possible formats into which data
 316      * in the specified DataFlavors can be translated. The value of each key
 317      * is the DataFlavor in which the Transferable's data should be requested
 318      * when converting to the format.
 319      * <p>
 320      * The map keys are sorted according to the native formats preference
 321      * order.
 322      *
 323      * @param flavors the data flavors
 324      * @param map the FlavorTable which contains mappings between
 325      *            DataFlavors and data formats
 326      * @throws NullPointerException if flavors or map is <code>null</code>
 327      */
 328     public SortedMap<Long, DataFlavor> getFormatsForFlavors(DataFlavor[] flavors,
 329                                                             FlavorTable map)
 330     {
 331         Map<Long,DataFlavor> formatMap = new HashMap<>(flavors.length);
 332         Map<Long,DataFlavor> textPlainMap = new HashMap<>(flavors.length);
 333         // Maps formats to indices that will be used to sort the formats
 334         // according to the preference order.
 335         // Larger index value corresponds to the more preferable format.
 336         Map<Long, Integer> indexMap = new HashMap<>(flavors.length);
 337         Map<Long, Integer> textPlainIndexMap = new HashMap<>(flavors.length);
 338 
 339         int currentIndex = 0;
 340 
 341         // Iterate backwards so that preferred DataFlavors are used over
 342         // other DataFlavors. (See javadoc for
 343         // Transferable.getTransferDataFlavors.)
 344         for (int i = flavors.length - 1; i >= 0; i--) {
 345             DataFlavor flavor = flavors[i];
 346             if (flavor == null) continue;
 347 
 348             // Don't explicitly test for String, since it is just a special
 349             // case of Serializable
 350             if (flavor.isFlavorTextType() ||
 351                 flavor.isFlavorJavaFileListType() ||
 352                 DataFlavor.imageFlavor.equals(flavor) ||
 353                 flavor.isRepresentationClassSerializable() ||
 354                 flavor.isRepresentationClassInputStream() ||
 355                 flavor.isRepresentationClassRemote())
 356             {
 357                 List<String> natives = map.getNativesForFlavor(flavor);
 358 
 359                 currentIndex += natives.size();
 360 
 361                 for (String aNative : natives) {
 362                     Long lFormat = getFormatForNativeAsLong(aNative);
 363                     Integer index = currentIndex--;
 364 
 365                     formatMap.put(lFormat, flavor);
 366                     indexMap.put(lFormat, index);
 367 
 368                     // SystemFlavorMap.getNativesForFlavor will return
 369                     // text/plain natives for all text/*. While this is good
 370                     // for a single text/* flavor, we would prefer that
 371                     // text/plain native data come from a text/plain flavor.
 372                     if (("text".equals(flavor.getPrimaryType()) &&
 373                             "plain".equals(flavor.getSubType())) ||
 374                             flavor.equals(DataFlavor.stringFlavor)) {
 375                         textPlainMap.put(lFormat, flavor);
 376                         textPlainIndexMap.put(lFormat, index);
 377                     }
 378                 }
 379 
 380                 currentIndex += natives.size();
 381             }
 382         }
 383 
 384         formatMap.putAll(textPlainMap);
 385         indexMap.putAll(textPlainIndexMap);
 386 
 387         // Sort the map keys according to the formats preference order.
 388         Comparator<Long> comparator = DataFlavorUtil.getIndexOrderComparator(indexMap).reversed();
 389         SortedMap<Long, DataFlavor> sortedMap = new TreeMap<>(comparator);
 390         sortedMap.putAll(formatMap);
 391 
 392         return sortedMap;
 393     }
 394 
 395     /**
 396      * Reduces the Map output for the root function to an array of the
 397      * Map's keys.
 398      */
 399     public long[] getFormatsForTransferableAsArray(Transferable contents,
 400                                                    FlavorTable map) {
 401         return keysToLongArray(getFormatsForTransferable(contents, map));
 402     }
 403 
 404     /**
 405      * Returns a Map whose keys are all of the possible DataFlavors into which
 406      * data in the specified formats can be translated. The value of each key
 407      * is the format in which the Clipboard or dropped data should be requested
 408      * when converting to the DataFlavor.
 409      */
 410     public Map<DataFlavor, Long> getFlavorsForFormats(long[] formats, FlavorTable map) {
 411         Map<DataFlavor, Long> flavorMap = new HashMap<>(formats.length);
 412         Set<AbstractMap.SimpleEntry<Long, DataFlavor>> mappingSet = new HashSet<>(formats.length);
 413         Set<DataFlavor> flavorSet = new HashSet<>(formats.length);
 414 
 415         // First step: build flavorSet, mappingSet and initial flavorMap
 416         // flavorSet  - the set of all the DataFlavors into which
 417         //              data in the specified formats can be translated;
 418         // mappingSet - the set of all the mappings from the specified formats
 419         //              into any DataFlavor;
 420         // flavorMap  - after this step, this map maps each of the DataFlavors
 421         //              from flavorSet to any of the specified formats.
 422         for (long format : formats) {
 423             String nat = getNativeForFormat(format);
 424             List<DataFlavor> flavors = map.getFlavorsForNative(nat);
 425             for (DataFlavor flavor : flavors) {
 426                 // Don't explicitly test for String, since it is just a special
 427                 // case of Serializable
 428                 if (flavor.isFlavorTextType() ||
 429                         flavor.isFlavorJavaFileListType() ||
 430                         DataFlavor.imageFlavor.equals(flavor) ||
 431                         flavor.isRepresentationClassSerializable() ||
 432                         flavor.isRepresentationClassInputStream() ||
 433                         flavor.isRepresentationClassRemote()) {
 434 
 435                     AbstractMap.SimpleEntry<Long, DataFlavor> mapping =
 436                             new AbstractMap.SimpleEntry<>(format, flavor);
 437                     flavorMap.put(flavor, format);
 438                     mappingSet.add(mapping);
 439                     flavorSet.add(flavor);
 440                 }
 441             }
 442         }
 443 
 444         // Second step: for each DataFlavor try to figure out which of the
 445         // specified formats is the best to translate to this flavor.
 446         // Then map each flavor to the best format.
 447         // For the given flavor, FlavorTable indicates which native will
 448         // best reflect data in the specified flavor to the underlying native
 449         // platform. We assume that this native is the best to translate
 450         // to this flavor.
 451         // Note: FlavorTable allows one-way mappings, so we can occasionally
 452         // map a flavor to the format for which the corresponding
 453         // format-to-flavor mapping doesn't exist. For this reason we have built
 454         // a mappingSet of all format-to-flavor mappings for the specified formats
 455         // and check if the format-to-flavor mapping exists for the
 456         // (flavor,format) pair being added.
 457         for (DataFlavor flavor : flavorSet) {
 458             List<String> natives = map.getNativesForFlavor(flavor);
 459             for (String aNative : natives) {
 460                 Long lFormat = getFormatForNativeAsLong(aNative);
 461                 if (mappingSet.contains(new AbstractMap.SimpleEntry<>(lFormat, flavor))) {
 462                     flavorMap.put(flavor, lFormat);
 463                     break;
 464                 }
 465             }
 466         }
 467 
 468         return flavorMap;
 469     }
 470 
 471     /**
 472      * Returns a Set of all DataFlavors for which
 473      * 1) a mapping from at least one of the specified formats exists in the
 474      * specified map and
 475      * 2) the data translation for this mapping can be performed by the data
 476      * transfer subsystem.
 477      *
 478      * @param formats the data formats
 479      * @param map the FlavorTable which contains mappings between
 480      *            DataFlavors and data formats
 481      * @throws NullPointerException if formats or map is <code>null</code>
 482      */
 483     public Set<DataFlavor> getFlavorsForFormatsAsSet(long[] formats, FlavorTable map) {
 484         Set<DataFlavor> flavorSet = new HashSet<>(formats.length);
 485 
 486         for (long format : formats) {
 487             List<DataFlavor> flavors = map.getFlavorsForNative(getNativeForFormat(format));
 488             for (DataFlavor flavor : flavors) {
 489                 // Don't explicitly test for String, since it is just a special
 490                 // case of Serializable
 491                 if (flavor.isFlavorTextType() ||
 492                         flavor.isFlavorJavaFileListType() ||
 493                         DataFlavor.imageFlavor.equals(flavor) ||
 494                         flavor.isRepresentationClassSerializable() ||
 495                         flavor.isRepresentationClassInputStream() ||
 496                         flavor.isRepresentationClassRemote()) {
 497                     flavorSet.add(flavor);
 498                 }
 499             }
 500         }
 501 
 502         return flavorSet;
 503     }
 504 
 505     /**
 506      * Returns an array of all DataFlavors for which
 507      * 1) a mapping from at least one of the specified formats exists in the
 508      * specified map and
 509      * 2) the data translation for this mapping can be performed by the data
 510      * transfer subsystem.
 511      * The array will be sorted according to a
 512      * <code>DataFlavorComparator</code> created with the specified
 513      * map as an argument.
 514      *
 515      * @param formats the data formats
 516      * @param map the FlavorTable which contains mappings between
 517      *            DataFlavors and data formats
 518      * @throws NullPointerException if formats or map is <code>null</code>
 519      */
 520     public DataFlavor[] getFlavorsForFormatsAsArray(long[] formats,
 521                                                     FlavorTable map) {
 522         // getFlavorsForFormatsAsSet() is less expensive than
 523         // getFlavorsForFormats().
 524         return setToSortedDataFlavorArray(getFlavorsForFormatsAsSet(formats, map));
 525     }
 526 
 527     /**
 528      * Looks-up or registers the String native with the native data transfer
 529      * system and returns a long format corresponding to that native.
 530      */
 531     protected abstract Long getFormatForNativeAsLong(String str);
 532 
 533     /**
 534      * Looks-up the String native corresponding to the specified long format in
 535      * the native data transfer system.
 536      */
 537     protected abstract String getNativeForFormat(long format);
 538 
 539     /* Contains common code for finding the best charset for
 540      * clipboard string encoding/decoding, basing on clipboard
 541      * format and localeTransferable(on decoding, if available)
 542      */
 543     protected String getBestCharsetForTextFormat(Long lFormat,
 544         Transferable localeTransferable) throws IOException
 545     {
 546         String charset = null;
 547         if (localeTransferable != null &&
 548             isLocaleDependentTextFormat(lFormat) &&
 549             localeTransferable.isDataFlavorSupported(javaTextEncodingFlavor)) {
 550             try {
 551                 byte[] charsetNameBytes = (byte[])localeTransferable
 552                         .getTransferData(javaTextEncodingFlavor);
 553                 charset = new String(charsetNameBytes, StandardCharsets.UTF_8);
 554             } catch (UnsupportedFlavorException cannotHappen) {
 555             }
 556         } else {
 557             charset = getCharsetForTextFormat(lFormat);
 558         }
 559         if (charset == null) {
 560             // Only happens when we have a custom text type.
 561             charset = Charset.defaultCharset().name();
 562         }
 563         return charset;
 564     }
 565 
 566     /**
 567      *  Translation function for converting string into
 568      *  a byte array. Search-and-replace EOLN. Encode into the
 569      *  target format. Append terminating NUL bytes.
 570      *
 571      *  Java to Native string conversion
 572      */
 573     private byte[] translateTransferableString(String str,
 574                                                long format) throws IOException
 575     {
 576         Long lFormat = format;
 577         String charset = getBestCharsetForTextFormat(lFormat, null);
 578         // Search and replace EOLN. Note that if EOLN is "\n", then we
 579         // never added an entry to nativeEOLNs anyway, so we'll skip this
 580         // code altogether.
 581         // windows: "abc\nde"->"abc\r\nde"
 582         String eoln = nativeEOLNs.get(lFormat);
 583         if (eoln != null) {
 584             int length = str.length();
 585             StringBuilder buffer = new StringBuilder(length * 2); // 2 is a heuristic
 586             for (int i = 0; i < length; i++) {
 587                 // Fix for 4914613 - skip native EOLN
 588                 if (str.startsWith(eoln, i)) {
 589                     buffer.append(eoln);
 590                     i += eoln.length() - 1;
 591                     continue;
 592                 }
 593                 char c = str.charAt(i);
 594                 if (c == '\n') {
 595                     buffer.append(eoln);
 596                 } else {
 597                     buffer.append(c);
 598                 }
 599             }
 600             str = buffer.toString();
 601         }
 602 
 603         // Encode text in target format.
 604         byte[] bytes = str.getBytes(charset);
 605 
 606         // Append terminating NUL bytes. Note that if terminators is 0,
 607         // the we never added an entry to nativeTerminators anyway, so
 608         // we'll skip code altogether.
 609         // "abcde" -> "abcde\0"
 610         Integer terminators = nativeTerminators.get(lFormat);
 611         if (terminators != null) {
 612             int numTerminators = terminators;
 613             byte[] terminatedBytes =
 614                 new byte[bytes.length + numTerminators];
 615             System.arraycopy(bytes, 0, terminatedBytes, 0, bytes.length);
 616             for (int i = bytes.length; i < terminatedBytes.length; i++) {
 617                 terminatedBytes[i] = 0x0;
 618             }
 619             bytes = terminatedBytes;
 620         }
 621         return bytes;
 622     }
 623 
 624     /**
 625      * Translating either a byte array or an InputStream into an String.
 626      * Strip terminators and search-and-replace EOLN.
 627      *
 628      * Native to Java string conversion
 629      */
 630     private String translateBytesToString(byte[] bytes, long format,
 631                                           Transferable localeTransferable)
 632             throws IOException
 633     {
 634 
 635         Long lFormat = format;
 636         String charset = getBestCharsetForTextFormat(lFormat, localeTransferable);
 637 
 638         // Locate terminating NUL bytes. Note that if terminators is 0,
 639         // the we never added an entry to nativeTerminators anyway, so
 640         // we'll skip code altogether.
 641 
 642         // In other words: we are doing char alignment here basing on suggestion
 643         // that count of zero-'terminators' is a number of bytes in one symbol
 644         // for selected charset (clipboard format). It is not complitly true for
 645         // multibyte coding like UTF-8, but helps understand the procedure.
 646         // "abcde\0" -> "abcde"
 647 
 648         String eoln = nativeEOLNs.get(lFormat);
 649         Integer terminators = nativeTerminators.get(lFormat);
 650         int count;
 651         if (terminators != null) {
 652             int numTerminators = terminators;
 653 search:
 654             for (count = 0; count < (bytes.length - numTerminators + 1); count += numTerminators) {
 655                 for (int i = count; i < count + numTerminators; i++) {
 656                     if (bytes[i] != 0x0) {
 657                         continue search;
 658                     }
 659                 }
 660                 // found terminators
 661                 break search;
 662             }
 663         } else {
 664             count = bytes.length;
 665         }
 666 
 667         // Decode text to chars. Don't include any terminators.
 668         String converted = new String(bytes, 0, count, charset);
 669 
 670         // Search and replace EOLN. Note that if EOLN is "\n", then we
 671         // never added an entry to nativeEOLNs anyway, so we'll skip this
 672         // code altogether.
 673         // Count of NUL-terminators and EOLN coding are platform-specific and
 674         // loaded from flavormap.properties file
 675         // windows: "abc\r\nde" -> "abc\nde"
 676 
 677         if (eoln != null) {
 678 
 679             /* Fix for 4463560: replace EOLNs symbol-by-symbol instead
 680              * of using buf.replace()
 681              */
 682 
 683             char[] buf = converted.toCharArray();
 684             char[] eoln_arr = eoln.toCharArray();
 685             int j = 0;
 686             boolean match;
 687 
 688             for (int i = 0; i < buf.length; ) {
 689                 // Catch last few bytes
 690                 if (i + eoln_arr.length > buf.length) {
 691                     buf[j++] = buf[i++];
 692                     continue;
 693                 }
 694 
 695                 match = true;
 696                 for (int k = 0, l = i; k < eoln_arr.length; k++, l++) {
 697                     if (eoln_arr[k] != buf[l]) {
 698                         match = false;
 699                         break;
 700                     }
 701                 }
 702                 if (match) {
 703                     buf[j++] = '\n';
 704                     i += eoln_arr.length;
 705                 } else {
 706                     buf[j++] = buf[i++];
 707                 }
 708             }
 709             converted = new String(buf, 0, j);
 710         }
 711 
 712         return converted;
 713     }
 714 
 715 
 716     /**
 717      * Primary translation function for translating a Transferable into
 718      * a byte array, given a source DataFlavor and target format.
 719      */
 720     public byte[] translateTransferable(Transferable contents,
 721                                         DataFlavor flavor,
 722                                         long format) throws IOException
 723     {
 724         // Obtain the transfer data in the source DataFlavor.
 725         //
 726         // Note that we special case DataFlavor.plainTextFlavor because
 727         // StringSelection supports this flavor incorrectly -- instead of
 728         // returning an InputStream as the DataFlavor representation class
 729         // states, it returns a Reader. Instead of using this broken
 730         // functionality, we request the data in stringFlavor (the other
 731         // DataFlavor which StringSelection supports) and use the String
 732         // translator.
 733         Object obj;
 734         boolean stringSelectionHack;
 735         try {
 736             obj = contents.getTransferData(flavor);
 737             if (obj == null) {
 738                 return null;
 739             }
 740             if (flavor.equals(DataFlavor.plainTextFlavor) &&
 741                 !(obj instanceof InputStream))
 742             {
 743                 obj = contents.getTransferData(DataFlavor.stringFlavor);
 744                 if (obj == null) {
 745                     return null;
 746                 }
 747                 stringSelectionHack = true;
 748             } else {
 749                 stringSelectionHack = false;
 750             }
 751         } catch (UnsupportedFlavorException e) {
 752             throw new IOException(e.getMessage());
 753         }
 754 
 755         // Source data is a String. Search-and-replace EOLN. Encode into the
 756         // target format. Append terminating NUL bytes.
 757         if (stringSelectionHack ||
 758             (String.class.equals(flavor.getRepresentationClass()) &&
 759              DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
 760 
 761             String str = removeSuspectedData(flavor, contents, (String)obj);
 762 
 763             return translateTransferableString(
 764                 str,
 765                 format);
 766 
 767         // Source data is a Reader. Convert to a String and recur. In the
 768         // future, we may want to rewrite this so that we encode on demand.
 769         } else if (flavor.isRepresentationClassReader()) {
 770             if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
 771                 throw new IOException
 772                     ("cannot transfer non-text data as Reader");
 773             }
 774 
 775             StringBuilder buf = new StringBuilder();
 776             try (Reader r = (Reader)obj) {
 777                 int c;
 778                 while ((c = r.read()) != -1) {
 779                     buf.append((char)c);
 780                 }
 781             }
 782 
 783             return translateTransferableString(
 784                 buf.toString(),
 785                 format);
 786 
 787         // Source data is a CharBuffer. Convert to a String and recur.
 788         } else if (flavor.isRepresentationClassCharBuffer()) {
 789             if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
 790                 throw new IOException
 791                     ("cannot transfer non-text data as CharBuffer");
 792             }
 793 
 794             CharBuffer buffer = (CharBuffer)obj;
 795             int size = buffer.remaining();
 796             char[] chars = new char[size];
 797             buffer.get(chars, 0, size);
 798 
 799             return translateTransferableString(
 800                 new String(chars),
 801                 format);
 802 
 803         // Source data is a char array. Convert to a String and recur.
 804         } else if (char[].class.equals(flavor.getRepresentationClass())) {
 805             if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
 806                 throw new IOException
 807                     ("cannot transfer non-text data as char array");
 808             }
 809 
 810             return translateTransferableString(
 811                 new String((char[])obj),
 812                 format);
 813 
 814         // Source data is a ByteBuffer. For arbitrary flavors, simply return
 815         // the array. For text flavors, decode back to a String and recur to
 816         // reencode according to the requested format.
 817         } else if (flavor.isRepresentationClassByteBuffer()) {
 818             ByteBuffer buffer = (ByteBuffer)obj;
 819             int size = buffer.remaining();
 820             byte[] bytes = new byte[size];
 821             buffer.get(bytes, 0, size);
 822 
 823             if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
 824                 String sourceEncoding = DataFlavorUtil.getTextCharset(flavor);
 825                 return translateTransferableString(
 826                     new String(bytes, sourceEncoding),
 827                     format);
 828             } else {
 829                 return bytes;
 830             }
 831 
 832         // Source data is a byte array. For arbitrary flavors, simply return
 833         // the array. For text flavors, decode back to a String and recur to
 834         // reencode according to the requested format.
 835         } else if (byte[].class.equals(flavor.getRepresentationClass())) {
 836             byte[] bytes = (byte[])obj;
 837 
 838             if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
 839                 String sourceEncoding = DataFlavorUtil.getTextCharset(flavor);
 840                 return translateTransferableString(
 841                     new String(bytes, sourceEncoding),
 842                     format);
 843             } else {
 844                 return bytes;
 845             }
 846         // Source data is Image
 847         } else if (DataFlavor.imageFlavor.equals(flavor)) {
 848             if (!isImageFormat(format)) {
 849                 throw new IOException("Data translation failed: " +
 850                                       "not an image format");
 851             }
 852 
 853             Image image = (Image)obj;
 854             byte[] bytes = imageToPlatformBytes(image, format);
 855 
 856             if (bytes == null) {
 857                 throw new IOException("Data translation failed: " +
 858                     "cannot convert java image to native format");
 859             }
 860             return bytes;
 861         }
 862 
 863         byte[] theByteArray = null;
 864 
 865         // Target data is a file list. Source data must be a
 866         // java.util.List which contains java.io.File or String instances.
 867         if (isFileFormat(format)) {
 868             if (!DataFlavor.javaFileListFlavor.equals(flavor)) {
 869                 throw new IOException("data translation failed");
 870             }
 871 
 872             final List<?> list = (List<?>)obj;
 873 
 874             final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
 875 
 876             final ArrayList<String> fileList = castToFiles(list, userProtectionDomain);
 877 
 878             try (ByteArrayOutputStream bos = convertFileListToBytes(fileList)) {
 879                 theByteArray = bos.toByteArray();
 880             }
 881 
 882         // Target data is a URI list. Source data must be a
 883         // java.util.List which contains java.io.File or String instances.
 884         } else if (isURIListFormat(format)) {
 885             if (!DataFlavor.javaFileListFlavor.equals(flavor)) {
 886                 throw new IOException("data translation failed");
 887             }
 888             String nat = getNativeForFormat(format);
 889             String targetCharset = null;
 890             if (nat != null) {
 891                 try {
 892                     targetCharset = new DataFlavor(nat).getParameter("charset");
 893                 } catch (ClassNotFoundException cnfe) {
 894                     throw new IOException(cnfe);
 895                 }
 896             }
 897             if (targetCharset == null) {
 898                 targetCharset = "UTF-8";
 899             }
 900             final List<?> list = (List<?>)obj;
 901             final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
 902             final ArrayList<String> fileList = castToFiles(list, userProtectionDomain);
 903             final ArrayList<String> uriList = new ArrayList<>(fileList.size());
 904             for (String fileObject : fileList) {
 905                 final URI uri = new File(fileObject).toURI();
 906                 // Some implementations are fussy about the number of slashes (file:///path/to/file is best)
 907                 try {
 908                     uriList.add(new URI(uri.getScheme(), "", uri.getPath(), uri.getFragment()).toString());
 909                 } catch (URISyntaxException uriSyntaxException) {
 910                     throw new IOException(uriSyntaxException);
 911                   }
 912               }
 913 
 914             byte[] eoln = "\r\n".getBytes(targetCharset);
 915 
 916             try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
 917                 for (String uri : uriList) {
 918                     byte[] bytes = uri.getBytes(targetCharset);
 919                     bos.write(bytes, 0, bytes.length);
 920                     bos.write(eoln, 0, eoln.length);
 921                 }
 922                 theByteArray = bos.toByteArray();
 923             }
 924 
 925         // Source data is an InputStream. For arbitrary flavors, just grab the
 926         // bytes and dump them into a byte array. For text flavors, decode back
 927         // to a String and recur to reencode according to the requested format.
 928         } else if (flavor.isRepresentationClassInputStream()) {
 929             try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
 930                 try (InputStream is = (InputStream)obj) {
 931                     boolean eof = false;
 932                     int avail = is.available();
 933                     byte[] tmp = new byte[avail > 8192 ? avail : 8192];
 934                     do {
 935                         int aValue;
 936                         if (!(eof = (aValue = is.read(tmp, 0, tmp.length)) == -1)) {
 937                             bos.write(tmp, 0, aValue);
 938                         }
 939                     } while (!eof);
 940                 }
 941 
 942                 if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
 943                     byte[] bytes = bos.toByteArray();
 944                     String sourceEncoding = DataFlavorUtil.getTextCharset(flavor);
 945                     return translateTransferableString(
 946                                new String(bytes, sourceEncoding),
 947                                format);
 948                 }
 949                 theByteArray = bos.toByteArray();
 950             }
 951 
 952 
 953         // Source data is an RMI object
 954         } else if (flavor.isRepresentationClassRemote()) {
 955             theByteArray = convertObjectToBytes(DataFlavorUtil.RMI.newMarshalledObject(obj));
 956 
 957         // Source data is Serializable
 958         } else if (flavor.isRepresentationClassSerializable()) {
 959 
 960             theByteArray = convertObjectToBytes(obj);
 961 
 962         } else {
 963             throw new IOException("data translation failed");
 964         }
 965 
 966 
 967 
 968         return theByteArray;
 969     }
 970 
 971     private static byte[] convertObjectToBytes(Object object) throws IOException {
 972         try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
 973              ObjectOutputStream oos = new ObjectOutputStream(bos))
 974         {
 975             oos.writeObject(object);
 976             return bos.toByteArray();
 977         }
 978     }
 979 
 980     protected abstract ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList) throws IOException;
 981 
 982     private String removeSuspectedData(DataFlavor flavor, final Transferable contents, final String str)
 983             throws IOException
 984     {
 985         if (null == System.getSecurityManager()
 986             || !flavor.isMimeTypeEqual("text/uri-list"))
 987         {
 988             return str;
 989         }
 990 
 991         final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
 992 
 993         try {
 994             return AccessController.doPrivileged((PrivilegedExceptionAction<String>) () -> {
 995 
 996                 StringBuilder allowedFiles = new StringBuilder(str.length());
 997                 String [] uriArray = str.split("(\\s)+");
 998 
 999                 for (String fileName : uriArray)
1000                 {
1001                     File file = new File(fileName);
1002                     if (file.exists() &&
1003                         !(isFileInWebstartedCache(file) ||
1004                         isForbiddenToRead(file, userProtectionDomain)))
1005                     {
1006                         if (0 != allowedFiles.length())
1007                         {
1008                             allowedFiles.append("\\r\\n");
1009                         }
1010 
1011                         allowedFiles.append(fileName);
1012                     }
1013                 }
1014 
1015                 return allowedFiles.toString();
1016             });
1017         } catch (PrivilegedActionException pae) {
1018             throw new IOException(pae.getMessage(), pae);
1019         }
1020     }
1021 
1022     private static ProtectionDomain getUserProtectionDomain(Transferable contents) {
1023         return contents.getClass().getProtectionDomain();
1024     }
1025 
1026     private boolean isForbiddenToRead (File file, ProtectionDomain protectionDomain)
1027     {
1028         if (null == protectionDomain) {
1029             return false;
1030         }
1031         try {
1032             FilePermission filePermission =
1033                     new FilePermission(file.getCanonicalPath(), "read, delete");
1034             if (protectionDomain.implies(filePermission)) {
1035                 return false;
1036             }
1037         } catch (IOException e) {}
1038 
1039         return true;
1040     }
1041 
1042     private ArrayList<String> castToFiles(final List<?> files,
1043                                           final ProtectionDomain userProtectionDomain) throws IOException {
1044         try {
1045             return AccessController.doPrivileged((PrivilegedExceptionAction<ArrayList<String>>) () -> {
1046                 ArrayList<String> fileList = new ArrayList<>();
1047                 for (Object fileObject : files)
1048                 {
1049                     File file = castToFile(fileObject);
1050                     if (file != null &&
1051                         (null == System.getSecurityManager() ||
1052                         !(isFileInWebstartedCache(file) ||
1053                         isForbiddenToRead(file, userProtectionDomain))))
1054                     {
1055                         fileList.add(file.getCanonicalPath());
1056                     }
1057                 }
1058                 return fileList;
1059             });
1060         } catch (PrivilegedActionException pae) {
1061             throw new IOException(pae.getMessage());
1062         }
1063     }
1064 
1065     // It is important do not use user's successors
1066     // of File class.
1067     private File castToFile(Object fileObject) throws IOException {
1068         String filePath = null;
1069         if (fileObject instanceof File) {
1070             filePath = ((File)fileObject).getCanonicalPath();
1071         } else if (fileObject instanceof String) {
1072            filePath = (String) fileObject;
1073         } else {
1074            return null;
1075         }
1076         return new File(filePath);
1077     }
1078 
1079     private final static String[] DEPLOYMENT_CACHE_PROPERTIES = {
1080         "deployment.system.cachedir",
1081         "deployment.user.cachedir",
1082         "deployment.javaws.cachedir",
1083         "deployment.javapi.cachedir"
1084     };
1085 
1086     private final static ArrayList <File> deploymentCacheDirectoryList = new ArrayList<>();
1087 
1088     private static boolean isFileInWebstartedCache(File f) {
1089 
1090         if (deploymentCacheDirectoryList.isEmpty()) {
1091             for (String cacheDirectoryProperty : DEPLOYMENT_CACHE_PROPERTIES) {
1092                 String cacheDirectoryPath = System.getProperty(cacheDirectoryProperty);
1093                 if (cacheDirectoryPath != null) {
1094                     try {
1095                         File cacheDirectory = (new File(cacheDirectoryPath)).getCanonicalFile();
1096                         if (cacheDirectory != null) {
1097                             deploymentCacheDirectoryList.add(cacheDirectory);
1098                         }
1099                     } catch (IOException ioe) {}
1100                 }
1101             }
1102         }
1103 
1104         for (File deploymentCacheDirectory : deploymentCacheDirectoryList) {
1105             for (File dir = f; dir != null; dir = dir.getParentFile()) {
1106                 if (dir.equals(deploymentCacheDirectory)) {
1107                     return true;
1108                 }
1109             }
1110         }
1111 
1112         return false;
1113     }
1114 
1115 
1116     public Object translateBytes(byte[] bytes, DataFlavor flavor,
1117                                  long format, Transferable localeTransferable)
1118         throws IOException
1119     {
1120 
1121         Object theObject = null;
1122 
1123         // Source data is a file list. Use the dragQueryFile native function to
1124         // do most of the decoding. Then wrap File objects around the String
1125         // filenames and return a List.
1126         if (isFileFormat(format)) {
1127             if (!DataFlavor.javaFileListFlavor.equals(flavor)) {
1128                 throw new IOException("data translation failed");
1129             }
1130             String[] filenames = dragQueryFile(bytes);
1131             if (filenames == null) {
1132                 return null;
1133             }
1134 
1135             // Convert the strings to File objects
1136             File[] files = new File[filenames.length];
1137             for (int i = 0; i < filenames.length; i++) {
1138                 files[i] = new File(filenames[i]);
1139             }
1140 
1141             // Turn the list of Files into a List and return
1142             theObject = Arrays.asList(files);
1143 
1144             // Source data is a URI list. Convert to DataFlavor.javaFileListFlavor
1145             // where possible.
1146         } else if (isURIListFormat(format)
1147                     && DataFlavor.javaFileListFlavor.equals(flavor)) {
1148 
1149             try (ByteArrayInputStream str = new ByteArrayInputStream(bytes))  {
1150 
1151                 URI uris[] = dragQueryURIs(str, format, localeTransferable);
1152                 if (uris == null) {
1153                     return null;
1154                 }
1155                 List<File> files = new ArrayList<>();
1156                 for (URI uri : uris) {
1157                     try {
1158                         files.add(new File(uri));
1159                     } catch (IllegalArgumentException illegalArg) {
1160                         // When converting from URIs to less generic files,
1161                         // common practice (Wine, SWT) seems to be to
1162                         // silently drop the URIs that aren't local files.
1163                     }
1164                 }
1165                 theObject = files;
1166             }
1167 
1168             // Target data is a String. Strip terminating NUL bytes. Decode bytes
1169             // into characters. Search-and-replace EOLN.
1170         } else if (String.class.equals(flavor.getRepresentationClass()) &&
1171                    DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1172 
1173             theObject = translateBytesToString(bytes, format, localeTransferable);
1174 
1175             // Target data is a Reader. Obtain data in InputStream format, encoded
1176             // as "Unicode" (utf-16be). Then use an InputStreamReader to decode
1177             // back to chars on demand.
1178         } else if (flavor.isRepresentationClassReader()) {
1179             try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) {
1180                 theObject = translateStream(bais,
1181                         flavor, format, localeTransferable);
1182             }
1183             // Target data is a CharBuffer. Recur to obtain String and wrap.
1184         } else if (flavor.isRepresentationClassCharBuffer()) {
1185             if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1186                 throw new IOException("cannot transfer non-text data as CharBuffer");
1187             }
1188 
1189             CharBuffer buffer = CharBuffer.wrap(
1190                 translateBytesToString(bytes,format, localeTransferable));
1191 
1192             theObject = constructFlavoredObject(buffer, flavor, CharBuffer.class);
1193 
1194             // Target data is a char array. Recur to obtain String and convert to
1195             // char array.
1196         } else if (char[].class.equals(flavor.getRepresentationClass())) {
1197             if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1198                 throw new IOException
1199                           ("cannot transfer non-text data as char array");
1200             }
1201 
1202             theObject = translateBytesToString(
1203                 bytes, format, localeTransferable).toCharArray();
1204 
1205             // Target data is a ByteBuffer. For arbitrary flavors, just return
1206             // the raw bytes. For text flavors, convert to a String to strip
1207             // terminators and search-and-replace EOLN, then reencode according to
1208             // the requested flavor.
1209         } else if (flavor.isRepresentationClassByteBuffer()) {
1210             if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1211                 bytes = translateBytesToString(
1212                     bytes, format, localeTransferable).getBytes(
1213                         DataFlavorUtil.getTextCharset(flavor)
1214                     );
1215             }
1216 
1217             ByteBuffer buffer = ByteBuffer.wrap(bytes);
1218             theObject = constructFlavoredObject(buffer, flavor, ByteBuffer.class);
1219 
1220             // Target data is a byte array. For arbitrary flavors, just return
1221             // the raw bytes. For text flavors, convert to a String to strip
1222             // terminators and search-and-replace EOLN, then reencode according to
1223             // the requested flavor.
1224         } else if (byte[].class.equals(flavor.getRepresentationClass())) {
1225             if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1226                 theObject = translateBytesToString(
1227                     bytes, format, localeTransferable
1228                 ).getBytes(DataFlavorUtil.getTextCharset(flavor));
1229             } else {
1230                 theObject = bytes;
1231             }
1232 
1233             // Target data is an InputStream. For arbitrary flavors, just return
1234             // the raw bytes. For text flavors, decode to strip terminators and
1235             // search-and-replace EOLN, then reencode according to the requested
1236             // flavor.
1237         } else if (flavor.isRepresentationClassInputStream()) {
1238 
1239             try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) {
1240                 theObject = translateStream(bais, flavor, format, localeTransferable);
1241             }
1242 
1243         } else if (flavor.isRepresentationClassRemote()) {
1244             try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
1245                  ObjectInputStream ois = new ObjectInputStream(bais)) {
1246 
1247                 theObject = DataFlavorUtil.RMI.getMarshalledObject(ois.readObject());
1248             } catch (Exception e) {
1249                 throw new IOException(e.getMessage());
1250             }
1251 
1252             // Target data is Serializable
1253         } else if (flavor.isRepresentationClassSerializable()) {
1254 
1255             try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) {
1256                 theObject = translateStream(bais, flavor, format, localeTransferable);
1257             }
1258 
1259             // Target data is Image
1260         } else if (DataFlavor.imageFlavor.equals(flavor)) {
1261             if (!isImageFormat(format)) {
1262                 throw new IOException("data translation failed");
1263             }
1264 
1265             theObject = platformImageBytesToImage(bytes, format);
1266         }
1267 
1268         if (theObject == null) {
1269             throw new IOException("data translation failed");
1270         }
1271 
1272         return theObject;
1273 
1274     }
1275 
1276     /**
1277      * Primary translation function for translating
1278      * an InputStream into an Object, given a source format and a target
1279      * DataFlavor.
1280      */
1281     public Object translateStream(InputStream str, DataFlavor flavor,
1282                                   long format, Transferable localeTransferable)
1283         throws IOException
1284     {
1285 
1286         Object theObject = null;
1287         // Source data is a URI list. Convert to DataFlavor.javaFileListFlavor
1288         // where possible.
1289         if (isURIListFormat(format)
1290                 && DataFlavor.javaFileListFlavor.equals(flavor))
1291         {
1292 
1293             URI uris[] = dragQueryURIs(str, format, localeTransferable);
1294             if (uris == null) {
1295                 return null;
1296             }
1297             List<File> files = new ArrayList<>();
1298             for (URI uri : uris) {
1299                 try {
1300                     files.add(new File(uri));
1301                 } catch (IllegalArgumentException illegalArg) {
1302                     // When converting from URIs to less generic files,
1303                     // common practice (Wine, SWT) seems to be to
1304                     // silently drop the URIs that aren't local files.
1305                 }
1306             }
1307             theObject = files;
1308 
1309         // Target data is a String. Strip terminating NUL bytes. Decode bytes
1310         // into characters. Search-and-replace EOLN.
1311         } else if (String.class.equals(flavor.getRepresentationClass()) &&
1312                    DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1313 
1314             return translateBytesToString(inputStreamToByteArray(str),
1315                 format, localeTransferable);
1316 
1317             // Special hack to maintain backwards-compatibility with the brokenness
1318             // of StringSelection. Return a StringReader instead of an InputStream.
1319             // Recur to obtain String and encapsulate.
1320         } else if (DataFlavor.plainTextFlavor.equals(flavor)) {
1321             theObject = new StringReader(translateBytesToString(
1322                 inputStreamToByteArray(str),
1323                 format, localeTransferable));
1324 
1325             // Target data is an InputStream. For arbitrary flavors, just return
1326             // the raw bytes. For text flavors, decode to strip terminators and
1327             // search-and-replace EOLN, then reencode according to the requested
1328             // flavor.
1329         } else if (flavor.isRepresentationClassInputStream()) {
1330             theObject = translateStreamToInputStream(str, flavor, format,
1331                                                                localeTransferable);
1332 
1333             // Target data is a Reader. Obtain data in InputStream format, encoded
1334             // as "Unicode" (utf-16be). Then use an InputStreamReader to decode
1335             // back to chars on demand.
1336         } else if (flavor.isRepresentationClassReader()) {
1337             if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
1338                 throw new IOException
1339                           ("cannot transfer non-text data as Reader");
1340             }
1341 
1342             InputStream is = (InputStream)translateStreamToInputStream(
1343                     str, DataFlavor.plainTextFlavor,
1344                     format, localeTransferable);
1345 
1346             String unicode = DataFlavorUtil.getTextCharset(DataFlavor.plainTextFlavor);
1347 
1348             Reader reader = new InputStreamReader(is, unicode);
1349 
1350             theObject = constructFlavoredObject(reader, flavor, Reader.class);
1351             // Target data is a byte array
1352         } else if (byte[].class.equals(flavor.getRepresentationClass())) {
1353             if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1354                 theObject = translateBytesToString(inputStreamToByteArray(str), format, localeTransferable)
1355                         .getBytes(DataFlavorUtil.getTextCharset(flavor));
1356             } else {
1357                 theObject = inputStreamToByteArray(str);
1358             }
1359             // Target data is an RMI object
1360         } else if (flavor.isRepresentationClassRemote()) {
1361             try (ObjectInputStream ois = new ObjectInputStream(str)) {
1362                 theObject = DataFlavorUtil.RMI.getMarshalledObject(ois.readObject());
1363             } catch (Exception e) {
1364                 throw new IOException(e.getMessage());
1365             }
1366 
1367             // Target data is Serializable
1368         } else if (flavor.isRepresentationClassSerializable()) {
1369             try (ObjectInputStream ois =
1370                      new ObjectInputStream(str))
1371             {
1372                 theObject = ois.readObject();
1373             } catch (Exception e) {
1374                 throw new IOException(e.getMessage());
1375             }
1376             // Target data is Image
1377         } else if (DataFlavor.imageFlavor.equals(flavor)) {
1378             if (!isImageFormat(format)) {
1379                 throw new IOException("data translation failed");
1380             }
1381             theObject = platformImageBytesToImage(inputStreamToByteArray(str), format);
1382         }
1383 
1384         if (theObject == null) {
1385             throw new IOException("data translation failed");
1386         }
1387 
1388         return theObject;
1389 
1390     }
1391 
1392     /**
1393      * For arbitrary flavors, just use the raw InputStream. For text flavors,
1394      * ReencodingInputStream will decode and reencode the InputStream on demand
1395      * so that we can strip terminators and search-and-replace EOLN.
1396      */
1397     private Object translateStreamToInputStream
1398         (InputStream str, DataFlavor flavor, long format,
1399          Transferable localeTransferable) throws IOException
1400     {
1401         if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
1402             str = new ReencodingInputStream
1403                 (str, format, DataFlavorUtil.getTextCharset(flavor),
1404                  localeTransferable);
1405         }
1406 
1407         return constructFlavoredObject(str, flavor, InputStream.class);
1408     }
1409 
1410     /**
1411      * We support representations which are exactly of the specified Class,
1412      * and also arbitrary Objects which have a constructor which takes an
1413      * instance of the Class as its sole parameter.
1414      */
1415     private Object constructFlavoredObject(Object arg, DataFlavor flavor,
1416                                            Class<?> clazz)
1417         throws IOException
1418     {
1419         final Class<?> dfrc = flavor.getRepresentationClass();
1420 
1421         if (clazz.equals(dfrc)) {
1422             return arg; // simple case
1423         } else {
1424             Constructor<?>[] constructors;
1425 
1426             try {
1427                 constructors = AccessController.doPrivileged(
1428                         (PrivilegedAction<Constructor<?>[]>) dfrc::getConstructors);
1429             } catch (SecurityException se) {
1430                 throw new IOException(se.getMessage());
1431             }
1432 
1433             Constructor<?> constructor = Stream.of(constructors)
1434                     .filter(c -> Modifier.isPublic(c.getModifiers()))
1435                     .filter(c -> {
1436                         Class<?>[] ptypes = c.getParameterTypes();
1437                         return ptypes != null
1438                                 && ptypes.length == 1
1439                                 && clazz.equals(ptypes[0]);
1440                     })
1441                     .findFirst()
1442                     .orElseThrow(() ->
1443                             new IOException("can't find <init>(L"+ clazz + ";)V for class: " + dfrc.getName()));
1444 
1445             try {
1446                 return constructor.newInstance(arg);
1447             } catch (Exception e) {
1448                 throw new IOException(e.getMessage());
1449             }
1450         }
1451     }
1452 
1453     /**
1454      * Used for decoding and reencoding an InputStream on demand so that we
1455      * can strip NUL terminators and perform EOLN search-and-replace.
1456      */
1457     public class ReencodingInputStream extends InputStream {
1458         BufferedReader wrapped;
1459         final char[] in = new char[2];
1460         byte[] out;
1461 
1462         CharsetEncoder encoder;
1463         CharBuffer inBuf;
1464         ByteBuffer outBuf;
1465 
1466         char[] eoln;
1467         int numTerminators;
1468 
1469         boolean eos;
1470         int index, limit;
1471 
1472         public ReencodingInputStream(InputStream bytestream, long format,
1473                                      String targetEncoding,
1474                                      Transferable localeTransferable)
1475             throws IOException
1476         {
1477             Long lFormat = format;
1478 
1479             String sourceEncoding = getBestCharsetForTextFormat(format, localeTransferable);
1480             wrapped = new BufferedReader(new InputStreamReader(bytestream, sourceEncoding));
1481 
1482             if (targetEncoding == null) {
1483                 // Throw NullPointerException for compatibility with the former
1484                 // call to sun.io.CharToByteConverter.getConverter(null)
1485                 // (Charset.forName(null) throws unspecified IllegalArgumentException
1486                 // now; see 6228568)
1487                 throw new NullPointerException("null target encoding");
1488             }
1489 
1490             try {
1491                 encoder = Charset.forName(targetEncoding).newEncoder();
1492                 out = new byte[(int)(encoder.maxBytesPerChar() * 2 + 0.5)];
1493                 inBuf = CharBuffer.wrap(in);
1494                 outBuf = ByteBuffer.wrap(out);
1495             } catch (IllegalCharsetNameException
1496                     | UnsupportedCharsetException
1497                     | UnsupportedOperationException e) {
1498                 throw new IOException(e.toString());
1499             }
1500 
1501             String sEoln = nativeEOLNs.get(lFormat);
1502             if (sEoln != null) {
1503                 eoln = sEoln.toCharArray();
1504             }
1505 
1506             // A hope and a prayer that this works generically. This will
1507             // definitely work on Win32.
1508             Integer terminators = nativeTerminators.get(lFormat);
1509             if (terminators != null) {
1510                 numTerminators = terminators;
1511             }
1512         }
1513 
1514         private int readChar() throws IOException {
1515             int c = wrapped.read();
1516 
1517             if (c == -1) { // -1 is EOS
1518                 eos = true;
1519                 return -1;
1520             }
1521 
1522             // "c == 0" is not quite correct, but good enough on Windows.
1523             if (numTerminators > 0 && c == 0) {
1524                 eos = true;
1525                 return -1;
1526             } else if (eoln != null && matchCharArray(eoln, c)) {
1527                 c = '\n' & 0xFFFF;
1528             }
1529 
1530             return c;
1531         }
1532 
1533         public int read() throws IOException {
1534             if (eos) {
1535                 return -1;
1536             }
1537 
1538             if (index >= limit) {
1539                 // deal with supplementary characters
1540                 int c = readChar();
1541                 if (c == -1) {
1542                     return -1;
1543                 }
1544 
1545                 in[0] = (char) c;
1546                 in[1] = 0;
1547                 inBuf.limit(1);
1548                 if (Character.isHighSurrogate((char) c)) {
1549                     c = readChar();
1550                     if (c != -1) {
1551                         in[1] = (char) c;
1552                         inBuf.limit(2);
1553                     }
1554                 }
1555 
1556                 inBuf.rewind();
1557                 outBuf.limit(out.length).rewind();
1558                 encoder.encode(inBuf, outBuf, false);
1559                 outBuf.flip();
1560                 limit = outBuf.limit();
1561 
1562                 index = 0;
1563 
1564                 return read();
1565             } else {
1566                 return out[index++] & 0xFF;
1567             }
1568         }
1569 
1570         public int available() throws IOException {
1571             return ((eos) ? 0 : (limit - index));
1572         }
1573 
1574         public void close() throws IOException {
1575             wrapped.close();
1576         }
1577 
1578         /**
1579          * Checks to see if the next array.length characters in wrapped
1580          * match array. The first character is provided as c. Subsequent
1581          * characters are read from wrapped itself. When this method returns,
1582          * the wrapped index may be different from what it was when this
1583          * method was called.
1584          */
1585         private boolean matchCharArray(char[] array, int c)
1586             throws IOException
1587         {
1588             wrapped.mark(array.length);  // BufferedReader supports mark
1589 
1590             int count = 0;
1591             if ((char)c == array[0]) {
1592                 for (count = 1; count < array.length; count++) {
1593                     c = wrapped.read();
1594                     if (c == -1 || ((char)c) != array[count]) {
1595                         break;
1596                     }
1597                 }
1598             }
1599 
1600             if (count == array.length) {
1601                 return true;
1602             } else {
1603                 wrapped.reset();
1604                 return false;
1605             }
1606         }
1607     }
1608 
1609     /**
1610      * Decodes a byte array into a set of String filenames.
1611      */
1612     protected abstract String[] dragQueryFile(byte[] bytes);
1613 
1614     /**
1615      * Decodes URIs from either a byte array or a stream.
1616      */
1617     protected URI[] dragQueryURIs(InputStream stream,
1618                                   long format,
1619                                   Transferable localeTransferable)
1620       throws IOException
1621     {
1622         throw new IOException(
1623             new UnsupportedOperationException("not implemented on this platform"));
1624     }
1625 
1626     /**
1627      * Translates either a byte array or an input stream which contain
1628      * platform-specific image data in the given format into an Image.
1629      */
1630 
1631 
1632     protected abstract Image platformImageBytesToImage(
1633         byte[] bytes,long format) throws IOException;
1634 
1635     /**
1636      * Translates either a byte array or an input stream which contain
1637      * an image data in the given standard format into an Image.
1638      *
1639      * @param mimeType image MIME type, such as: image/png, image/jpeg, image/gif
1640      */
1641     protected Image standardImageBytesToImage(
1642         byte[] bytes, String mimeType) throws IOException
1643     {
1644 
1645         Iterator<ImageReader> readerIterator = ImageIO.getImageReadersByMIMEType(mimeType);
1646 
1647         if (!readerIterator.hasNext()) {
1648             throw new IOException("No registered service provider can decode " +
1649                                   " an image from " + mimeType);
1650         }
1651 
1652         IOException ioe = null;
1653 
1654         while (readerIterator.hasNext()) {
1655             ImageReader imageReader = readerIterator.next();
1656             try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) {
1657                 try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(bais)) {
1658                     ImageReadParam param = imageReader.getDefaultReadParam();
1659                     imageReader.setInput(imageInputStream, true, true);
1660                     BufferedImage bufferedImage = imageReader.read(imageReader.getMinIndex(), param);
1661                     if (bufferedImage != null) {
1662                         return bufferedImage;
1663                     }
1664                 } finally {
1665                     imageReader.dispose();
1666                 }
1667             } catch (IOException e) {
1668                 ioe = e;
1669                 continue;
1670             }
1671         }
1672 
1673         if (ioe == null) {
1674             ioe = new IOException("Registered service providers failed to decode"
1675                                   + " an image from " + mimeType);
1676         }
1677 
1678         throw ioe;
1679     }
1680 
1681     /**
1682      * Translates a Java Image into a byte array which contains platform-
1683      * specific image data in the given format.
1684      */
1685     protected abstract byte[] imageToPlatformBytes(Image image, long format)
1686       throws IOException;
1687 
1688     /**
1689      * Translates a Java Image into a byte array which contains
1690      * an image data in the given standard format.
1691      *
1692      * @param mimeType image MIME type, such as: image/png, image/jpeg
1693      */
1694     protected byte[] imageToStandardBytes(Image image, String mimeType)
1695       throws IOException {
1696         IOException originalIOE = null;
1697 
1698         Iterator<ImageWriter> writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
1699 
1700         if (!writerIterator.hasNext()) {
1701             throw new IOException("No registered service provider can encode " +
1702                                   " an image to " + mimeType);
1703         }
1704 
1705         if (image instanceof RenderedImage) {
1706             // Try to encode the original image.
1707             try {
1708                 return imageToStandardBytesImpl((RenderedImage)image, mimeType);
1709             } catch (IOException ioe) {
1710                 originalIOE = ioe;
1711             }
1712         }
1713 
1714         // Retry with a BufferedImage.
1715         int width = 0;
1716         int height = 0;
1717         if (image instanceof ToolkitImage) {
1718             ImageRepresentation ir = ((ToolkitImage)image).getImageRep();
1719             ir.reconstruct(ImageObserver.ALLBITS);
1720             width = ir.getWidth();
1721             height = ir.getHeight();
1722         } else {
1723             width = image.getWidth(null);
1724             height = image.getHeight(null);
1725         }
1726 
1727         ColorModel model = ColorModel.getRGBdefault();
1728         WritableRaster raster =
1729             model.createCompatibleWritableRaster(width, height);
1730 
1731         BufferedImage bufferedImage =
1732             new BufferedImage(model, raster, model.isAlphaPremultiplied(),
1733                               null);
1734 
1735         Graphics g = bufferedImage.getGraphics();
1736         try {
1737             g.drawImage(image, 0, 0, width, height, null);
1738         } finally {
1739             g.dispose();
1740         }
1741 
1742         try {
1743             return imageToStandardBytesImpl(bufferedImage, mimeType);
1744         } catch (IOException ioe) {
1745             if (originalIOE != null) {
1746                 throw originalIOE;
1747             } else {
1748                 throw ioe;
1749             }
1750         }
1751     }
1752 
1753     byte[] imageToStandardBytesImpl(RenderedImage renderedImage,
1754                                               String mimeType)
1755         throws IOException {
1756 
1757         Iterator<ImageWriter> writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
1758 
1759         ImageTypeSpecifier typeSpecifier =
1760             new ImageTypeSpecifier(renderedImage);
1761 
1762         ByteArrayOutputStream baos = new ByteArrayOutputStream();
1763         IOException ioe = null;
1764 
1765         while (writerIterator.hasNext()) {
1766             ImageWriter imageWriter = writerIterator.next();
1767             ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
1768 
1769             if (!writerSpi.canEncodeImage(typeSpecifier)) {
1770                 continue;
1771             }
1772 
1773             try {
1774                 try (ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos)) {
1775                     imageWriter.setOutput(imageOutputStream);
1776                     imageWriter.write(renderedImage);
1777                     imageOutputStream.flush();
1778                 }
1779             } catch (IOException e) {
1780                 imageWriter.dispose();
1781                 baos.reset();
1782                 ioe = e;
1783                 continue;
1784             }
1785 
1786             imageWriter.dispose();
1787             baos.close();
1788             return baos.toByteArray();
1789         }
1790 
1791         baos.close();
1792 
1793         if (ioe == null) {
1794             ioe = new IOException("Registered service providers failed to encode "
1795                                   + renderedImage + " to " + mimeType);
1796         }
1797 
1798         throw ioe;
1799     }
1800 
1801     /**
1802      * Concatenates the data represented by two objects. Objects can be either
1803      * byte arrays or instances of <code>InputStream</code>. If both arguments
1804      * are byte arrays byte array will be returned. Otherwise an
1805      * <code>InputStream</code> will be returned.
1806      * <p>
1807      * Currently is only called from native code to prepend palette data to
1808      * platform-specific image data during image transfer on Win32.
1809      *
1810      * @param obj1 the first object to be concatenated.
1811      * @param obj2 the second object to be concatenated.
1812      * @return a byte array or an <code>InputStream</code> which represents
1813      *         a logical concatenation of the two arguments.
1814      * @throws NullPointerException is either of the arguments is
1815      *         <code>null</code>
1816      * @throws ClassCastException is either of the arguments is
1817      *         neither byte array nor an instance of <code>InputStream</code>.
1818      */
1819     private Object concatData(Object obj1, Object obj2) {
1820         InputStream str1 = null;
1821         InputStream str2 = null;
1822 
1823         if (obj1 instanceof byte[]) {
1824             byte[] arr1 = (byte[])obj1;
1825             if (obj2 instanceof byte[]) {
1826                 byte[] arr2 = (byte[])obj2;
1827                 byte[] ret = new byte[arr1.length + arr2.length];
1828                 System.arraycopy(arr1, 0, ret, 0, arr1.length);
1829                 System.arraycopy(arr2, 0, ret, arr1.length, arr2.length);
1830                 return ret;
1831             } else {
1832                 str1 = new ByteArrayInputStream(arr1);
1833                 str2 = (InputStream)obj2;
1834             }
1835         } else {
1836             str1 = (InputStream)obj1;
1837             if (obj2 instanceof byte[]) {
1838                 str2 = new ByteArrayInputStream((byte[])obj2);
1839             } else {
1840                 str2 = (InputStream)obj2;
1841             }
1842         }
1843 
1844         return new SequenceInputStream(str1, str2);
1845     }
1846 
1847     public byte[] convertData(final Object source,
1848                               final Transferable contents,
1849                               final long format,
1850                               final Map<Long, DataFlavor> formatMap,
1851                               final boolean isToolkitThread)
1852         throws IOException
1853     {
1854         byte[] ret = null;
1855 
1856         /*
1857          * If the current thread is the Toolkit thread we should post a
1858          * Runnable to the event dispatch thread associated with source Object,
1859          * since translateTransferable() calls Transferable.getTransferData()
1860          * that may contain client code.
1861          */
1862         if (isToolkitThread) try {
1863             final Stack<byte[]> stack = new Stack<>();
1864             final Runnable dataConverter = new Runnable() {
1865                 // Guard against multiple executions.
1866                 private boolean done = false;
1867                 public void run() {
1868                     if (done) {
1869                         return;
1870                     }
1871                     byte[] data = null;
1872                     try {
1873                         DataFlavor flavor = formatMap.get(format);
1874                         if (flavor != null) {
1875                             data = translateTransferable(contents, flavor, format);
1876                         }
1877                     } catch (Exception e) {
1878                         e.printStackTrace();
1879                         data = null;
1880                     }
1881                     try {
1882                         getToolkitThreadBlockedHandler().lock();
1883                         stack.push(data);
1884                         getToolkitThreadBlockedHandler().exit();
1885                     } finally {
1886                         getToolkitThreadBlockedHandler().unlock();
1887                         done = true;
1888                     }
1889                 }
1890             };
1891 
1892             final AppContext appContext = SunToolkit.targetToAppContext(source);
1893 
1894             getToolkitThreadBlockedHandler().lock();
1895 
1896             if (appContext != null) {
1897                 appContext.put(DATA_CONVERTER_KEY, dataConverter);
1898             }
1899 
1900             SunToolkit.executeOnEventHandlerThread(source, dataConverter);
1901 
1902             while (stack.empty()) {
1903                 getToolkitThreadBlockedHandler().enter();
1904             }
1905 
1906             if (appContext != null) {
1907                 appContext.remove(DATA_CONVERTER_KEY);
1908             }
1909 
1910             ret = stack.pop();
1911         } finally {
1912             getToolkitThreadBlockedHandler().unlock();
1913         } else {
1914             DataFlavor flavor = formatMap.get(format);
1915             if (flavor != null) {
1916                 ret = translateTransferable(contents, flavor, format);
1917             }
1918         }
1919 
1920         return ret;
1921     }
1922 
1923     public void processDataConversionRequests() {
1924         if (EventQueue.isDispatchThread()) {
1925             AppContext appContext = AppContext.getAppContext();
1926             getToolkitThreadBlockedHandler().lock();
1927             try {
1928                 Runnable dataConverter =
1929                     (Runnable)appContext.get(DATA_CONVERTER_KEY);
1930                 if (dataConverter != null) {
1931                     dataConverter.run();
1932                     appContext.remove(DATA_CONVERTER_KEY);
1933                 }
1934             } finally {
1935                 getToolkitThreadBlockedHandler().unlock();
1936             }
1937         }
1938     }
1939 
1940     public abstract ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler();
1941 
1942     /**
1943      * Helper function to reduce a Map with Long keys to a long array.
1944      * <p>
1945      * The map keys are sorted according to the native formats preference
1946      * order.
1947      */
1948     public static long[] keysToLongArray(SortedMap<Long, ?> map) {
1949         Set<Long> keySet = map.keySet();
1950         long[] retval = new long[keySet.size()];
1951         int i = 0;
1952         for (Iterator<Long> iter = keySet.iterator(); iter.hasNext(); i++) {
1953             retval[i] = iter.next();
1954         }
1955         return retval;
1956     }
1957 
1958     /**
1959      * Helper function to convert a Set of DataFlavors to a sorted array.
1960      * The array will be sorted according to <code>DataFlavorComparator</code>.
1961      */
1962     public static DataFlavor[] setToSortedDataFlavorArray(Set<DataFlavor> flavorsSet) {
1963         DataFlavor[] flavors = new DataFlavor[flavorsSet.size()];
1964         flavorsSet.toArray(flavors);
1965         final Comparator<DataFlavor> comparator = DataFlavorUtil.getDataFlavorComparator().reversed();
1966         Arrays.sort(flavors, comparator);
1967         return flavors;
1968     }
1969 
1970     /**
1971      * Helper function to convert an InputStream to a byte[] array.
1972      */
1973     protected static byte[] inputStreamToByteArray(InputStream str)
1974         throws IOException
1975     {
1976         try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
1977             int len = 0;
1978             byte[] buf = new byte[8192];
1979 
1980             while ((len = str.read(buf)) != -1) {
1981                 baos.write(buf, 0, len);
1982             }
1983 
1984             return baos.toByteArray();
1985         }
1986     }
1987 
1988     /**
1989      * Returns platform-specific mappings for the specified native.
1990      * If there are no platform-specific mappings for this native, the method
1991      * returns an empty <code>List</code>.
1992      */
1993     public LinkedHashSet<DataFlavor> getPlatformMappingsForNative(String nat) {
1994         return new LinkedHashSet<>();
1995     }
1996 
1997     /**
1998      * Returns platform-specific mappings for the specified flavor.
1999      * If there are no platform-specific mappings for this flavor, the method
2000      * returns an empty <code>List</code>.
2001      */
2002     public LinkedHashSet<String> getPlatformMappingsForFlavor(DataFlavor df) {
2003         return new LinkedHashSet<>();
2004     }
2005 }