Statistics
| Revision:

root / branches / v2_0_0_prep / frameworks / _fwAndami / src / org / gvsig / andami / Utilities.java @ 29593

History | View | Annotate | Download (12.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004-2007 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package org.gvsig.andami;
42

    
43
import java.awt.Component;
44
import java.awt.Container;
45
import java.io.BufferedInputStream;
46
import java.io.BufferedOutputStream;
47
import java.io.DataOutputStream;
48
import java.io.File;
49
import java.io.FileOutputStream;
50
import java.io.IOException;
51
import java.io.InputStream;
52
import java.io.OutputStream;
53
import java.net.ConnectException;
54
import java.net.MalformedURLException;
55
import java.net.URL;
56
import java.net.UnknownHostException;
57
import java.util.Enumeration;
58
import java.util.Hashtable;
59
import java.util.zip.ZipEntry;
60
import java.util.zip.ZipException;
61
import java.util.zip.ZipFile;
62

    
63
import javax.swing.ImageIcon;
64
import javax.swing.RootPaneContainer;
65

    
66
import org.gvsig.andami.ui.mdiManager.IWindow;
67
import org.gvsig.andami.ui.splash.MultiSplashWindow;
68
import org.slf4j.Logger;
69
import org.slf4j.LoggerFactory;
70

    
71

    
72

    
73

    
74
/**
75
 * This class offers several general purpose method, to perform common
76
 * tasks in an easy way.
77
 *
78
 * @version $Revision: 29593 $
79
 */
80
public class Utilities {
81
        /**
82
     * <b>key</b>: URL, <b>value</b>: path to the downloaded file.
83
     */
84
    private static Hashtable downloadedFiles;
85
    /** DOCUMENT ME! */
86
    private static Logger logger = LoggerFactory.getLogger(Utilities.class.getName());
87
        public static final String TEMPDIRECTORYPATH = System.getProperty("java.io.tmpdir")+"/tmp-andami";
88

    
89

    
90
    /**
91
     * Creates an icon from an image path.
92
     *
93
     * @param path Path to the image to be loaded
94
     *
95
     * @return ImageIcon if the image is found, null otherwise
96
     */
97
    public static ImageIcon createImageIcon(String path) {
98
        URL imgURL = null;
99

    
100
        try {
101
            imgURL = new URL("file:" + path);
102
        } catch (MalformedURLException e) {
103
            e.printStackTrace();
104
        }
105

    
106
        if (imgURL != null) {
107
            return new ImageIcon(imgURL);
108
        } else {
109
            return null;
110
        }
111
    }
112

    
113
    /**
114
     * Method which frees the memory from JInternalFrames
115
     *
116
     * @param baseComponent JInternalFrame whose memory is to be
117
     * freed
118
     */
119
    public static void cleanComponent(Component baseComponent) {
120
        try {
121
            cleanComponent(baseComponent, 0);
122
        } catch (Exception ignore) { // give some exception handling...
123
        }
124
    }
125

    
126
    /*    * 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.    */
127
    protected static void cleanComponent(Component baseComponent, int depth) {
128
        if (baseComponent == null) // recursion terminating clause
129
         {
130
            return;
131
        }
132

    
133
        if (baseComponent instanceof IWindow){
134
                return;
135
        }
136

    
137
        Container cont;
138
        Component[] childComponents;
139
        int numChildren; // clean up component containers
140

    
141
        if (baseComponent instanceof Container) { // now clean up container instance variables
142

    
143
            if (baseComponent instanceof RootPaneContainer) { // Swing specialised container
144
                cont = (Container) baseComponent;
145
                numChildren = cont.getComponentCount();
146
                childComponents = cont.getComponents();
147

    
148
                for (int i = 0; i < numChildren; i++) { // remove each component from the current container
149

    
150
                    // each child component may be a container itself
151
                    cleanComponent(childComponents[i], depth + 1);
152
                    ((RootPaneContainer) cont).getContentPane().remove(childComponents[i]);
153
                }
154

    
155
                ((RootPaneContainer) cont).getContentPane().setLayout(null);
156
            } else { // General Swing, and AWT, Containers
157
                cont = (Container) baseComponent;
158
                numChildren = cont.getComponentCount();
159
                childComponents = cont.getComponents();
160

    
161
                for (int i = 0; i < numChildren; i++) //for(int i = 0;i < numChildren;i++)
162
                 {
163
                    // remove each component from the current container                    // each child component may be a container itself
164
                    cleanComponent(childComponents[i], depth + 1);
165
                    cont.remove(childComponents[i]);
166
                }
167

    
168
                cont.setLayout(null);
169
            }
170
        }
171

    
172
        // if component is also a container
173
    }
174

    
175

    
176

    
177
    /**
178
     * Extracts a ZIP file in the provided directory
179
     *
180
     * @param file Compressed file
181
     * @param dir Directory to extract the files
182
     * @param splash The splash window to show the extraction progress
183
     *
184
     * @throws ZipException If there is some problem in the file format
185
     * @throws IOException If there is a problem reading the file
186
     */
187
    public static void extractTo(File file, File dir, MultiSplashWindow splash)
188
        throws ZipException, IOException {
189
        ZipFile zip = new ZipFile(file);
190
        Enumeration e = zip.entries();
191

    
192
                // Pasada para crear las carpetas
193
                while (e.hasMoreElements()) {
194
                        ZipEntry entry = (ZipEntry) e.nextElement();
195

    
196
                        if (entry.isDirectory()) {
197
                                File directorio = new File(dir.getAbsolutePath()
198
                                                + File.separator + entry.getName());
199

    
200
                                directorio.mkdirs();
201
                        }
202

    
203
                    }
204

    
205
                // Pasada para crear los ficheros
206
                e = zip.entries();
207
                while (e.hasMoreElements()) {
208
                        ZipEntry entry = (ZipEntry) e.nextElement();
209
                        splash.process(30, "Procesando " + entry.getName() + "...");
210
                        if (!entry.isDirectory()) {
211
                                InputStream in = zip.getInputStream(entry);
212
                                OutputStream out = new FileOutputStream(dir + File.separator
213
                                                + entry.getName());
214
                                BufferedInputStream bin = new BufferedInputStream(in);
215
                                BufferedOutputStream bout = new BufferedOutputStream(out);
216

    
217
                                int i;
218

    
219
                                while ((i = bin.read()) != -1) {
220
                                        bout.write(i);
221
                                }
222

    
223
                                bout.flush();
224
                                bout.close();
225
                                bin.close();
226

    
227
                        }
228

    
229
                }
230

    
231
                zip.close();
232
                zip = null;
233
                System.gc();
234

    
235
        }
236
    /**
237
     * Returns the content of this URL as a file from the file system.<br>
238
     * <p>
239
     * If the URL has been already downloaded in this session and notified
240
     * to the system using the static <b>Utilities.addDownloadedURL(URL)</b>
241
     * method, it can be restored faster from the file system avoiding to
242
     * download it again.
243
     * </p>
244
     * @param url
245
     * @return File containing this URL's content or null if no file was found.
246
     */
247
    private static File getPreviousDownloadedURL(URL url){
248
        File f = null;
249
        if (downloadedFiles!=null && downloadedFiles.containsKey(url)){
250
            String filePath = (String) downloadedFiles.get(url);
251
            f = new File(filePath);
252
        }
253
        return f;
254
    }
255

    
256
    /**
257
     * Adds an URL to the table of downloaded files for further uses. If the URL
258
     * already exists in the table its filePath value is updated to the new one and
259
     * the old file itself is removed from the file system.
260
     *
261
     * @param url
262
     * @param filePath
263
     */
264
    private static void addDownloadedURL(URL url, String filePath){
265
        if (downloadedFiles==null)
266
            downloadedFiles = new Hashtable();
267
        String fileName = (String) downloadedFiles.put(url, filePath);
268
        //JMV: No se puede eliminar el anterior porque puede que alguien lo
269
        // este usando
270
        /*
271
        if (fileName!=null){
272
            File f = new File(fileName);
273
            if (f.exists())
274
                f.delete();
275
        }
276
        */
277
    }
278

    
279
    /**
280
     * Downloads an URL into a temporary file that is removed the next time the
281
     * tempFileManager class is called, which means the next time gvSIG is launched.
282
     *
283
     * @param url
284
     * @param name
285
     * @return
286
     * @throws IOException
287
     * @throws ServerErrorResponseException
288
     * @throws ConnectException
289
     * @throws UnknownHostException
290
     */
291
    public static File downloadFile(URL url, String name) throws IOException,ConnectException, UnknownHostException{
292
            File f = null;
293

    
294
            try{
295
                if ((f=getPreviousDownloadedURL(url))==null){
296
                        File tempDirectory = new File(TEMPDIRECTORYPATH);
297
                        if (!tempDirectory.exists())
298
                                tempDirectory.mkdir();
299

    
300
                        f = new File(TEMPDIRECTORYPATH+"/"+name+System.currentTimeMillis());
301

    
302
                    System.out.println("downloading '"+url.toString()+"' to: "+f.getAbsolutePath());
303

    
304
                    f.deleteOnExit();
305
                DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)));
306
                byte[] buffer = new byte[1024*256];
307
                InputStream is = url.openStream();
308
                long readed = 0;
309
                for (int i = is.read(buffer); i>0; i = is.read(buffer)){
310
                    dos.write(buffer, 0, i);
311
                    readed += i;
312
                }
313
                dos.close();
314
                addDownloadedURL(url, f.getAbsolutePath());
315
                }
316
            } catch (IOException io) {
317
                    io.printStackTrace();
318
            }
