/
DataTransferer.java
2001 lines (1731 loc) · 75.9 KB
/
DataTransferer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.datatransfer;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorMap;
import java.awt.datatransfer.FlavorTable;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.io.SequenceInputStream;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.*;
import sun.datatransfer.DataFlavorUtil;
import sun.awt.AppContext;
import sun.awt.ComponentFactory;
import sun.awt.SunToolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.awt.image.ColorModel;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageWriter;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import sun.awt.image.ImageRepresentation;
import sun.awt.image.ToolkitImage;
import java.io.FilePermission;
import java.util.stream.Stream;
/**
* Provides a set of functions to be shared among the DataFlavor class and
* platform-specific data transfer implementations.
*
* The concept of "flavors" and "natives" is extended to include "formats",
* which are the numeric values Win32 and X11 use to express particular data
* types. Like FlavorMap, which provides getNativesForFlavors(DataFlavor[]) and
* getFlavorsForNatives(String[]) functions, DataTransferer provides a set
* of getFormatsFor(Transferable|Flavor|Flavors) and
* getFlavorsFor(Format|Formats) functions.
*
* Also provided are functions for translating a Transferable into a byte
* array, given a source DataFlavor and a target format, and for translating
* a byte array or InputStream into an Object, given a source format and
* a target DataFlavor.
*
* @author David Mendenhall
* @author Danila Sinopalnikov
*
* @since 1.3.1
*/
public abstract class DataTransferer {
/**
* The {@code DataFlavor} representing a Java text encoding String
* encoded in UTF-8, where
* <pre>
* representationClass = [B
* mimeType = "application/x-java-text-encoding"
* </pre>
*/
public static final DataFlavor javaTextEncodingFlavor;
/**
* A collection of all natives listed in flavormap.properties with
* a primary MIME type of "text".
*/
private static final Set<Long> textNatives =
Collections.synchronizedSet(new HashSet<>());
/**
* The native encodings/charsets for the Set of textNatives.
*/
private static final Map<Long, String> nativeCharsets =
Collections.synchronizedMap(new HashMap<>());
/**
* The end-of-line markers for the Set of textNatives.
*/
private static final Map<Long, String> nativeEOLNs =
Collections.synchronizedMap(new HashMap<>());
/**
* The number of terminating NUL bytes for the Set of textNatives.
*/
private static final Map<Long, Integer> nativeTerminators =
Collections.synchronizedMap(new HashMap<>());
/**
* The key used to store pending data conversion requests for an AppContext.
*/
private static final String DATA_CONVERTER_KEY = "DATA_CONVERTER_KEY";
static {
DataFlavor tJavaTextEncodingFlavor = null;
try {
tJavaTextEncodingFlavor = new DataFlavor("application/x-java-text-encoding;class=\"[B\"");
} catch (ClassNotFoundException cannotHappen) {
}
javaTextEncodingFlavor = tJavaTextEncodingFlavor;
}
/**
* The accessor method for the singleton DataTransferer instance. Note
* that in a headless environment, there may be no DataTransferer instance;
* instead, null will be returned.
*/
public static synchronized DataTransferer getInstance() {
return ((ComponentFactory) Toolkit.getDefaultToolkit()).getDataTransferer();
}
/**
* Converts a FlavorMap to a FlavorTable.
*/
public static FlavorTable adaptFlavorMap(final FlavorMap map) {
if (map instanceof FlavorTable) {
return (FlavorTable)map;
}
return new FlavorTable() {
@Override
public Map<DataFlavor, String> getNativesForFlavors(DataFlavor[] flavors) {
return map.getNativesForFlavors(flavors);
}
@Override
public Map<String, DataFlavor> getFlavorsForNatives(String[] natives) {
return map.getFlavorsForNatives(natives);
}
@Override
public List<String> getNativesForFlavor(DataFlavor flav) {
Map<DataFlavor, String> natives = getNativesForFlavors(new DataFlavor[]{flav});
String nat = natives.get(flav);
if (nat != null) {
return Collections.singletonList(nat);
} else {
return Collections.emptyList();
}
}
@Override
public List<DataFlavor> getFlavorsForNative(String nat) {
Map<String, DataFlavor> flavors = getFlavorsForNatives(new String[]{nat});
DataFlavor flavor = flavors.get(nat);
if (flavor != null) {
return Collections.singletonList(flavor);
} else {
return Collections.emptyList();
}
}
};
}
/**
* Returns the default Unicode encoding for the platform. The encoding
* need not be canonical. This method is only used by the archaic function
* DataFlavor.getTextPlainUnicodeFlavor().
*/
public abstract String getDefaultUnicodeEncoding();
/**
* This method is called for text flavor mappings established while parsing
* the flavormap.properties file. It stores the "eoln" and "terminators"
* parameters which are not officially part of the MIME type. They are
* MIME parameters specific to the flavormap.properties file format.
*/
public void registerTextFlavorProperties(String nat, String charset,
String eoln, String terminators) {
Long format = getFormatForNativeAsLong(nat);
textNatives.add(format);
nativeCharsets.put(format, (charset != null && charset.length() != 0)
? charset : Charset.defaultCharset().name());
if (eoln != null && eoln.length() != 0 && !eoln.equals("\n")) {
nativeEOLNs.put(format, eoln);
}
if (terminators != null && terminators.length() != 0) {
Integer iTerminators = Integer.valueOf(terminators);
if (iTerminators > 0) {
nativeTerminators.put(format, iTerminators);
}
}
}
/**
* Determines whether the native corresponding to the specified long format
* was listed in the flavormap.properties file.
*/
protected boolean isTextFormat(long format) {
return textNatives.contains(Long.valueOf(format));
}
protected String getCharsetForTextFormat(Long lFormat) {
return nativeCharsets.get(lFormat);
}
/**
* Specifies whether text imported from the native system in the specified
* format is locale-dependent. If so, when decoding such text,
* 'nativeCharsets' should be ignored, and instead, the Transferable should
* be queried for its javaTextEncodingFlavor data for the correct encoding.
*/
public abstract boolean isLocaleDependentTextFormat(long format);
/**
* Determines whether the DataFlavor corresponding to the specified long
* format is DataFlavor.javaFileListFlavor.
*/
public abstract boolean isFileFormat(long format);
/**
* Determines whether the DataFlavor corresponding to the specified long
* format is DataFlavor.imageFlavor.
*/
public abstract boolean isImageFormat(long format);
/**
* Determines whether the format is a URI list we can convert to
* a DataFlavor.javaFileListFlavor.
*/
protected boolean isURIListFormat(long format) {
return false;
}
/**
* Returns a Map whose keys are all of the possible formats into which the
* Transferable's transfer data flavors can be translated. The value of
* each key is the DataFlavor in which the Transferable's data should be
* requested when converting to the format.
* <p>
* The map keys are sorted according to the native formats preference
* order.
*/
public SortedMap<Long,DataFlavor> getFormatsForTransferable(Transferable contents,
FlavorTable map)
{
DataFlavor[] flavors = contents.getTransferDataFlavors();
if (flavors == null) {
return Collections.emptySortedMap();
}
return getFormatsForFlavors(flavors, map);
}
/**
* Returns a Map whose keys are all of the possible formats into which data
* in the specified DataFlavors can be translated. The value of each key
* is the DataFlavor in which the Transferable's data should be requested
* when converting to the format.
* <p>
* The map keys are sorted according to the native formats preference
* order.
*
* @param flavors the data flavors
* @param map the FlavorTable which contains mappings between
* DataFlavors and data formats
* @throws NullPointerException if flavors or map is {@code null}
*/
public SortedMap<Long, DataFlavor> getFormatsForFlavors(DataFlavor[] flavors,
FlavorTable map)
{
Map<Long,DataFlavor> formatMap = new HashMap<>(flavors.length);
Map<Long,DataFlavor> textPlainMap = new HashMap<>(flavors.length);
// Maps formats to indices that will be used to sort the formats
// according to the preference order.
// Larger index value corresponds to the more preferable format.
Map<Long, Integer> indexMap = new HashMap<>(flavors.length);
Map<Long, Integer> textPlainIndexMap = new HashMap<>(flavors.length);
int currentIndex = 0;
// Iterate backwards so that preferred DataFlavors are used over
// other DataFlavors. (See javadoc for
// Transferable.getTransferDataFlavors.)
for (int i = flavors.length - 1; i >= 0; i--) {
DataFlavor flavor = flavors[i];
if (flavor == null) continue;
// Don't explicitly test for String, since it is just a special
// case of Serializable
if (flavor.isFlavorTextType() ||
flavor.isFlavorJavaFileListType() ||
DataFlavor.imageFlavor.equals(flavor) ||
flavor.isRepresentationClassSerializable() ||
flavor.isRepresentationClassInputStream() ||
flavor.isRepresentationClassRemote())
{
List<String> natives = map.getNativesForFlavor(flavor);
currentIndex += natives.size();
for (String aNative : natives) {
Long lFormat = getFormatForNativeAsLong(aNative);
Integer index = currentIndex--;
formatMap.put(lFormat, flavor);
indexMap.put(lFormat, index);
// SystemFlavorMap.getNativesForFlavor will return
// text/plain natives for all text/*. While this is good
// for a single text/* flavor, we would prefer that
// text/plain native data come from a text/plain flavor.
if (("text".equals(flavor.getPrimaryType()) &&
"plain".equals(flavor.getSubType())) ||
flavor.equals(DataFlavor.stringFlavor)) {
textPlainMap.put(lFormat, flavor);
textPlainIndexMap.put(lFormat, index);
}
}
currentIndex += natives.size();
}
}
formatMap.putAll(textPlainMap);
indexMap.putAll(textPlainIndexMap);
// Sort the map keys according to the formats preference order.
Comparator<Long> comparator = DataFlavorUtil.getIndexOrderComparator(indexMap).reversed();
SortedMap<Long, DataFlavor> sortedMap = new TreeMap<>(comparator);
sortedMap.putAll(formatMap);
return sortedMap;
}
/**
* Reduces the Map output for the root function to an array of the
* Map's keys.
*/
public long[] getFormatsForTransferableAsArray(Transferable contents,
FlavorTable map) {
return keysToLongArray(getFormatsForTransferable(contents, map));
}
/**
* Returns a Map whose keys are all of the possible DataFlavors into which
* data in the specified formats can be translated. The value of each key
* is the format in which the Clipboard or dropped data should be requested
* when converting to the DataFlavor.
*/
public Map<DataFlavor, Long> getFlavorsForFormats(long[] formats, FlavorTable map) {
Map<DataFlavor, Long> flavorMap = new HashMap<>(formats.length);
Set<AbstractMap.SimpleEntry<Long, DataFlavor>> mappingSet = new HashSet<>(formats.length);
Set<DataFlavor> flavorSet = new HashSet<>(formats.length);
// First step: build flavorSet, mappingSet and initial flavorMap
// flavorSet - the set of all the DataFlavors into which
// data in the specified formats can be translated;
// mappingSet - the set of all the mappings from the specified formats
// into any DataFlavor;
// flavorMap - after this step, this map maps each of the DataFlavors
// from flavorSet to any of the specified formats.
for (long format : formats) {
String nat = getNativeForFormat(format);
List<DataFlavor> flavors = map.getFlavorsForNative(nat);
for (DataFlavor flavor : flavors) {
// Don't explicitly test for String, since it is just a special
// case of Serializable
if (flavor.isFlavorTextType() ||
flavor.isFlavorJavaFileListType() ||
DataFlavor.imageFlavor.equals(flavor) ||
flavor.isRepresentationClassSerializable() ||
flavor.isRepresentationClassInputStream() ||
flavor.isRepresentationClassRemote()) {
AbstractMap.SimpleEntry<Long, DataFlavor> mapping =
new AbstractMap.SimpleEntry<>(format, flavor);
flavorMap.put(flavor, format);
mappingSet.add(mapping);
flavorSet.add(flavor);
}
}
}
// Second step: for each DataFlavor try to figure out which of the
// specified formats is the best to translate to this flavor.
// Then map each flavor to the best format.
// For the given flavor, FlavorTable indicates which native will
// best reflect data in the specified flavor to the underlying native
// platform. We assume that this native is the best to translate
// to this flavor.
// Note: FlavorTable allows one-way mappings, so we can occasionally
// map a flavor to the format for which the corresponding
// format-to-flavor mapping doesn't exist. For this reason we have built
// a mappingSet of all format-to-flavor mappings for the specified formats
// and check if the format-to-flavor mapping exists for the
// (flavor,format) pair being added.
for (DataFlavor flavor : flavorSet) {
List<String> natives = map.getNativesForFlavor(flavor);
for (String aNative : natives) {
Long lFormat = getFormatForNativeAsLong(aNative);
if (mappingSet.contains(new AbstractMap.SimpleEntry<>(lFormat, flavor))) {
flavorMap.put(flavor, lFormat);
break;
}
}
}
return flavorMap;
}
/**
* Returns a Set of all DataFlavors for which
* 1) a mapping from at least one of the specified formats exists in the
* specified map and
* 2) the data translation for this mapping can be performed by the data
* transfer subsystem.
*
* @param formats the data formats
* @param map the FlavorTable which contains mappings between
* DataFlavors and data formats
* @throws NullPointerException if formats or map is {@code null}
*/
public Set<DataFlavor> getFlavorsForFormatsAsSet(long[] formats, FlavorTable map) {
Set<DataFlavor> flavorSet = new HashSet<>(formats.length);
for (long format : formats) {
List<DataFlavor> flavors = map.getFlavorsForNative(getNativeForFormat(format));
for (DataFlavor flavor : flavors) {
// Don't explicitly test for String, since it is just a special
// case of Serializable
if (flavor.isFlavorTextType() ||
flavor.isFlavorJavaFileListType() ||
DataFlavor.imageFlavor.equals(flavor) ||
flavor.isRepresentationClassSerializable() ||
flavor.isRepresentationClassInputStream() ||
flavor.isRepresentationClassRemote()) {
flavorSet.add(flavor);
}
}
}
return flavorSet;
}
/**
* Returns an array of all DataFlavors for which
* 1) a mapping from at least one of the specified formats exists in the
* specified map and
* 2) the data translation for this mapping can be performed by the data
* transfer subsystem.
* The array will be sorted according to a
* {@code DataFlavorComparator} created with the specified
* map as an argument.
*
* @param formats the data formats
* @param map the FlavorTable which contains mappings between
* DataFlavors and data formats
* @throws NullPointerException if formats or map is {@code null}
*/
public DataFlavor[] getFlavorsForFormatsAsArray(long[] formats,
FlavorTable map) {
// getFlavorsForFormatsAsSet() is less expensive than
// getFlavorsForFormats().
return setToSortedDataFlavorArray(getFlavorsForFormatsAsSet(formats, map));
}
/**
* Looks-up or registers the String native with the native data transfer
* system and returns a long format corresponding to that native.
*/
protected abstract Long getFormatForNativeAsLong(String str);
/**
* Looks-up the String native corresponding to the specified long format in
* the native data transfer system.
*/
protected abstract String getNativeForFormat(long format);
/* Contains common code for finding the best charset for
* clipboard string encoding/decoding, basing on clipboard
* format and localeTransferable(on decoding, if available)
*/
protected String getBestCharsetForTextFormat(Long lFormat,
Transferable localeTransferable) throws IOException
{
String charset = null;
if (localeTransferable != null &&
isLocaleDependentTextFormat(lFormat) &&
localeTransferable.isDataFlavorSupported(javaTextEncodingFlavor)) {
try {
byte[] charsetNameBytes = (byte[])localeTransferable
.getTransferData(javaTextEncodingFlavor);
charset = new String(charsetNameBytes, StandardCharsets.UTF_8);
} catch (UnsupportedFlavorException cannotHappen) {
}
} else {
charset = getCharsetForTextFormat(lFormat);
}
if (charset == null) {
// Only happens when we have a custom text type.
charset = Charset.defaultCharset().name();
}
return charset;
}
/**
* Translation function for converting string into
* a byte array. Search-and-replace EOLN. Encode into the
* target format. Append terminating NUL bytes.
*
* Java to Native string conversion
*/
private byte[] translateTransferableString(String str,
long format) throws IOException
{
Long lFormat = format;
String charset = getBestCharsetForTextFormat(lFormat, null);
// Search and replace EOLN. Note that if EOLN is "\n", then we
// never added an entry to nativeEOLNs anyway, so we'll skip this
// code altogether.
// windows: "abc\nde"->"abc\r\nde"
String eoln = nativeEOLNs.get(lFormat);
if (eoln != null) {
int length = str.length();
StringBuilder buffer = new StringBuilder(length * 2); // 2 is a heuristic
for (int i = 0; i < length; i++) {
// Fix for 4914613 - skip native EOLN
if (str.startsWith(eoln, i)) {
buffer.append(eoln);
i += eoln.length() - 1;
continue;
}
char c = str.charAt(i);
if (c == '\n') {
buffer.append(eoln);
} else {
buffer.append(c);
}
}
str = buffer.toString();
}
// Encode text in target format.
byte[] bytes = str.getBytes(charset);
// Append terminating NUL bytes. Note that if terminators is 0,
// the we never added an entry to nativeTerminators anyway, so
// we'll skip code altogether.
// "abcde" -> "abcde\0"
Integer terminators = nativeTerminators.get(lFormat);
if (terminators != null) {
int numTerminators = terminators;
byte[] terminatedBytes =
new byte[bytes.length + numTerminators];
System.arraycopy(bytes, 0, terminatedBytes, 0, bytes.length);
for (int i = bytes.length; i < terminatedBytes.length; i++) {
terminatedBytes[i] = 0x0;
}
bytes = terminatedBytes;
}
return bytes;
}
/**
* Translating either a byte array or an InputStream into an String.
* Strip terminators and search-and-replace EOLN.
*
* Native to Java string conversion
*/
private String translateBytesToString(byte[] bytes, long format,
Transferable localeTransferable)
throws IOException
{
Long lFormat = format;
String charset = getBestCharsetForTextFormat(lFormat, localeTransferable);
// Locate terminating NUL bytes. Note that if terminators is 0,
// the we never added an entry to nativeTerminators anyway, so
// we'll skip code altogether.
// In other words: we are doing char alignment here basing on suggestion
// that count of zero-'terminators' is a number of bytes in one symbol
// for selected charset (clipboard format). It is not complitly true for
// multibyte coding like UTF-8, but helps understand the procedure.
// "abcde\0" -> "abcde"
String eoln = nativeEOLNs.get(lFormat);
Integer terminators = nativeTerminators.get(lFormat);
int count;
if (terminators != null) {
int numTerminators = terminators;
search:
for (count = 0; count < (bytes.length - numTerminators + 1); count += numTerminators) {
for (int i = count; i < count + numTerminators; i++) {
if (bytes[i] != 0x0) {
continue search;
}
}
// found terminators
break search;
}
} else {
count = bytes.length;
}
// Decode text to chars. Don't include any terminators.
String converted = new String(bytes, 0, count, charset);
// Search and replace EOLN. Note that if EOLN is "\n", then we
// never added an entry to nativeEOLNs anyway, so we'll skip this
// code altogether.
// Count of NUL-terminators and EOLN coding are platform-specific and
// loaded from flavormap.properties file
// windows: "abc\r\nde" -> "abc\nde"
if (eoln != null) {
/* Fix for 4463560: replace EOLNs symbol-by-symbol instead
* of using buf.replace()
*/
char[] buf = converted.toCharArray();
char[] eoln_arr = eoln.toCharArray();
int j = 0;
boolean match;
for (int i = 0; i < buf.length; ) {
// Catch last few bytes
if (i + eoln_arr.length > buf.length) {
buf[j++] = buf[i++];
continue;
}
match = true;
for (int k = 0, l = i; k < eoln_arr.length; k++, l++) {
if (eoln_arr[k] != buf[l]) {
match = false;
break;
}
}
if (match) {
buf[j++] = '\n';
i += eoln_arr.length;
} else {
buf[j++] = buf[i++];
}
}
converted = new String(buf, 0, j);
}
return converted;
}
/**
* Primary translation function for translating a Transferable into
* a byte array, given a source DataFlavor and target format.
*/
@SuppressWarnings("deprecation")
public byte[] translateTransferable(Transferable contents,
DataFlavor flavor,
long format) throws IOException
{
// Obtain the transfer data in the source DataFlavor.
//
// Note that we special case DataFlavor.plainTextFlavor because
// StringSelection supports this flavor incorrectly -- instead of
// returning an InputStream as the DataFlavor representation class
// states, it returns a Reader. Instead of using this broken
// functionality, we request the data in stringFlavor (the other
// DataFlavor which StringSelection supports) and use the String
// translator.
Object obj;
boolean stringSelectionHack;
try {
obj = contents.getTransferData(flavor);
if (obj == null) {
return null;
}
if (flavor.equals(DataFlavor.plainTextFlavor) &&
!(obj instanceof InputStream))
{
obj = contents.getTransferData(DataFlavor.stringFlavor);
if (obj == null) {
return null;
}
stringSelectionHack = true;
} else {
stringSelectionHack = false;
}
} catch (UnsupportedFlavorException e) {
throw new IOException(e.getMessage());
}
// Source data is a String. Search-and-replace EOLN. Encode into the
// target format. Append terminating NUL bytes.
if (stringSelectionHack ||
(String.class.equals(flavor.getRepresentationClass()) &&
DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
String str = removeSuspectedData(flavor, contents, (String)obj);
return translateTransferableString(
str,
format);
// Source data is a Reader. Convert to a String and recur. In the
// future, we may want to rewrite this so that we encode on demand.
} else if (flavor.isRepresentationClassReader()) {
if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
throw new IOException
("cannot transfer non-text data as Reader");
}
StringBuilder buf = new StringBuilder();
try (Reader r = (Reader)obj) {
int c;
while ((c = r.read()) != -1) {
buf.append((char)c);
}
}
return translateTransferableString(
buf.toString(),
format);
// Source data is a CharBuffer. Convert to a String and recur.
} else if (flavor.isRepresentationClassCharBuffer()) {
if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
throw new IOException
("cannot transfer non-text data as CharBuffer");
}
CharBuffer buffer = (CharBuffer)obj;
int size = buffer.remaining();
char[] chars = new char[size];
buffer.get(chars, 0, size);
return translateTransferableString(
new String(chars),
format);
// Source data is a char array. Convert to a String and recur.
} else if (char[].class.equals(flavor.getRepresentationClass())) {
if (!(DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
throw new IOException
("cannot transfer non-text data as char array");
}
return translateTransferableString(
new String((char[])obj),
format);
// Source data is a ByteBuffer. For arbitrary flavors, simply return
// the array. For text flavors, decode back to a String and recur to
// reencode according to the requested format.
} else if (flavor.isRepresentationClassByteBuffer()) {
ByteBuffer buffer = (ByteBuffer)obj;
int size = buffer.remaining();
byte[] bytes = new byte[size];
buffer.get(bytes, 0, size);
if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
String sourceEncoding = DataFlavorUtil.getTextCharset(flavor);
return translateTransferableString(
new String(bytes, sourceEncoding),
format);
} else {
return bytes;
}
// Source data is a byte array. For arbitrary flavors, simply return
// the array. For text flavors, decode back to a String and recur to
// reencode according to the requested format.
} else if (byte[].class.equals(flavor.getRepresentationClass())) {
byte[] bytes = (byte[])obj;
if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
String sourceEncoding = DataFlavorUtil.getTextCharset(flavor);
return translateTransferableString(
new String(bytes, sourceEncoding),
format);
} else {
return bytes;
}
// Source data is Image
} else if (DataFlavor.imageFlavor.equals(flavor)) {
if (!isImageFormat(format)) {
throw new IOException("Data translation failed: " +
"not an image format");
}
Image image = (Image)obj;
byte[] bytes = imageToPlatformBytes(image, format);
if (bytes == null) {
throw new IOException("Data translation failed: " +
"cannot convert java image to native format");
}
return bytes;
}
byte[] theByteArray = null;
// Target data is a file list. Source data must be a
// java.util.List which contains java.io.File or String instances.
if (isFileFormat(format)) {
if (!DataFlavor.javaFileListFlavor.equals(flavor)) {
throw new IOException("data translation failed");
}
final List<?> list = (List<?>)obj;
final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
final ArrayList<String> fileList = castToFiles(list, userProtectionDomain);
try (ByteArrayOutputStream bos = convertFileListToBytes(fileList)) {
theByteArray = bos.toByteArray();
}
// Target data is a URI list. Source data must be a
// java.util.List which contains java.io.File or String instances.
} else if (isURIListFormat(format)) {
if (!DataFlavor.javaFileListFlavor.equals(flavor)) {
throw new IOException("data translation failed");
}
String nat = getNativeForFormat(format);
String targetCharset = null;
if (nat != null) {
try {
targetCharset = new DataFlavor(nat).getParameter("charset");
} catch (ClassNotFoundException cnfe) {
throw new IOException(cnfe);
}
}
if (targetCharset == null) {
targetCharset = "UTF-8";
}
final List<?> list = (List<?>)obj;
final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
final ArrayList<String> fileList = castToFiles(list, userProtectionDomain);
final ArrayList<String> uriList = new ArrayList<>(fileList.size());
for (String fileObject : fileList) {
final URI uri = new File(fileObject).toURI();
// Some implementations are fussy about the number of slashes (file:///path/to/file is best)
try {
uriList.add(new URI(uri.getScheme(), "", uri.getPath(), uri.getFragment()).toString());
} catch (URISyntaxException uriSyntaxException) {
throw new IOException(uriSyntaxException);
}
}
byte[] eoln = "\r\n".getBytes(targetCharset);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
for (String uri : uriList) {
byte[] bytes = uri.getBytes(targetCharset);
bos.write(bytes, 0, bytes.length);
bos.write(eoln, 0, eoln.length);
}
theByteArray = bos.toByteArray();
}
// Source data is an InputStream. For arbitrary flavors, just grab the
// bytes and dump them into a byte array. For text flavors, decode back
// to a String and recur to reencode according to the requested format.
} else if (flavor.isRepresentationClassInputStream()) {
// Workaround to JDK-8024061: Exception thrown when drag and drop
// between two components is executed quickly.
// and JDK-8065098: JColorChooser no longer supports drag and drop
// between two JVM instances
if (!(obj instanceof InputStream)) {
return new byte[0];
}
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try (InputStream is = (InputStream)obj) {
is.mark(Integer.MAX_VALUE);
is.transferTo(bos);
is.reset();
}
if (DataFlavorUtil.isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
byte[] bytes = bos.toByteArray();
String sourceEncoding = DataFlavorUtil.getTextCharset(flavor);
return translateTransferableString(
new String(bytes, sourceEncoding),
format);
}
theByteArray = bos.toByteArray();
}
// Source data is an RMI object
} else if (flavor.isRepresentationClassRemote()) {
theByteArray = convertObjectToBytes(DataFlavorUtil.RMI.newMarshalledObject(obj));
// Source data is Serializable
} else if (flavor.isRepresentationClassSerializable()) {
theByteArray = convertObjectToBytes(obj);
} else {
throw new IOException("data translation failed");
}
return theByteArray;
}
private static byte[] convertObjectToBytes(Object object) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos))
{
oos.writeObject(object);
return bos.toByteArray();
}
}
protected abstract ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList) throws IOException;
private String removeSuspectedData(DataFlavor flavor, final Transferable contents, final String str)
throws IOException
{
if (null == System.getSecurityManager()
|| !flavor.isMimeTypeEqual("text/uri-list"))
{
return str;
}
final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<String>) () -> {
StringBuilder allowedFiles = new StringBuilder(str.length());