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