319

    
320
            return f;
321
        }
322

    
323
    /**
324
     * Cleans every temporal file previously downloaded.
325
     */
326
    public static void cleanUpTempFiles() {
327
            try{
328
                    File tempDirectory = new File(TEMPDIRECTORYPATH);
329

    
330
                    File[] files = tempDirectory.listFiles();
331
                    if (files!=null) {
332
                            for (int i = 0; i < files.length; i++) {
333
                                     // s?lo por si en un futuro se necesitan crear directorios temporales
334
                                    if (files[i].isDirectory())        deleteDirectory(files[i]);
335
                                    files[i].delete();
336
                            }
337
                    }
338
                    tempDirectory.delete();
339
            } catch (Exception e) {        }
340

    
341
    }
342
    /**
343
     * Recursive directory delete.
344
     * @param f
345
     */
346
        private static void deleteDirectory(File f) {
347
                File[] files = f.listFiles();
348
                for (int i = 0; i < files.length; i++) {
349
                        if (files[i].isDirectory()) deleteDirectory(files[i]);
350
                        files[i].delete();
351
                }
352

    
353
        }
354

    
355
    /**
356
     * Creates a temporary file with a the provided name and data. The file
357
     * will be automatically deleted when the application exits. 
358
     * 
359
     * @param fileName Name of the temporary file to create
360
     * @param data The data to store in the file
361
     */
362
    public static File createTemp(String fileName, String data)throws IOException{
363
            File f = new File(fileName);
364
            DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)) );
365
                dos.writeBytes(data);
366
                dos.close();
367
            f.deleteOnExit();
368
            return f;
369
    }
370

    
371
    /**
372
     * Remove an URL from the system cache. The file will remain in the file
373
     * system for further eventual uses.
374
     * @param request
375
     */
376
        public static void removeURL(URL url) {
377
                if (downloadedFiles != null && downloadedFiles.containsKey(url))
378
                        downloadedFiles.remove(url);
379
        }
380
        
381
        /**
382
         * Creates the directory for temporary files, and returns the path of
383
         * this directory. If the directory already exists, it just returns
384
         * its path. Any file or directory created in this special directory
385
         * will be delete when the application finishes.
386
         * 
387
         * @return An String containing the full path to the temporary directory
388
         */
389
        public static String createTempDirectory(){
390
                File tempDirectory = new File(TEMPDIRECTORYPATH);
391
            if (!tempDirectory.exists())
392
                    tempDirectory.mkdir();
393
            return TEMPDIRECTORYPATH;
394
        }
395
}