Statistics
| Revision:

svn-gvsig-desktop / tags / Root_v06 / frameworks / _fwAndami / src / com / iver / andami / Utilities.java @ 4811

History | View | Annotate | Download (12.1 KB)

1
/* 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
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
import java.io.BufferedReader;
48
import java.io.DataOutputStream;
49
import java.io.File;
50
import java.io.FileOutputStream;
51
import java.io.IOException;
52
import java.io.InputStream;
53
import java.io.InputStreamReader;
54
import java.io.OutputStream;
55
import java.net.ConnectException;
56
import java.net.HttpURLConnection;
57
import java.net.MalformedURLException;
58
import java.net.URL;
59
import java.net.URLConnection;
60
import java.net.UnknownHostException;
61
import java.util.Enumeration;
62
import java.util.Hashtable;
63
import java.util.zip.ZipEntry;
64
import java.util.zip.ZipException;
65
import java.util.zip.ZipFile;
66

    
67
import javax.swing.ImageIcon;
68
import javax.swing.RootPaneContainer;
69

    
70
import org.apache.log4j.Logger;
71

    
72
import com.iver.andami.ui.SplashWindow;
73
import com.iver.andami.ui.mdiManager.View;
74

    
75

    
76

    
77
/**
78
 * Clase de utilidad
79
 *
80
 * @version $Revision: 4811 $
81
 */
82
public class Utilities {
83
        /**
84
     * <b>key</b>: URL, <b>value</b>: path to the downloaded file.
85
     */
86
    private static Hashtable downloadedFiles = new Hashtable();
87
    private static Hashtable contentTypes;
88
    private static final String tempDirectoryPath = System.getProperty("java.io.tmpdir")+"/tmp-andami";
89
    
90
    /** DOCUMENT ME! */
91
    private static Logger logger = Logger.getLogger(Utilities.class.getName());
92

    
93
    /**
94
     * Crea un icono a partir del path de una imagen
95
     *
96
     * @param path Path de la imagen dentro del jar de la aplicaci?n
97
     *
98
     * @return ImageIcon si encuentra la imagen y null si no la encuentra
99
     */
100
    public static ImageIcon createImageIcon(String path) {
101
        URL imgURL = null;
102

    
103
        try {
104
            imgURL = new URL("file:" + path);
105
        } catch (MalformedURLException e) {
106
            e.printStackTrace();
107
        }
108

    
109
        if (imgURL != null) {
110
            return new ImageIcon(imgURL);
111
        } else {
112
            return null;
113
        }
114
    }
115

    
116
    /**
117
     * M?todo que libera la memoria de los jInternalFrame
118
     *
119
     * @param baseComponent JInternalFrame cuya memoria se quiere eliminar
120
     */
121
    public static void cleanComponent(Component baseComponent) {
122
        try {
123
            cleanComponent(baseComponent, 0);
124
        } catch (Exception ignore) { // give some exception handling... 
125
        }
126
    }
127

    
128
    /*    * 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.    */
129
    protected static void cleanComponent(Component baseComponent, int depth) {
130
        if (baseComponent == null) // recursion terminating clause     
131
         {
132
            return;
133
        }
134
        
135
        if (baseComponent instanceof View){
136
                return;
137
        }
138

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

    
143
        if (baseComponent instanceof Container) { // now clean up container instance variables 
144

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

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

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

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

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

    
170
                cont.setLayout(null);
171
            }
172
        }
173

    
174
        // if component is also a container  
175
    }
176

    
177
    /**
178
     * Extrae un fichero zip en un directorio
179
     *
180
     * @param file fichero comprimido
181
     * @param dir Directorio donde se extraera el fichero
182
     *
183
     * @throws ZipException Si hay un error con el formato del fichero
184
     * @throws IOException Si se produce un error de entrada salida gen?rico
185
     */
186
    public static void extractTo(File file, File dir, SplashWindow splash)
187
        throws ZipException, IOException {
188
        ZipFile zip = new ZipFile(file);
189
        Enumeration e = zip.entries();
190

    
191
        while (e.hasMoreElements()) {
192
            ZipEntry entry = (ZipEntry) e.nextElement();
193
            System.out.println("Procesando " + entry.getName() + "...");
194
            splash.process(30, "Procesando " + entry.getName() + "...");
195
            if (entry.isDirectory()) {
196
                new File(dir.getAbsolutePath() + File.separator +
197
                    entry.getName()).mkdir();
198
            } else {
199
                InputStream in = zip.getInputStream(entry);
200
                OutputStream out = new FileOutputStream(dir + File.separator +
201
                        entry.getName());
202
                BufferedInputStream bin = new BufferedInputStream(in);
203
                BufferedOutputStream bout = new BufferedOutputStream(out);
204

    
205
                int i;
206

    
207
                while ((i = bin.read()) != -1) {
208
                    bout.write(i);
209
                }
210

    
211
                bout.flush();
212
                bout.close();
213
                bin.close();
214
            }
215
        }
216
    }
217
    
218
    /**
219
     * Adds an URL to the table of downloaded files for further uses. If the URL
220
     * already exists in the table its filePath value is updated to the new one and
221
     * the old file itself is removed from the file system.
222
     * 
223
     * @param url
224
     * @param filePath
225
     */
