3090 lines · 116.7 KB · Java
RawDownload
        } catch (PrivilegedActionException pae) {            throw new IOException(pae.getMessage());        }        return fileList;    }     // It is important do not use user's successors    // of File class.    private File castToFile(Object fileObject) throws IOException {        String filePath = null;        if (fileObject instanceof File) {            filePath = ((File)fileObject).getCanonicalPath();        } else if (fileObject instanceof String) {           filePath = (String) fileObject;        } else {           return null;        }        return new File(filePath);    }     private final static String[] DEPLOYMENT_CACHE_PROPERTIES = {        "deployment.system.cachedir",        "deployment.user.cachedir",        "deployment.javaws.cachedir",        "deployment.javapi.cachedir"    };     private final static ArrayList <File> deploymentCacheDirectoryList =            new ArrayList<File>();     private static boolean isFileInWebstartedCache(File f) {         if (deploymentCacheDirectoryList.isEmpty()) {            for (String cacheDirectoryProperty : DEPLOYMENT_CACHE_PROPERTIES) {                String cacheDirectoryPath = System.getProperty(cacheDirectoryProperty);                if (cacheDirectoryPath != null) {                    try {                        File cacheDirectory = (new File(cacheDirectoryPath)).getCanonicalFile();                        if (cacheDirectory != null) {                            deploymentCacheDirectoryList.add(cacheDirectory);                        }                    } catch (IOException ioe) {}                }            }        }         for (File deploymentCacheDirectory : deploymentCacheDirectoryList) {            for (File dir = f; dir != null; dir = dir.getParentFile()) {                if (dir.equals(deploymentCacheDirectory)) {                    return true;                }            }        }         return false;    }      public Object translateBytes(byte[] bytes, DataFlavor flavor,                                 long format, Transferable localeTransferable)        throws IOException    {        return translateBytesOrStream(null, bytes, flavor, format,                                      localeTransferable);    }     public Object translateStream(InputStream str, DataFlavor flavor,                                  long format, Transferable localeTransferable)        throws IOException    {        return translateBytesOrStream(str, null, flavor, format,                                      localeTransferable);    }      /**     * Primary translation function for translating either a byte array or     * an InputStream into an Object, given a source format and a target     * DataFlavor.     *     * One of str/bytes is non-null; the other is null.     * The conversion from byte[] to InputStream is cheap, so do that     * immediately if necessary. The opposite conversion is expensive,     * so avoid it if possible.     */    protected Object translateBytesOrStream(InputStream str, byte[] bytes,                                            DataFlavor flavor, long format,                                            Transferable localeTransferable)        throws IOException    {         if (str == null) {            str = new ByteArrayInputStream(bytes);        }         // Source data is a file list. Use the dragQueryFile native function to        // do most of the decoding. Then wrap File objects around the String        // filenames and return a List.        if (isFileFormat(format)) {            if (!DataFlavor.javaFileListFlavor.equals(flavor)) {                throw new IOException("data translation failed");            }            if (bytes == null) {                bytes = inputStreamToByteArray(str);            }            String[] filenames = dragQueryFile(bytes);            if (filenames == null) {                str.close();                return null;            }             // Convert the strings to File objects            File[] files = new File[filenames.length];            for (int i = 0; i < filenames.length; i++) {                files[i] = new File(filenames[i]);            }            str.close();             // Turn the list of Files into a List and return            return Arrays.asList(files);         // Source data is a URI list. Convert to DataFlavor.javaFileListFlavor        // where possible.        } else if (isURIListFormat(format) && DataFlavor.javaFileListFlavor.equals(flavor)) {            try {                URI uris[] = dragQueryURIs(str, bytes, format, localeTransferable);                if (uris == null) {                    return null;                }                ArrayList files = new ArrayList();                for (URI uri : uris) {                    try {                        files.add(new File(uri));                    } catch (IllegalArgumentException illegalArg) {                        // When converting from URIs to less generic files,                        // common practice (Wine, SWT) seems to be to                        // silently drop the URIs that aren't local files.                    }                }                return files;            } finally {                str.close();            }         // Target data is a String. Strip terminating NUL bytes. Decode bytes        // into characters. Search-and-replace EOLN.        } else if (String.class.equals(flavor.getRepresentationClass()) &&                   isFlavorCharsetTextType(flavor) && isTextFormat(format)) {             return translateBytesOrStreamToString(                str, bytes,                format, localeTransferable);         // Special hack to maintain backwards-compatibility with the brokenness        // of StringSelection. Return a StringReader instead of an InputStream.        // Recur to obtain String and encapsulate.        } else if (DataFlavor.plainTextFlavor.equals(flavor)) {            return new StringReader(translateBytesOrStreamToString(                        str, bytes,                        format, localeTransferable));         // Target data is an InputStream. For arbitrary flavors, just return        // the raw bytes. For text flavors, decode to strip terminators and        // search-and-replace EOLN, then reencode according to the requested        // flavor.        } else if (flavor.isRepresentationClassInputStream()) {            return translateBytesOrStreamToInputStream(str, flavor, format,                                                       localeTransferable);         // Target data is a Reader. Obtain data in InputStream format, encoded        // as "Unicode" (utf-16be). Then use an InputStreamReader to decode        // back to chars on demand.        } else if (flavor.isRepresentationClassReader()) {            if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {                throw new IOException                    ("cannot transfer non-text data as Reader");            }             InputStream is = (InputStream)                translateBytesOrStreamToInputStream                    (str, DataFlavor.plainTextFlavor, format,                     localeTransferable);            String unicode =                DataTransferer.getTextCharset(DataFlavor.plainTextFlavor);            Reader reader = new InputStreamReader(is, unicode);             return constructFlavoredObject(reader, flavor, Reader.class);         // Target data is a CharBuffer. Recur to obtain String and wrap.        } else if (flavor.isRepresentationClassCharBuffer()) {            if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {                throw new IOException                    ("cannot transfer non-text data as CharBuffer");            }             CharBuffer buffer = CharBuffer.wrap(translateBytesOrStreamToString(                str, bytes,                format, localeTransferable));             return constructFlavoredObject(buffer, flavor, CharBuffer.class);         // Target data is a char array. Recur to obtain String and convert to        // char array.        } else if (charArrayClass.equals(flavor.getRepresentationClass())) {            if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {                throw new IOException                    ("cannot transfer non-text data as char array");            }             return translateBytesOrStreamToString(                    str, bytes,                    format, localeTransferable).toCharArray();         // Target data is a ByteBuffer. For arbitrary flavors, just return        // the raw bytes. For text flavors, convert to a String to strip        // terminators and search-and-replace EOLN, then reencode according to        // the requested flavor.        } else if (flavor.isRepresentationClassByteBuffer()) {            if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {                bytes = translateBytesOrStreamToString(                    str, bytes,                    format, localeTransferable                ).getBytes(                    DataTransferer.getTextCharset(flavor)                );            } else {                if (bytes == null) {                    bytes = inputStreamToByteArray(str);                }            }             ByteBuffer buffer = ByteBuffer.wrap(bytes);            return constructFlavoredObject(buffer, flavor, ByteBuffer.class);         // Target data is a byte array. For arbitrary flavors, just return        // the raw bytes. For text flavors, convert to a String to strip        // terminators and search-and-replace EOLN, then reencode according to        // the requested flavor.        } else if (byteArrayClass.equals(flavor.getRepresentationClass())) {            if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {                return translateBytesOrStreamToString(                    str, bytes,                    format, localeTransferable                ).getBytes(                    DataTransferer.getTextCharset(flavor)                );            } else {                return (bytes != null) ? bytes : inputStreamToByteArray(str);            }         // Target data is an RMI object        } else if (flavor.isRepresentationClassRemote()) {            try {                byte[] ba = inputStreamToByteArray(str);                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(ba));                Object ret = RMI.getMarshalledObject(ois.readObject());                ois.close();                str.close();                return ret;            } catch (Exception e) {                throw new IOException(e.getMessage());            }         // Target data is Serializable        } else if (flavor.isRepresentationClassSerializable()) {            try {                byte[] ba = inputStreamToByteArray(str);                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(ba));                Object ret = ois.readObject();                ois.close();                str.close();                return ret;            } catch (Exception e) {                throw new IOException(e.getMessage());            }         // Target data is Image        } else if (DataFlavor.imageFlavor.equals(flavor)) {            if (!isImageFormat(format)) {                throw new IOException("data translation failed");            }             Image image = platformImageBytesOrStreamToImage(str, bytes, format);            str.close();            return image;        }         throw new IOException("data translation failed");    }     /**     * For arbitrary flavors, just use the raw InputStream. For text flavors,     * ReencodingInputStream will decode and reencode the InputStream on demand     * so that we can strip terminators and search-and-replace EOLN.     */    private Object translateBytesOrStreamToInputStream        (InputStream str, DataFlavor flavor, long format,         Transferable localeTransferable) throws IOException    {        if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {            str = new ReencodingInputStream                (str, format, DataTransferer.getTextCharset(flavor),                 localeTransferable);        }         return constructFlavoredObject(str, flavor, InputStream.class);    }     /**     * We support representations which are exactly of the specified Class,     * and also arbitrary Objects which have a constructor which takes an     * instance of the Class as its sole parameter.     */    private Object constructFlavoredObject(Object arg, DataFlavor flavor,                                           Class clazz)        throws IOException    {        final Class dfrc = flavor.getRepresentationClass();         if (clazz.equals(dfrc)) {            return arg; // simple case        } else {            Constructor[] constructors = null;             try {                constructors = (Constructor[])                    AccessController.doPrivileged(new PrivilegedAction() {                            public Object run() {                                return dfrc.getConstructors();                            }                        });            } catch (SecurityException se) {                throw new IOException(se.getMessage());            }             Constructor constructor = null;             for (int j = 0; j < constructors.length; j++) {                if (!Modifier.isPublic(constructors[j].getModifiers())) {                    continue;                }                 Class[] ptypes = constructors[j].getParameterTypes();                 if (ptypes != null && ptypes.length == 1 &&                    clazz.equals(ptypes[0])) {                    constructor = constructors[j];                    break;                }            }             if (constructor == null) {                throw new IOException("can't find <init>(L"+ clazz +                                      ";)V for class: " + dfrc.getName());            }             try {                return constructor.newInstance(new Object[] { arg } );            } catch (Exception e) {                throw new IOException(e.getMessage());            }        }    }     /**     * Used for decoding and reencoding an InputStream on demand so that we     * can strip NUL terminators and perform EOLN search-and-replace.     */    public class ReencodingInputStream extends InputStream {        protected BufferedReader wrapped;        protected final char[] in = new char[1];        protected byte[] out;         protected CharsetEncoder encoder;        protected CharBuffer inBuf;        protected ByteBuffer outBuf;         protected char[] eoln;        protected int numTerminators;         protected boolean eos;        protected int index, limit;         public ReencodingInputStream(InputStream bytestream, long format,                                     String targetEncoding,                                     Transferable localeTransferable)            throws IOException        {            Long lFormat = Long.valueOf(format);             String sourceEncoding = null;            if (isLocaleDependentTextFormat(format) &&                localeTransferable != null &&                localeTransferable.                    isDataFlavorSupported(javaTextEncodingFlavor))            {                try {                    sourceEncoding = new String((byte[])localeTransferable.                                       getTransferData(javaTextEncodingFlavor),                                       "UTF-8");                } catch (UnsupportedFlavorException cannotHappen) {                }            } else {                sourceEncoding = getCharsetForTextFormat(lFormat);            }             if (sourceEncoding == null) {                // Only happens when we have a custom text type.                sourceEncoding = getDefaultTextCharset();            }            wrapped = new BufferedReader                (new InputStreamReader(bytestream, sourceEncoding));             if (targetEncoding == null) {                // Throw NullPointerException for compatibility with the former                // call to sun.io.CharToByteConverter.getConverter(null)                // (Charset.forName(null) throws unspecified IllegalArgumentException                // now; see 6228568)                throw new NullPointerException("null target encoding");            }             try {                encoder = Charset.forName(targetEncoding).newEncoder();                out = new byte[(int)(encoder.maxBytesPerChar() + 0.5)];                inBuf = CharBuffer.wrap(in);                outBuf = ByteBuffer.wrap(out);            } catch (IllegalCharsetNameException e) {                throw new IOException(e.toString());            } catch (UnsupportedCharsetException e) {                throw new IOException(e.toString());            } catch (UnsupportedOperationException e) {                throw new IOException(e.toString());            }             String sEoln = (String)nativeEOLNs.get(lFormat);            if (sEoln != null) {                eoln = sEoln.toCharArray();            }             // A hope and a prayer that this works generically. This will            // definitely work on Win32.            Integer terminators = (Integer)nativeTerminators.get(lFormat);            if (terminators != null) {                numTerminators = terminators.intValue();            }        }         public int read() throws IOException {            if (eos) {                return -1;            }             if (index >= limit) {                int c = wrapped.read();                 if (c == -1) { // -1 is EOS                    eos = true;                    return -1;                }                 // "c == 0" is not quite correct, but good enough on Windows.                if (numTerminators > 0 && c == 0) {                    eos = true;                    return -1;                } else if (eoln != null && matchCharArray(eoln, c)) {                    c = '\n' & 0xFFFF;                }                 in[0] = (char)c;                 inBuf.rewind();                outBuf.rewind();                encoder.encode(inBuf, outBuf, false);                outBuf.flip();                limit = outBuf.limit();                 index = 0;                 return read();            } else {                return out[index++] & 0xFF;            }        }         public int available() throws IOException {            return ((eos) ? 0 : (limit - index));        }         public void close() throws IOException {            wrapped.close();        }         /**         * Checks to see if the next array.length characters in wrapped         * match array. The first character is provided as c. Subsequent         * characters are read from wrapped itself. When this method returns,         * the wrapped index may be different from what it was when this         * method was called.         */        private boolean matchCharArray(char[] array, int c)

Lines 1501–2000 of 3090. Previous lines

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

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

Repository code

Go to file
t