1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.xnap.commons.gui.dnd;
22
23 import java.awt.datatransfer.DataFlavor;
24 import java.awt.datatransfer.Transferable;
25 import java.awt.datatransfer.UnsupportedFlavorException;
26 import java.io.File;
27 import java.io.IOException;
28 import java.net.URL;
29 import java.util.Iterator;
30 import java.util.List;
31
32 /***
33 * Implements the {@link Transferable} interface for files thereby supporting
34 * the flavors {@link DataFlavor#javaFileListFlavor} and
35 * {@link org.xnap.commons.gui.dnd.AbstractFileTransferHandler#linuxURIFlavor}.
36 *
37 * @author Felix Berger
38 */
39 public class FileTransferable implements Transferable
40 {
41 private final List<File> files;
42
43 /***
44 * Constructs a transferable for a list of files.
45 * <p>
46 * The list is not copied, so it should not be modified from the outside.
47 *
48 * @param files list of files to be transferred, must not be <code>null</code>
49 *
50 * @throws NullPointerException if <code>files</code> is null
51 */
52 public FileTransferable(List<File> files)
53 {
54 if (files == null) {
55 throw new NullPointerException("files must not be null");
56 }
57 this.files = files;
58 }
59
60 public DataFlavor[] getTransferDataFlavors()
61 {
62 return new DataFlavor[] {
63 DataFlavor.javaFileListFlavor,
64 AbstractFileTransferHandler.linuxURIFlavor
65 };
66 }
67
68 public boolean isDataFlavorSupported(DataFlavor flavor)
69 {
70 return DataFlavor.javaFileListFlavor.equals(flavor)
71 || AbstractFileTransferHandler.linuxURIFlavor.equals(flavor);
72 }
73
74 public Object getTransferData(DataFlavor flavor)
75 throws UnsupportedFlavorException, IOException {
76 if (DataFlavor.javaFileListFlavor.equals(flavor)) {
77 return files;
78 }
79 else if (AbstractFileTransferHandler.linuxURIFlavor.equals(flavor)) {
80 StringBuilder sb = new StringBuilder();
81 String lineSep = System.getProperty("line.separator");
82 for (Iterator<File> i = files.iterator(); i.hasNext();) {
83 File file = i.next();
84 URL url = file.toURL();
85 if (sb.length() > 0) {
86 sb.append(lineSep);
87 }
88 sb.append(url.toExternalForm());
89 }
90 return sb.toString();
91 }
92 else {
93 throw new UnsupportedFlavorException(flavor);
94 }
95 }
96
97 }