Statistics
| Revision:

svn-gvsig-desktop / branches / v10 / frameworks / _fwAndami / src / com / iver / andami / Utilities.java @ 7167

History | View | Annotate | Download (11.6 KB)

1 1104 fjp
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 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 598 fernando
package com.iver.andami;
42
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
import org.apache.log4j.Logger;
67
68
import com.iver.andami.ui.SplashWindow;
69 6877 cesar
import com.iver.andami.ui.mdiManager.IWindow;
70 598 fernando
71
72
73
/**
74
 * Clase de utilidad
75
 *
76
 * @version $Revision$
77
 */
78
public class Utilities {
79 3706 jaume
        /**
80
     * <b>key</b>: URL, <b>value</b>: path to the downloaded file.
81
     */
82
    private static Hashtable downloadedFiles;
83 598 fernando
    /** DOCUMENT ME! */
84
    private static Logger logger = Logger.getLogger(Utilities.class.getName());
85 3706 jaume
        private static final String tempDirectoryPath = System.getProperty("java.io.tmpdir")+"/tmp-andami";
86
87 598 fernando
88
    /**
89
     * Crea un icono a partir del path de una imagen
90
     *
91
     * @param path Path de la imagen dentro del jar de la aplicaci?n
92
     *
93
     * @return ImageIcon si encuentra la imagen y null si no la encuentra
94
     */
95
    public static ImageIcon createImageIcon(String path) {
96
        URL imgURL = null;
97
98
        try {
99
            imgURL = new URL("file:" + path);
100
        } catch (MalformedURLException e) {
101
            e.printStackTrace();
102
        }
103
104
        if (imgURL != null) {
105
            return new ImageIcon(imgURL);
106
        } else {
107
            return null;
108
        }
109
    }
110
111
    /**
112
     * M?todo que libera la memoria de los jInternalFrame
113
     *
114
     * @param baseComponent JInternalFrame cuya memoria se quiere eliminar
115
     */
116
    public static void cleanComponent(Component baseComponent) {
117
        try {
118
            cleanComponent(baseComponent, 0);
119
        } catch (Exception ignore) { // give some exception handling...
120
        }
121
    }
122
123
    /*    * 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.    */
124
    protected static void cleanComponent(Component baseComponent, int depth) {
125
        if (baseComponent == null) // recursion terminating clause
126
         {
127
            return;
128
        }
129 901 fernando
130 6877 cesar
        if (baseComponent instanceof IWindow){
131 901 fernando
                return;
132
        }
133 598 fernando
134
        Container cont;
135
        Component[] childComponents;
136
        int numChildren; // clean up component containers
137
138
        if (baseComponent instanceof Container) { // now clean up container instance variables
139
140
            if (baseComponent instanceof RootPaneContainer) { // Swing specialised container
141
                cont = (Container) baseComponent;
142
                numChildren = cont.getComponentCount();
143
                childComponents = cont.getComponents();
144
145
                for (int i = 0; i < numChildren; i++) { // remove each component from the current container
146
147
                    // each child component may be a container itself
148
                    cleanComponent(childComponents[i], depth + 1);
149
                    ((RootPaneContainer) cont).getContentPane().remove(childComponents[i]);
150
                }
151
152
                ((RootPaneContainer) cont).getContentPane().setLayout(null);
153
            } else { // General Swing, and AWT, Containers
154
                cont = (Container) baseComponent;
155
                numChildren = cont.getComponentCount();
156
                childComponents = cont.getComponents();
157
158
                for (int i = 0; i < numChildren; i++) //for(int i = 0;i < numChildren;i++)
159
                 {
160
                    // remove each component from the current container                    // each child component may be a container itself
161
                    cleanComponent(childComponents[i], depth + 1);
162
                    cont.remove(childComponents[i]);
163
                }
164
165
                cont.setLayout(null);
166
            }
167
        }
168
169
        // if component is also a container
170
    }
171
172
    /**
173
     * Extrae un fichero zip en un directorio
174
     *
175
     * @param file fichero comprimido
176
     * @param dir Directorio donde se extraera el fichero
177
     *
178
     * @throws ZipException Si hay un error con el formato del fichero
179
     * @throws IOException Si se produce un error de entrada salida gen?rico
180
     */
181
    public static void extractTo(File file, File dir, SplashWindow splash)
182
        throws ZipException, IOException {
183
        ZipFile zip = new ZipFile(file);
184
        Enumeration e = zip.entries();
185
186
        while (e.hasMoreElements()) {
187
            ZipEntry entry = (ZipEntry) e.nextElement();
188
            System.out.println("Procesando " + entry.getName() + "...");
189
            splash.process(30, "Procesando " + entry.getName() + "...");
190
            if (entry.isDirectory()) {
191
                new File(dir.getAbsolutePath() + File.separator +
192
                    entry.getName()).mkdir();
193
            } else {
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);
199
200
                int i;
201
202
                while ((i = bin.read()) != -1) {
203
                    bout.write(i);
204
                }
205
206
                bout.flush();
207
                bout.close();
208
                bin.close();
209
            }
210
        }
211
    }
