]> git.argeo.org Git - lgpl/argeo-commons.git/blob - base/runtime/org.argeo.eclipse.ui.rcp/src/main/java/org/argeo/eclipse/ui/specific/FileHandler.java
new proposal to address the generic "open file" issue using a cleaner strategy.
[lgpl/argeo-commons.git] / base / runtime / org.argeo.eclipse.ui.rcp / src / main / java / org / argeo / eclipse / ui / specific / FileHandler.java
1 /*
2 * Copyright (C) 2007-2012 Argeo GmbH
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.argeo.eclipse.ui.specific;
17
18 import java.awt.Desktop;
19 import java.io.File;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24
25 import org.apache.commons.io.IOUtils;
26 import org.argeo.ArgeoException;
27
28 /**
29 * Abstraction that enable to implement runtime environment specific (typically
30 * RCP or RAP) methods while dealing with files in the UI.
31 *
32 */
33 public class FileHandler {
34
35 private FileProvider provider;
36
37 public FileHandler(FileProvider provider) {
38 this.provider = provider;
39 }
40
41 public void openFile(String fileName, String fileId) {
42 String tmpFileName = fileName;
43 String prefix = "", extension = "";
44 if (fileName != null) {
45 int ind = fileName.lastIndexOf('.');
46 if (ind > 0) {
47 prefix = fileName.substring(0, ind);
48 extension = fileName.substring(ind);
49 }
50 }
51
52 InputStream is = null;
53 try {
54 is = provider.getInputStreamFromFileId(fileId);
55 File file = createTmpFile(prefix, extension, is);
56 tmpFileName = file.getName();
57 Desktop desktop = null;
58 if (Desktop.isDesktopSupported()) {
59 desktop = Desktop.getDesktop();
60 }
61 desktop.open(file);
62 } catch (IOException e) {
63 // Note : tmpFileName = fileName if the error has been thrown while
64 // creating the tmpFile.
65 throw new ArgeoException("Cannot open file " + tmpFileName, e);
66 } finally {
67 IOUtils.closeQuietly(is);
68 }
69 }
70
71 private File createTmpFile(String prefix, String suffix, InputStream is) {
72 File tmpFile = null;
73 OutputStream os = null;
74 try {
75 tmpFile = File.createTempFile(prefix, suffix);
76 os = new FileOutputStream(tmpFile);
77 IOUtils.copy(is, os);
78 } catch (IOException e) {
79 throw new ArgeoException("Cannot open file " + prefix + "."
80 + suffix, e);
81 } finally {
82 IOUtils.closeQuietly(os);
83 }
84 return tmpFile;
85 }
86 }