Revision 43102 trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/java/org/gvsig/andami/Utilities.java

View differences:

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

  
......
48 47

  
49 48
import org.gvsig.andami.ui.mdiManager.IWindow;
50 49
import org.gvsig.andami.ui.splash.MultiSplashWindow;
50
import org.gvsig.tools.ToolsLocator;
51 51
import org.slf4j.Logger;
52 52
import org.slf4j.LoggerFactory;
53 53

  
54

  
55

  
56

  
57 54
/**
58
 * This class offers several general purpose method, to perform common
59
 * tasks in an easy way.
55
 * This class offers several general purpose method, to perform common tasks in
56
 * an easy way.
60 57
 *
61 58
 * @version $Revision: 29593 $
62 59
 */
63 60
public class Utilities {
64
	/**
61

  
62
    /**
65 63
     * <b>key</b>: URL, <b>value</b>: path to the downloaded file.
66 64
     */
67 65
    private static Hashtable downloadedFiles;
68
    /** DOCUMENT ME! */
69
    private static Logger logger = LoggerFactory.getLogger(Utilities.class.getName());
70
	public static final String TEMPDIRECTORYPATH = System.getProperty("java.io.tmpdir")+"/tmp-andami";
71 66

  
67
    private static final Logger logger = LoggerFactory.getLogger(Utilities.class.getName());
72 68

  
73 69
    /**
70
     * @deprecated use TemporaryFolderManager
71
     */
72
    public static final String TEMPDIRECTORYPATH = getTempDirectory();
73

  
74
    /**
75
     * @deprecated use TemporaryFolderManager.getTemporaryFolder()
76
     */
77
    public static String getTempDirectory() {
78
        return ToolsLocator.getFoldersManager().getTemporaryFolder().getAbsolutePath();
79
    }
80

  
81
    /**
82
     * Cleans every temporal file previously downloaded.
83
     * 
84
     * @deprecated use TemporaryFolderManager.cleanAll()
85
     */
86
    public static void cleanUpTempFiles() {
87
        ToolsLocator.getFoldersManager().cleanTemporaryFiles();
88
    }
89

  
90
    /**
91
     * Creates a temporary file with a the provided name and data. The file will
92
     * be automatically deleted when the application exits.
93
     *
94
     * @param fileName Name of the temporary file to create
95
     * @param data The data to store in the file
96
     * @return 
97
     * @throws java.io.IOException
98
     * 
99
     * @deprecated use TemporaryFolderManager.createTemporaryFile()
100
     */
101
    public static File createTemp(String fileName, String data) throws IOException {
102
        return ToolsLocator.getFoldersManager().createTemporaryFile(fileName, data);
103
    }
104

  
105
    /**
106
     * Creates the directory for temporary files, and returns the path of this
107
     * directory. If the directory already exists, it just returns its path. Any
108
     * file or directory created in this special directory will be delete when
109
     * the application finishes.
110
     *
111
     * @return An String containing the full path to the temporary directory
112
     * 
113
     * @deprecated use TemporaryFolderManager.createTemporaryFolder()
114
     */
115
    public static String createTempDirectory() {
116
        return ToolsLocator.getFoldersManager().createTemporaryFolder().getAbsolutePath();
117
    }
118

  
119
    /**
74 120
     * Creates an icon from an image path.
75 121
     *
76 122
     * @param path Path to the image to be loaded
......
96 142
    /**
97 143
     * Method which frees the memory from JInternalFrames
98 144
     *
99
     * @param baseComponent JInternalFrame whose memory is to be
100
     * freed
145
     * @param baseComponent JInternalFrame whose memory is to be freed
101 146
     */
102 147
    public static void cleanComponent(Component baseComponent) {
103 148
        try {
......
109 154
    /*    * The "depth" parameter was being used for text output debugging.    * But isn't essential now.  I'll keep it anyways, as it avoids    * calling the garbage collector every recursion.    */
110 155
    protected static void cleanComponent(Component baseComponent, int depth) {
111 156
        if (baseComponent == null) // recursion terminating clause
112
         {
157
        {
113 158
            return;
114 159
        }
115 160

  
116
        if (baseComponent instanceof IWindow){
117
        	return;
161
        if (baseComponent instanceof IWindow) {
162
            return;
118 163
        }
119 164

  
120 165
        Container cont;
......
142 187
                childComponents = cont.getComponents();
143 188

  
144 189
                for (int i = 0; i < numChildren; i++) //for(int i = 0;i < numChildren;i++)
145
                 {
190
                {
146 191
                    // remove each component from the current container                    // each child component may be a container itself
147 192
                    cleanComponent(childComponents[i], depth + 1);
148 193
                    cont.remove(childComponents[i]);
......
155 200
        // if component is also a container
156 201
    }
157 202

  
158

  
159

  
160 203
    /**
161 204
     * Extracts a ZIP file in the provided directory
162 205
     *
......
168 211
     * @throws IOException If there is a problem reading the file
169 212
     */
170 213
    public static void extractTo(File file, File dir, MultiSplashWindow splash)
171
        throws ZipException, IOException {
214
            throws ZipException, IOException {
172 215
        ZipFile zip = new ZipFile(file);
173 216
        Enumeration e = zip.entries();
174 217

  
175
		// Pasada para crear las carpetas
176
		while (e.hasMoreElements()) {
177
			ZipEntry entry = (ZipEntry) e.nextElement();
218
        // Pasada para crear las carpetas
219
        while (e.hasMoreElements()) {
220
            ZipEntry entry = (ZipEntry) e.nextElement();
178 221

  
179
			if (entry.isDirectory()) {
180
				File directorio = new File(dir.getAbsolutePath()
181
						+ File.separator + entry.getName());
222
            if (entry.isDirectory()) {
223
                File directorio = new File(dir.getAbsolutePath()
224
                        + File.separator + entry.getName());
182 225

  
183
				directorio.mkdirs();
184
			}
226
                directorio.mkdirs();
227
            }
185 228

  
186
    		}
229
        }
187 230

  
188
		// Pasada para crear los ficheros
189
		e = zip.entries();
190
		while (e.hasMoreElements()) {
191
			ZipEntry entry = (ZipEntry) e.nextElement();
192
			splash.process(30, "Procesando " + entry.getName() + "...");
193
			if (!entry.isDirectory()) {
194
				InputStream in = zip.getInputStream(entry);
195
				OutputStream out = new FileOutputStream(dir + File.separator
196
						+ entry.getName());
197
				BufferedInputStream bin = new BufferedInputStream(in);
198
				BufferedOutputStream bout = new BufferedOutputStream(out);
231
        // Pasada para crear los ficheros
232
        e = zip.entries();
233
        while (e.hasMoreElements()) {
234
            ZipEntry entry = (ZipEntry) e.nextElement();
235
            splash.process(30, "Procesando " + entry.getName() + "...");
236
            if (!entry.isDirectory()) {
237
                InputStream in = zip.getInputStream(entry);
238
                OutputStream out = new FileOutputStream(dir + File.separator
239
                        + entry.getName());
240
                BufferedInputStream bin = new BufferedInputStream(in);
241
                BufferedOutputStream bout = new BufferedOutputStream(out);
199 242

  
200
				int i;
243
                int i;
201 244

  
202
				while ((i = bin.read()) != -1) {
203
					bout.write(i);
204
				}
245
                while ((i = bin.read()) != -1) {
246
                    bout.write(i);
247
                }
205 248

  
206
				bout.flush();
207
				bout.close();
208
				bin.close();
249
                bout.flush();
250
                bout.close();
251
                bin.close();
209 252

  
210
			}
253
            }
211 254

  
212
		}
255
        }
213 256

  
214
		zip.close();
215
		zip = null;
216
		System.gc();
257
        zip.close();
258
        zip = null;
259
        System.gc();
217 260

  
218
	}
261
    }
262

  
219 263
    /**
220 264
     * Returns the content of this URL as a file from the file system.<br>
221 265
     * <p>
222
     * If the URL has been already downloaded in this session and notified
223
     * to the system using the static <b>Utilities.addDownloadedURL(URL)</b>
266
     * If the URL has been already downloaded in this session and notified to
267
     * the system using the static <b>Utilities.addDownloadedURL(URL)</b>
224 268
     * method, it can be restored faster from the file system avoiding to
225 269
     * download it again.
226 270
     * </p>
271
     *
227 272
     * @param url
228 273
     * @return File containing this URL's content or null if no file was found.
229 274
     */
230
    private static File getPreviousDownloadedURL(URL url){
275
    private static File getPreviousDownloadedURL(URL url) {
231 276
        File f = null;
232
        if (downloadedFiles!=null && downloadedFiles.containsKey(url)){
277
        if (downloadedFiles != null && downloadedFiles.containsKey(url)) {
233 278
            String filePath = (String) downloadedFiles.get(url);
234 279
            f = new File(filePath);
235 280
        }
......
238 283

  
239 284
    /**
240 285
     * Adds an URL to the table of downloaded files for further uses. If the URL
241
     * already exists in the table its filePath value is updated to the new one and
242
     * the old file itself is removed from the file system.
286
     * already exists in the table its filePath value is updated to the new one
287
     * and the old file itself is removed from the file system.
243 288
     *
244 289
     * @param url
245 290
     * @param filePath
246 291
     */
247
    private static void addDownloadedURL(URL url, String filePath){
248
        if (downloadedFiles==null)
292
    private static void addDownloadedURL(URL url, String filePath) {
293
        if (downloadedFiles == null) {
249 294
            downloadedFiles = new Hashtable();
295
        }
250 296
        String fileName = (String) downloadedFiles.put(url, filePath);
251 297
        //JMV: No se puede eliminar el anterior porque puede que alguien lo
252 298
        // este usando
253 299
        /*
254
        if (fileName!=null){
255
            File f = new File(fileName);
256
            if (f.exists())
257
                f.delete();
258
        }
259
        */
300
         if (fileName!=null){
301
         File f = new File(fileName);
302
         if (f.exists())
303
         f.delete();
304
         }
305
         */
260 306
    }
261 307

  
262 308
    /**
263 309
     * Downloads an URL into a temporary file that is removed the next time the
264
     * tempFileManager class is called, which means the next time gvSIG is launched.
310
     * tempFileManager class is called, which means the next time gvSIG is
311
     * launched.
265 312
     *
266 313
     * @param url
267 314
     * @param name
......
271 318
     * @throws ConnectException
272 319
     * @throws UnknownHostException
273 320
     */
274
    public static File downloadFile(URL url, String name) throws IOException,ConnectException, UnknownHostException{
275
    	File f = null;
321
    public static File downloadFile(URL url, String name) throws IOException, ConnectException, UnknownHostException {
322
        File f = null;
276 323

  
277
	    try{
278
	        if ((f=getPreviousDownloadedURL(url))==null){
279
	        	File tempDirectory = new File(TEMPDIRECTORYPATH);
280
	        	if (!tempDirectory.exists())
281
	        		tempDirectory.mkdir();
324
        try {
325
            if ((f = getPreviousDownloadedURL(url)) == null) {
326
                File tempDirectory = new File(TEMPDIRECTORYPATH);
327
                if (!tempDirectory.exists()) {
328
                    tempDirectory.mkdir();
329
                }
282 330

  
283
	        	f = new File(TEMPDIRECTORYPATH+"/"+name+System.currentTimeMillis());
331
                f = new File(TEMPDIRECTORYPATH + "/" + name + System.currentTimeMillis());
284 332

  
285
	            System.out.println("downloading '"+url.toString()+"' to: "+f.getAbsolutePath());
333
                System.out.println("downloading '" + url.toString() + "' to: " + f.getAbsolutePath());
286 334

  
287
	            f.deleteOnExit();
288
                DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)));
289
                byte[] buffer = new byte[1024*256];
335
                f.deleteOnExit();
336
                DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
337
                byte[] buffer = new byte[1024 * 256];
290 338
                InputStream is = url.openStream();
291 339
                long readed = 0;
292
                for (int i = is.read(buffer); i>0; i = is.read(buffer)){
340
                for (int i = is.read(buffer); i > 0; i = is.read(buffer)) {
293 341
                    dos.write(buffer, 0, i);
294 342
                    readed += i;
295 343
                }
296 344
                dos.close();
297 345
                addDownloadedURL(url, f.getAbsolutePath());
298
	        }
299
	    } catch (IOException io) {
300
	    	io.printStackTrace();
301
	    }
346
            }
347
        } catch (IOException io) {
348
            io.printStackTrace();
349
        }
302 350

  
303
	    return f;
304
	}
305

  
306
    /**
307
     * Cleans every temporal file previously downloaded.
308
     */
309
    public static void cleanUpTempFiles() {
310
    	try{
311
    		File tempDirectory = new File(TEMPDIRECTORYPATH);
312

  
313
    		File[] files = tempDirectory.listFiles();
314
    		if (files!=null) {
315
    			for (int i = 0; i < files.length; i++) {
316
    				 // s?lo por si en un futuro se necesitan crear directorios temporales
317
    				if (files[i].isDirectory())	deleteDirectory(files[i]);
318
    				files[i].delete();
319
    			}
320
    		}
321
    		tempDirectory.delete();
322
    	} catch (Exception e) {	}
323

  
351
        return f;
324 352
    }
325
    /**
326
     * Recursive directory delete.
327
     * @param f
328
     */
329
	private static void deleteDirectory(File f) {
330
		File[] files = f.listFiles();
331
		for (int i = 0; i < files.length; i++) {
332
			if (files[i].isDirectory()) deleteDirectory(files[i]);
333
			files[i].delete();
334
		}
335 353

  
336
	}
337

  
338 354
    /**
339
     * Creates a temporary file with a the provided name and data. The file
340
     * will be automatically deleted when the application exits. 
341
     * 
342
     * @param fileName Name of the temporary file to create
343
     * @param data The data to store in the file
344
     */
345
    public static File createTemp(String fileName, String data)throws IOException{
346
    	File f = new File(fileName);
347
    	DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)) );
348
		dos.writeBytes(data);
349
		dos.close();
350
    	f.deleteOnExit();
351
    	return f;
352
    }
353

  
354
    /**
355 355
     * Remove an URL from the system cache. The file will remain in the file
356 356
     * system for further eventual uses.
357
     *
357 358
     * @param request
358 359
     */
359
	public static void removeURL(URL url) {
360
		if (downloadedFiles != null && downloadedFiles.containsKey(url))
361
			downloadedFiles.remove(url);
362
	}
363
	
364
	/**
365
	 * Creates the directory for temporary files, and returns the path of
366
	 * this directory. If the directory already exists, it just returns
367
	 * its path. Any file or directory created in this special directory
368
	 * will be delete when the application finishes.
369
	 * 
370
	 * @return An String containing the full path to the temporary directory
371
	 */
372
	public static String createTempDirectory(){
373
		File tempDirectory = new File(TEMPDIRECTORYPATH);
374
    	if (!tempDirectory.exists())
375
    		tempDirectory.mkdir();
376
    	return TEMPDIRECTORYPATH;
377
	}
360
    public static void removeURL(URL url) {
361
        if (downloadedFiles != null && downloadedFiles.containsKey(url)) {
362
            downloadedFiles.remove(url);
363
        }
364
    }
365

  
378 366
}

Also available in: Unified diff