212 3706 jaume
213
    /**
214
     * Returns the content of this URL as a file from the file system.<br>
215
     * <p>
216
     * If the URL has been already downloaded in this session and notified
217
     * to the system using the static <b>Utilities.addDownloadedURL(URL)</b>
218
     * method, it can be restored faster from the file system avoiding to
219
     * download it again.
220
     * </p>
221
     * @param url
222
     * @return File containing this URL's content or null if no file was found.
223
     */
224
    private static File getPreviousDownloadedURL(URL url){
225
        File f = null;
226
        if (downloadedFiles!=null && downloadedFiles.containsKey(url)){
227
            String filePath = (String) downloadedFiles.get(url);
228
            f = new File(filePath);
229
        }
230
        return f;
231
    }
232
233
    /**
234
     * Adds an URL to the table of downloaded files for further uses. If the URL
235
     * already exists in the table its filePath value is updated to the new one and
236
     * the old file itself is removed from the file system.
237
     *
238
     * @param url
239
     * @param filePath
240
     */
241
    private static void addDownloadedURL(URL url, String filePath){
242
        if (downloadedFiles==null)
243
            downloadedFiles = new Hashtable();
244
        String fileName = (String) downloadedFiles.put(url, filePath);
245 5276 jmvivo
        //JMV: No se puede eliminar el anterior porque puede que alguien lo
246
        // este usando
247
        /*
248 3706 jaume
        if (fileName!=null){
249
            File f = new File(fileName);
250
            if (f.exists())
251
                f.delete();
252
        }
253 5276 jmvivo
        */
254 3706 jaume
    }
255
256
    /**
257
     * Downloads an URL into a temporary file that is removed the next time the
258
     * tempFileManager class is called, which means the next time gvSIG is launched.
259
     *
260
     * @param url
261
     * @param name
262
     * @return
263
     * @throws IOException
264
     * @throws ServerErrorResponseException
265
     * @throws ConnectException
266
     * @throws UnknownHostException
267
     */
268
    public static File downloadFile(URL url, String name) throws IOException,ConnectException, UnknownHostException{
269
            File f = null;
270
271
            try{
272
                if ((f=getPreviousDownloadedURL(url))==null){
273
                        File tempDirectory = new File(tempDirectoryPath);
274
                        if (!tempDirectory.exists())
275
                                tempDirectory.mkdir();
276
277
                        f = new File(tempDirectoryPath+"/"+name+System.currentTimeMillis());
278
279
                    System.out.println("downloading '"+url.toString()+"' to: "+f.getAbsolutePath());
280
281
                    f.deleteOnExit();
282
                DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)));
283
                byte[] buffer = new byte[1024*256];
284
                InputStream is = url.openStream();
285
                long readed = 0;
286
                for (int i = is.read(buffer); i>0; i = is.read(buffer)){
287
                    dos.write(buffer, 0, i);
288
                    readed += i;
289
                }
290
                dos.close();
291
                addDownloadedURL(url, f.getAbsolutePath());
292
                }
293
            } catch (IOException io) {
294
                    io.printStackTrace();
295
            }
296
297
            return f;
298
        }
299
300
    /**
301
     * Cleans every temporal file previously downloaded.
302
     */
303
    public static void cleanUpTempFiles() {
304
            try{
305
                    File tempDirectory = new File(tempDirectoryPath);
306
307
                    File[] files = tempDirectory.listFiles();
308
                    if (files!=null) {
309
                            for (int i = 0; i < files.length; i++) {
310
                                     // s?lo por si en un futuro se necesitan crear directorios temporales
311
                                    if (files[i].isDirectory())        deleteDirectory(files[i]);
312
                                    files[i].delete();
313
                            }
314
                    }
315
                    tempDirectory.delete();
316
            } catch (Exception e) {        }
317
318
    }
319
    /**
320
     * Recursive directory delete.
321
     * @param f
322
     */
323
        private static void deleteDirectory(File f) {
324
                File[] files = f.listFiles();
325
                for (int i = 0; i < files.length; i++) {
326
                        if (files[i].isDirectory()) deleteDirectory(files[i]);
327
                        files[i].delete();
328
                }
329
330
        }
331 4099 fjp
332
    /**
333
     * Crea un fichero temporal con un nombre concreto y unos datos pasados por
334
     * par?metro.
335
     * @param fileName Nombre de fichero
336
     * @param data datos a guardar en el fichero
337
     */
338
    public static void createTemp(String fileName, String data)throws IOException{
339
            File f = new File(fileName);
340
            DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)) );
341
                dos.writeBytes(data);
342
                dos.close();
343
            f.deleteOnExit();
344
    }
345
346
    /**
347
     * Remove an URL from the system cache. The file will remain in the file
348
     * system for further eventual uses.
349
     * @param request
350
     */
351
        public static void removeURL(URL url) {
352 4428 jaume
                if (downloadedFiles != null && downloadedFiles.containsKey(url))
353 4424 jaume
                        downloadedFiles.remove(url);
354 4099 fjp
        }
355 598 fernando
}