Statistics
| Revision:

gvsig-tools / org.gvsig.tools / library / trunk / org.gvsig.tools / org.gvsig.tools.lib / src / main / java / org / gvsig / tools / folders / impl / DefaultFoldersManager.java @ 2115

History | View | Annotate | Download (8.58 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.tools.folders.impl;
25

    
26
import java.io.File;
27
import java.io.FileOutputStream;
28
import java.io.IOException;
29
import java.lang.management.ManagementFactory;
30
import java.lang.management.RuntimeMXBean;
31
import java.util.HashMap;
32
import java.util.Iterator;
33
import java.util.Map;
34
import javax.swing.filechooser.FileSystemView;
35
import org.apache.commons.io.FileUtils;
36
import org.apache.commons.io.FilenameUtils;
37
import org.apache.commons.io.IOUtils;
38
import org.apache.commons.lang3.StringUtils;
39
import org.apache.commons.lang3.tuple.ImmutablePair;
40
import org.gvsig.tools.folders.FoldersManager;
41
import org.slf4j.Logger;
42
import org.slf4j.LoggerFactory;
43

    
44
public class DefaultFoldersManager implements FoldersManager {
45

    
46
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultFoldersManager.class);
47

    
48
    private File temporaryFolder;
49
    private Map<String, File> folders;
50
    private int uniqueCounter = 1;
51

    
52
    public DefaultFoldersManager() {
53
        String temp = System.getenv("GVSIG_TEMP");
54
        File f;
55
        if (StringUtils.isEmpty(temp)) {
56
            temp = FileUtils.getTempDirectoryPath();
57
            // f = FileUtils.getFile(temp, "tmp-gvsig"+getPID());
58
            f = FileUtils.getFile(temp, "tmp-gvsig");
59
        } else {
60
            f = new File(temp);
61
        }
62
        this.setTemporaryFolder(f);
63
        Runtime.getRuntime().addShutdownHook(new Thread() {
64

    
65
            @Override
66
            public void run() {
67
                cleanTemporaryFiles();
68
            }
69
        });
70
    }
71

    
72
    private Map<String, File> getFolders() {
73
        if( this.folders == null ) {
74
            this.folders = new HashMap<>();
75
        }
76
        return this.folders;
77
    }
78
    
79
    @Override
80
    public boolean isEmpty() {
81
        return this.folders == null || this.folders.isEmpty();
82
    }
83

    
84
    @Override
85
    public void setLastPath(String pathId, File path) {
86
        if( StringUtils.isBlank(pathId) ) {
87
            throw new IllegalArgumentException("Invalid argument pathId, it is a blank string.");
88
        }
89
        this.getFolders().put("last.path." + pathId, path);
90
    }
91

    
92
    @Override
93
    public File getLastPath(String pathId) {
94
      return this.getLastPath(pathId, null);
95
    }
96
    
97
    @Override
98
    public File getLastPath(String pathId, File defaultValue) {
99
        if( !StringUtils.isBlank(pathId) ) {
100
            File path = this.getFolders().get("last.path." + pathId);
101

    
102
            if (path != null) {
103
                return path;
104
            }
105
        }
106
        if (defaultValue != null) {
107
            return defaultValue;
108
        }
109
        return FileSystemView.getFileSystemView().getHomeDirectory();
110
    }
111

    
112
    @Override
113
    public Iterator<Map.Entry<String, File>> lastPathsIterator() {
114
        final Iterator<Map.Entry<String, File>> it0 = this.getFolders().entrySet().iterator();
115
        Iterator<Map.Entry<String, File>> it = new Iterator<Map.Entry<String, File>>() {
116
            Map.Entry<String, File> last = null;
117
            @Override
118
            public boolean hasNext() {
119
                while(it0.hasNext() ) {
120
                    last = it0.next();
121
                    if( StringUtils.startsWithIgnoreCase(last.getKey(), "last.path.")) {
122
                        return true;
123
                    }
124
                }
125
                return false;
126
            }
127

    
128
            @Override
129
            public Map.Entry<String, File> next() {
130
                if( last==null ) {
131
                    return null;
132
                }
133
                return new ImmutablePair<>(
134
                        last.getKey().substring(10),
135
                        last.getValue()
136
                );
137
            }
138
        };
139
        return it;
140
    }
141
    
142
    @SuppressWarnings("UseSpecificCatch")
143
    private int getPID() {
144
        try {
145
            RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
146
            int java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("@")));
147
            return java_pid;
148
        } catch (Throwable th) {
149
            return 0;
150
        }
