Statistics
| Revision:

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

History | View | Annotate | Download (12.2 KB)

1 1104 fjp
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3 11996 cesar
 * Copyright (C) 2004-2007 IVER T.I. and Generalitat Valenciana.
4 1104 fjp
 *
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 29593 jpiera
package org.gvsig.andami;
42 598 fernando
43
import java.awt.Component;
44
import java.awt.Container;
45
import java.io.BufferedInputStream;
46
import java.io.BufferedOutputStream;
47 3706 jaume
import java.io.DataOutputStream;
48 598 fernando
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 3706 jaume
import java.net.ConnectException;
54 598 fernando
import java.net.MalformedURLException;
55
import java.net.URL;
56 3706 jaume
import java.net.UnknownHostException;
57 598 fernando
import java.util.Enumeration;
58 3706 jaume
import java.util.Hashtable;
59 598 fernando
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 29593 jpiera
import org.gvsig.andami.ui.mdiManager.IWindow;
67
import org.gvsig.andami.ui.splash.MultiSplashWindow;
68 27139 csanchez
import org.slf4j.Logger;
69
import org.slf4j.LoggerFactory;
70 598 fernando
71
72
73
74
/**
75 11996 cesar
 * This class offers several general purpose method, to perform common
76
 * tasks in an easy way.
77 598 fernando
 *
78
 * @version $Revision$
79
 */