226
    private static void addDownloadedURL(URL url, String filePath){
227
        String fileName = (String) downloadedFiles.put(url, filePath);
228
        if (fileName!=null){
229
            File f = new File(fileName);
230
            if (f.exists())
231
                f.delete();
232
        }
233
    }
234
       
235
    /**
236
     * Downloads an URL into a temporary file that is removed the next time the 
237
     * tempFileManager class is called, which means the next time gvSIG is launched.
238
     * 
239
     * @param url
240
     * @param name
241
     * @return
242
     * @throws IOException
243
     * @throws ServerErrorResponseException
244
     * @throws ConnectException
245
     * @throws UnknownHostException
246
     */
247
    public static File downloadFile(URL url, String name) throws IOException, ConnectException, UnknownHostException{
248
            File f = null;
249
            long t1 = System.currentTimeMillis();
250
            if ((f=getPreviousDownloadedURL(url))==null){
251
                    
252
                    File tempDirectory = new File(tempDirectoryPath);
253
                    if (!tempDirectory.exists())
254
                            tempDirectory.mkdir();
255
                    
256
                    f = new File(tempDirectoryPath+"/"+name+System.currentTimeMillis());
257
                    
258
                    System.out.println("downloading '"+url.toString()+"' to: "+f.getAbsolutePath());
259
                    
260
                    f.deleteOnExit();
261
                    DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)));
262
                    byte[] buffer = new byte[1024*256];
263
                    URLConnection connection = url.openConnection();
264
                    InputStream is = null;
265
                    try {
266
                            is = connection.getInputStream();
267
                    } catch (IOException e) {
268
                            // Ops! The server gave us an error. I'm piping the error
269
                            // channel to the input channel to lay it out to the user.
270
                            
271
                            if (!(connection instanceof HttpURLConnection)) throw e;
272
                            InputStream err = ((HttpURLConnection) connection).getErrorStream();
273
                            
274
                            if (err == null) throw e;
275
                            is = err;
276
                    }
277
                    long readed = 0;
278
                    for (int i = is.read(buffer); i>0; i = is.read(buffer)){
279
                            dos.write(buffer, 0, i);
280
                            readed += i;
281
                    }
282
                    dos.close();
283
                    addDownloadedURL(url, f.getAbsolutePath());
284
            }
285
            
286
            // Avoid possible conflits caused by multiple application instances.
287
            if (!f.exists()) {
288
                    downloadedFiles.remove(url);
289
                    f = downloadFile(url, name);
290
            }
291
            long t2 = System.currentTimeMillis();
292
            System.err.println("Total download method time: "+(t2-t1));
293
            return f;
294
        }
295

    
296
    /**
297
     * Crea un fichero temporal con un nombre concreto y unos datos pasados por
298
     * par?metro.
299
     * @param fileName Nombre de fichero
300
     * @param data datos a guardar en el fichero
301
     */
302
    public static void createTemp(String fileName, String data)throws IOException{
303
            File f = new File(fileName);
304
            DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)) );
305
                dos.writeBytes(data);
306
                dos.close();
307
            f.deleteOnExit();
308
    }
309
    
310
    /**
311
     * Cleans every temporal file previously downloaded.
312
     */
313
    public static void cleanUpTempFiles() {
314
            try{
315
                    File tempDirectory = new File(tempDirectoryPath);
316
                    
317
                    File[] files = tempDirectory.listFiles();
318
                    if (files!=null) {
319
                            for (int i = 0; i < files.length; i++) {
320
                                     // s?lo por si en un futuro se necesitan crear directorios temporales
321
                                    if (files[i].isDirectory())        deleteDirectory(files[i]);
322
                                    files[i].delete();
323
                            }
324
                    }
325
                    tempDirectory.delete();
326
            } catch (Exception e) {        }
327
            
328
    }
329
    
330
    /**
331
     * Recursive directory delete.
332
     * @param f
333
     */
334
        private static void deleteDirectory(File f) {
335
                File[] files = f.listFiles();
336
                for (int i = 0; i < files.length; i++) {
337
                        if (files[i].isDirectory()) deleteDirectory(files[i]);
338
                        files[i].delete();
339
                }
340
                
341
        }
342
        
343
        /**
344
     * Returns the content of this URL as a file from the file system.<br>
345
     * <p>
346
     * If the URL has been already downloaded in this session and notified 
347
     * to the system using the static <b>Utilities.addDownloadedURL(URL)</b>
348
     * method, it can be restored faster from the file system avoiding to
349
     * download it again.
350
     * </p>
351
     * @param url
352
     * @return File containing this URL's content or null if no file was found.
353
     */
354
    private static File getPreviousDownloadedURL(URL url){
355
        File f = null;
356
        if (downloadedFiles!=null && downloadedFiles.containsKey(url)){
357
            String filePath = (String) downloadedFiles.get(url);
358
            f = new File(filePath);
359
        }
360
        return f;
361
    }
362

    
363
    /**
364
     * Remove an URL from the system cache. The file will remain in the file
365
     * system for further eventual uses.
366
     * @param request
367
     */
368
        public static void removeURL(URL url) {
369
                if (downloadedFiles != null && downloadedFiles.containsKey(url))
370
                        downloadedFiles.remove(url);
371
        }
372
}