]> git.argeo.org Git - lgpl/argeo-commons.git/blob - FileHandler.java
53285b4f03f2a2f020654f21350a25fdc73a067f
[lgpl/argeo-commons.git] / FileHandler.java
1 package org.argeo.eclipse.ui.specific;
2
3 import java.awt.Desktop;
4 import java.io.File;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9
10 import org.apache.commons.io.IOUtils;
11 import org.argeo.ArgeoException;
12
13 /**
14 * Abstraction that enable to implement runtime environment specific (typically
15 * RCP or RAP) methods while dealing with files in the UI.
16 *
17 */
18 public class FileHandler {
19
20 private FileProvider provider;
21
22 public FileHandler(FileProvider provider) {
23 this.provider = provider;
24 }
25
26 public void openFile(String fileName, String fileId) {
27 String tmpFileName = fileName;
28 String prefix = "", extension = "";
29 if (fileName != null) {
30 int ind = fileName.lastIndexOf('.');
31 if (ind > 0) {
32 prefix = fileName.substring(0, ind);
33 extension = fileName.substring(ind);
34 }
35 }
36
37 InputStream is = null;
38 try {
39 is = provider.getInputStreamFromFileId(fileId);
40 File file = createTmpFile(prefix, extension, is);
41 tmpFileName = file.getName();
42 Desktop desktop = null;
43 if (Desktop.isDesktopSupported()) {
44 desktop = Desktop.getDesktop();
45 }
46 desktop.open(file);
47 } catch (IOException e) {
48 // Note : tmpFileName = fileName if the error has been thrown while
49 // creating the tmpFile.
50 throw new ArgeoException("Cannot open file " + tmpFileName, e);
51 } finally {
52 IOUtils.closeQuietly(is);
53 }
54 }
55
56 private File createTmpFile(String prefix, String suffix, InputStream is) {
57 File tmpFile = null;
58 OutputStream os = null;
59 try {
60 tmpFile = File.createTempFile(prefix, suffix);
61 os = new FileOutputStream(tmpFile);
62 IOUtils.copy(is, os);
63 } catch (IOException e) {
64 throw new ArgeoException("Cannot open file " + prefix + "."
65 + suffix, e);
66 } finally {
67 IOUtils.closeQuietly(os);
68 }
69 return tmpFile;
70 }
71 }