151
    }
152

    
153
    @Override
154
    public File getTemporaryFolder() {
155
        return this.temporaryFolder;
156
    }
157

    
158
    @Override
159
    public final void setTemporaryFolder(File folder) {
160
        if (folder == null) {
161
            throw new IllegalArgumentException("Can't set temporary folder to null.");
162
        }
163
        this.temporaryFolder = folder.getAbsoluteFile();
164
        this.createTemporaryFolder();
165
    }
166

    
167
    @Override
168
    public void cleanTemporaryFiles() {
169
        if (this.temporaryFolder == null) {
170
            LOGGER.warn("Can't clean temporary folder, is null.");
171
        }
172
        try {
173
            FileUtils.cleanDirectory(this.temporaryFolder);
174
        } catch (IOException ex) {
175
            LOGGER.warn("Can't clean temporary folder (" + this.temporaryFolder.getAbsolutePath() + ").", ex);
176
        }
177
    }
178

    
179
    @Override
180
    public File createTemporaryFolder() {
181
        if (this.temporaryFolder == null) {
182
            throw new RuntimeException("Can't create temporary folder, is null.");
183
        }
184
        try {
185
            FileUtils.forceMkdir(temporaryFolder);
186
        } catch (IOException ex) {
187
            throw new RuntimeException("Can't create temporary folder", ex);
188
        }
189
        return this.temporaryFolder;
190
    }
191

    
192
    @Override
193
    public File getTemporaryFile(String... pathComponents) {
194
        if (this.temporaryFolder == null) {
195
            throw new RuntimeException("Can't get temporary file, temporary folder is null.");
196
        }
197
        File f = FileUtils.getFile(temporaryFolder, pathComponents);
198
        return f;
199
    }
200

    
201
    @Override
202
    public File getUniqueTemporaryFile(String... pathComponents) {
203
        File f = getTemporaryFile(pathComponents);
204
        String fullName = f.getAbsolutePath();
205
        String name = FilenameUtils.removeExtension(fullName);
206
        String extension = FilenameUtils.getExtension(fullName);
207
        if (StringUtils.isEmpty(extension)) {
208
            fullName = name + "-" + Integer.toHexString(uniqueCounter) + "-" + Long.toHexString(System.currentTimeMillis());
209
        } else {
210
            fullName = name + "-" + Integer.toHexString(uniqueCounter) + "-" + Long.toHexString(System.currentTimeMillis()) + "." + extension;
211
        }
212
        uniqueCounter++;
213
        return new File(fullName);
214
    }
215

    
216
    @Override
217
    public File createTemporaryFile(String basename, byte[] data) {
218
        if (this.temporaryFolder == null) {
219
            throw new RuntimeException("Can't create temporary file, temporary folder is null.");
220
        }
221
        File f = getTemporaryFile(basename);
222

    
223
        FileOutputStream fos = null;
224
        try {
225
            fos = new FileOutputStream(f);
226
            IOUtils.write(data, fos);
227
            f.deleteOnExit();
228
            return f;
229
        } catch (IOException ex) {
230
            throw new RuntimeException("Can't create temporaru file '" + f.getAbsolutePath() + "'.");
231
        } finally {
232
            IOUtils.closeQuietly(fos);
233
        }
234
    }
235

    
236
    @Override
237
    public File createTemporaryFile(String basename, String data) throws IOException {
238
        return this.createTemporaryFile(basename, data.getBytes());
239
    }
240

    
241
    @Override
242
    public void set(String id, File file) {
243
        this.getFolders().put(id, file);
244
    }
245

    
246
    @Override
247
    public File get(String id) {
248
        return this.getFolders().get(id);
249
    }
250

    
251
    @Override
252
    public File get(String id, File defaultValue) {
253
        if (this.getFolders().containsKey(id)) {
254
            return this.getFolders().get(id);
255
        }
256
        return defaultValue;
257
    }
258

    
259
    @Override
260
    public File getHome() {
261
        File home = new File(System.getProperty("user.home"));
262
        return home;
263
    }
264
    
265
    @Override
266
    public Iterator<String> iterator() {
267
        return this.getFolders().keySet().iterator();
268
    }
269

    
270
}