80
public class Utilities {
81 3706 jaume
        /**
82
     * <b>key</b>: URL, <b>value</b>: path to the downloaded file.
83
     */
84
    private static Hashtable downloadedFiles;
85 598 fernando
    /** DOCUMENT ME! */
86 27139 csanchez
    private static Logger logger = LoggerFactory.getLogger(Utilities.class.getName());
87 8906 caballero
        public static final String TEMPDIRECTORYPATH = System.getProperty("java.io.tmpdir")+"/tmp-andami";
88 598 fernando
89 7303 caballero
90 598 fernando
    /**
91 11996 cesar
     * Creates an icon from an image path.
92 598 fernando
     *
93 11996 cesar
     * @param path Path to the image to be loaded
94 598 fernando
     *
95 11996 cesar
     * @return ImageIcon if the image is found, null otherwise
96 598 fernando
     */
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 11996 cesar
     * Method which frees the memory from JInternalFrames
115 598 fernando
     *
116 11996 cesar
     * @param baseComponent JInternalFrame whose memory is to be
117
     * freed
118 598 fernando
     */
119
    public static void cleanComponent(Component baseComponent) {
120
        try {
121
            cleanComponent(baseComponent, 0);
122 7303 caballero
        } catch (Exception ignore) { // give some exception handling...
123 598 fernando
        }
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 7303 caballero
        if (baseComponent == null) // recursion terminating clause
129 598 fernando
         {
130
            return;
131
        }
132 7303 caballero
133 6877 cesar
        if (baseComponent instanceof IWindow){
134 901 fernando
                return;
135
        }
136 598 fernando
137
        Container cont;
138
        Component[] childComponents;
139
        int numChildren; // clean up component containers
140
141 7303 caballero
        if (baseComponent instanceof Container) { // now clean up container instance variables
142 598 fernando
143 7303 caballero
            if (baseComponent instanceof RootPaneContainer) { // Swing specialised container
144 598 fernando
                cont = (Container) baseComponent;
145
                numChildren = cont.getComponentCount();
146
                childComponents = cont.getComponents();
147
148 7303 caballero
                for (int i = 0; i < numChildren; i++) { // remove each component from the current container
149 598 fernando
150 7303 caballero
                    // each child component may be a container itself
151 598 fernando
                    cleanComponent(childComponents[i], depth + 1);
152
                    ((RootPaneContainer) cont).getContentPane().remove(childComponents[i]);
153
                }
154
155
                ((RootPaneContainer) cont).getContentPane().setLayout(null);
156 7303 caballero
            } else { // General Swing, and AWT, Containers
157 598 fernando
                cont = (Container) baseComponent;
158
                numChildren = cont.getComponentCount();
159
                childComponents = cont.getComponents();
160
161 7303 caballero
                for (int i = 0; i < numChildren; i++) //for(int i = 0;i < numChildren;i++)
162 598 fernando
                 {
163 7303 caballero
                    // remove each component from the current container                    // each child component may be a container itself
164 598 fernando
                    cleanComponent(childComponents[i], depth + 1);
165
                    cont.remove(childComponents[i]);
166
                }
167
168
                cont.setLayout(null);
169
            }
170
        }
171
172 7303 caballero
        // if component is also a container
173 598 fernando
    }
174
175 7514 caballero
176
177 598 fernando
    /**
178 11996 cesar
     * Extracts a ZIP file in the provided directory
179 598 fernando
     *
180 11996 cesar
     * @param file Compressed file
181
     * @param dir Directory to extract the files
182
     * @param splash The splash window to show the extraction progress
183 598 fernando
     *
184 11996 cesar
     * @throws ZipException If there is some problem in the file format
185
     * @throws IOException If there is a problem reading the file
186 598 fernando
     */
187 7303 caballero
    public static void extractTo(File file, File dir, MultiSplashWindow splash)
188 598 fernando
        throws ZipException, IOException {
189
        ZipFile zip = new ZipFile(file);
190
        Enumeration e = zip.entries();
191
192 7514 caballero
                // Pasada para crear las carpetas
193
                while (e.hasMoreElements()) {
194
                        ZipEntry entry = (ZipEntry) e.nextElement();
195 598 fernando
196 7514 caballero
                        if (entry.isDirectory()) {
197
                                File directorio = new File(dir.getAbsolutePath()
198
                                                + File.separator + entry.getName());
199 598 fernando
200 7514 caballero
                                directorio.mkdirs();
201
                        }
202 598 fernando
203 7514 caballero
                    }
204 7303 caballero
205 7514 caballero
                // 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 3706 jaume
    /**
237
     * Returns the content of this URL as a file from the file system.<br>
238
     * <p>
239 7303 caballero
     * If the URL has been already downloaded in this session and notified
240 3706 jaume
     * 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 7303 caballero
256 3706 jaume
    /**
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 7303 caballero
     *
261 3706 jaume
     * @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 5276 jmvivo
        //JMV: No se puede eliminar el anterior porque puede que alguien lo
269
        // este usando
270
        /*
271 3706 jaume
        if (fileName!=null){
272
            File f = new File(fileName);
273
            if (f.exists())
274
                f.delete();
275
        }
276 5276 jmvivo
        */
277 3706 jaume
    }
278 7303 caballero
279 3706 jaume
    /**
280 7303 caballero
     * Downloads an URL into a temporary file that is removed the next time the
281 3706 jaume
     * tempFileManager class is called, which means the next time gvSIG is launched.
282 7303 caballero
     *
283 3706 jaume
     * @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 8906 caballero
                        File tempDirectory = new File(TEMPDIRECTORYPATH);
297 3706 jaume
                        if (!tempDirectory.exists())
298
                                tempDirectory.mkdir();
299 7303 caballero
300 8906 caballero
                        f = new File(TEMPDIRECTORYPATH+"/"+name+System.currentTimeMillis());
301 7303 caballero
302 3706 jaume
                    System.out.println("downloading '"+url.toString()+"' to: "+f.getAbsolutePath());
303 7303 caballero
304 3706 jaume
                    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 7303 caballero
320 3706 jaume
            return f;
321
        }
322
323
    /**
324
     * Cleans every temporal file previously downloaded.
325
     */
326
    public static void cleanUpTempFiles() {
327
            try{
328 8906 caballero
                    File tempDirectory = new File(TEMPDIRECTORYPATH);
329 7303 caballero
330 3706 jaume
                    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 7303 caballero
341 3706 jaume
    }
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 7303 caballero
353 3706 jaume
        }
354 7303 caballero
355 4099 fjp
    /**
356 11996 cesar
     * 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 4099 fjp
     */
362 11996 cesar
    public static File createTemp(String fileName, String data)throws IOException{
363 4099 fjp
            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 11996 cesar
            return f;
369 4099 fjp
    }
370 7303 caballero
371 4099 fjp
    /**
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 4428 jaume
                if (downloadedFiles != null && downloadedFiles.containsKey(url))
378 4424 jaume
                        downloadedFiles.remove(url);
379 4099 fjp
        }
380 11335 nacho
381
        /**
382 11996 cesar
         * 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 11335 nacho
         */
389
        public static String createTempDirectory(){
390
                File tempDirectory = new File(TEMPDIRECTORYPATH);
391
            if (!tempDirectory.exists())
392
                    tempDirectory.mkdir();
393
            return TEMPDIRECTORYPATH;
394
        }
395 598 fernando
}