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

History | View | Annotate | Download (8.44 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 java.util.Set;
35
import javax.swing.filechooser.FileSystemView;
36
import org.apache.commons.io.FileUtils;
37
import org.apache.commons.io.FilenameUtils;
38
import org.apache.commons.io.IOUtils;
39
import org.apache.commons.lang3.StringUtils;
40
import org.apache.commons.lang3.tuple.ImmutablePair;
41
import org.gvsig.tools.folders.FoldersManager;
42
import org.slf4j.Logger;
43
import org.slf4j.LoggerFactory;
44

    
45
public class DefaultFoldersManager implements FoldersManager {
46

    
47
    private static final Logger logger = LoggerFactory.getLogger(DefaultFoldersManager.class);
48

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

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

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

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

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

    
93
    @Override
94
    public File getLastPath(String pathId, File defaultValue) {
95
        if( !StringUtils.isBlank(pathId) ) {
96
            File path = this.getFolders().get("last.path." + pathId);
97

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

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

    
124
            @Override
125
            public Map.Entry<String, File> next() {
126
                if( last==null ) {
127
                    return null;
128
                }
129
                return new ImmutablePair<>(
130
                        last.getKey().substring(10),
131
                        last.getValue()
132
                );
133
            }
134
        };
135
        return it;
136
    }
137
    
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 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 + "-" + Long.toHexString(System.currentTimeMillis()) + "-" + Integer.toHexString(uniqueCounter);
204
        } else {
205
            fullName = name + "-" + Long.toHexString(System.currentTimeMillis()) + "-" + Integer.toHexString(uniqueCounter) + "." + 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
}