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 @ 1990

History | View | Annotate | Download (8.47 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, File defaultValue) {
94
        if( !StringUtils.isBlank(pathId) ) {
95
            File path = this.getFolders().get("last.path." + pathId);
96

    
97
            if (path != null) {
98
                return path;
99
            }
100
        }
101
        if (defaultValue != null) {
102
            return defaultValue;
103
        }
104
        return FileSystemView.getFileSystemView().getHomeDirectory();
105
    }
106

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

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

    
148
    @Override
149
    public File getTemporaryFolder() {
150
        return this.temporaryFolder;
151
    }
152

    
153
    @Override
154
    public final void setTemporaryFolder(File folder) {
155
        if (folder == null) {
156
            throw new IllegalArgumentException("Can't set temporary folder to null.");
157
        }
158
        this.temporaryFolder = folder.getAbsoluteFile();
159
        this.createTemporaryFolder();
160
    }
161

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

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

    
187
    @Override
188
    public File getTemporaryFile(String... pathComponents) {
189
        if (this.temporaryFolder == null) {
190
            throw new RuntimeException("Can't get temporary file, temporary folder is null.");
191
        }
192
        File f = FileUtils.getFile(temporaryFolder, pathComponents);
193
        return f;
194
    }
195

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

    
211
    @Override
212
    public File createTemporaryFile(String basename, byte[] data) {
213
        if (this.temporaryFolder == null) {
214
            throw new RuntimeException("Can't create temporary file, temporary folder is null.");
215
        }
216
        File f = getTemporaryFile(basename);
217

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

    
231
    @Override
232
    public File createTemporaryFile(String basename, String data) throws IOException {
233
        return this.createTemporaryFile(basename, data.getBytes());
234
    }
235

    
236
    @Override
237
    public void set(String id, File file) {
238
        this.getFolders().put(id, file);
239
    }
240

    
241
    @Override
242
    public File get(String id) {
243
        return this.getFolders().get(id);
244
    }
245

    
246
    @Override
247
    public File get(String id, File defaultValue) {
248
        if (this.getFolders().containsKey(id)) {
249
            return this.getFolders().get(id);
250
        }
251
        return defaultValue;
252
    }
253

    
254
    @Override
255
    public File getHome() {
256
        File home = new File(System.getProperty("user.home"));
257
        return home;
258
    }
259
    
260
    @Override
261
    public Iterator<String> iterator() {
262
        return this.getFolders().keySet().iterator();
263
    }
264

    
265
}