Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.lib / org.gvsig.raster.lib.impl / src / main / java / org / gvsig / raster / util / DefaultFileUtils.java @ 595

History | View | Annotate | Download (13.2 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 */
22
package org.gvsig.raster.util;
23

    
24
import java.awt.geom.AffineTransform;
25
import java.io.BufferedOutputStream;
26
import java.io.BufferedReader;
27
import java.io.DataOutputStream;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileNotFoundException;
31
import java.io.FileOutputStream;
32
import java.io.FileReader;
33
import java.io.IOException;
34
import java.io.InputStream;
35
import java.io.OutputStream;
36
import java.text.NumberFormat;
37
import java.util.ArrayList;
38

    
39
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
40
import org.gvsig.fmap.dal.coverage.util.FileUtils;
41
import org.gvsig.fmap.dal.coverage.util.PropertyEvent;
42
import org.gvsig.fmap.dal.coverage.util.PropertyListener;
43

    
44

    
45
/**
46
 * Utilities for files, directories and file names 
47
 *
48
 * @author Nacho Brodin (nachobrodin@gmail.com)
49
 */
50
public class DefaultFileUtils implements FileUtils {
51
        /**
52
         * Copia de ficheros
53
         * @param pathOrig Ruta de origen
54
         * @param pathDst Ruta de destino.
55
         */
56
        public void copyFile(String pathOrig, String pathDst) throws FileNotFoundException, IOException {
57
                InputStream in;
58
                OutputStream out;
59

    
60
                if (pathOrig == null || pathDst == null) {
61
                        System.err.println("Error en path");
62
                        return;
63
                }
64

    
65
                File orig = new File(pathOrig);
66
                if (!orig.exists() || !orig.isFile() || !orig.canRead()) {
67
                        System.err.println("Error copying the file:" + pathOrig + " <Source Exists:" + orig.exists() + " Source is file:" + orig.isFile() + " Source can be read:" + orig.canRead());
68
                        return;
69
                }
70

    
71
                File dest = new File(pathDst);
72
                String file = new File(pathOrig).getName();
73
                if (dest.isDirectory())
74
                        pathDst += file;
75

    
76
                in = new FileInputStream(pathOrig);
77
                out = new FileOutputStream(pathDst);
78

    
79
                byte[] buf = new byte[1024];
80
                int len;
81

    
82
                while ((len = in.read(buf)) > 0)
83
                        out.write(buf, 0, len);
84

    
85
                in.close();
86
                out.close();
87
        }
88

    
89
        /**
90
         * Crea un fichero de georeferenciaci?n (world file) para un dataset
91
         * determinado
92
         * @param fileName Nombre completo del fichero de raster
93
         * @param Extent
94
         * @param pxWidth Ancho en p?xeles
95
         * @param pxHeight Alto en p?xeles
96
         * @return
97
         * @throws IOException
98
         */
99
        public void createWorldFile(String fileName, Extent ext, int pxWidth, int pxHeight) throws IOException {
100
                File tfw = null;
101

    
102
                String extWorldFile = ".wld";
103
                if (fileName.endsWith("tif"))
104
                        extWorldFile = ".tfw";
105
                if (fileName.endsWith("jpg") || fileName.endsWith("jpeg"))
106
                        extWorldFile = ".jpgw";
107

    
108
                tfw = new File(fileName.substring(0, fileName.lastIndexOf(".")) + extWorldFile);
109

    
110
                // Generamos un world file para gdal
111
                DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tfw)));
112
                dos.writeBytes((ext.getMax().getX() - ext.getMin().getX()) / (pxWidth - 1) + "\n");
113
                dos.writeBytes("0.0\n");
114
                dos.writeBytes("0.0\n");
115
                dos.writeBytes((ext.getMin().getY() - ext.getMax().getY()) / (pxHeight - 1) + "\n");
116
                dos.writeBytes("" + ext.getMin().getX() + "\n");
117
                dos.writeBytes("" + ext.getMax().getY() + "\n");
118
                dos.close();
119
        }
120

    
121
        /**
122
         * Crea un fichero de georeferenciaci?n (world file) para un dataset
123
         * determinado
124
         * @param fileName Nombre completo del fichero de raster
125
         * @param AffineTransform
126
         * @param pxWidth Ancho en p?xeles
127
         * @param pxHeight Alto en p?xeles
128
         * @return
129
         * @throws IOException
130
         */
131
        public void createWorldFile(String fileName, AffineTransform at, int pxWidth, int pxHeight) throws IOException {
132
                File tfw = null;
133

    
134
                String extWorldFile = ".wld";
135
                if (fileName.endsWith("tif"))
136
                        extWorldFile = ".tfw";
137
                if (fileName.endsWith("jpg") || fileName.endsWith("jpeg"))
138
                        extWorldFile = ".jpgw";
139

    
140
                tfw = new File(fileName.substring(0, fileName.lastIndexOf(".")) + extWorldFile);
141

    
142
                // Generamos un world file para gdal
143
                DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tfw)));
144
                dos.writeBytes(at.getScaleX() + "\n");
145
                dos.writeBytes(at.getShearX() + "\n");
146
                dos.writeBytes(at.getShearY() + "\n");
147
                dos.writeBytes(at.getScaleY() + "\n");
148
                dos.writeBytes("" + at.getTranslateX() + "\n");
149
                dos.writeBytes("" + at.getTranslateY() + "\n");
150
                dos.close();
151
        }
152

    
153
        /**
154
         * Formatea en forma de cadena un tama?o dado en bytes. El resultado ser? una
155
         * cadena con GB, MB, KB y B
156
         * @param size tama?o a formatear
157
         * @return cadena con la cantidad formateada
158
         */
159
        public String formatFileSize(long size) {
160
                double bytes = size;
161
                double kBytes = 0.0;
162
                double mBytes = 0.0;
163
                double gBytes = 0.0;
164
                if (bytes >= 1024.0) {
165
                        kBytes = bytes / 1024.0;
166
                        if (kBytes >= 1024.0) {
167
                                mBytes = kBytes / 1024.0;
168
                                if (mBytes >= 1024.0)
169
                                        gBytes = mBytes / 1024.0;
170
                        }
171
                }
172

    
173
                String texto = "";
174
                NumberFormat numberFormat = NumberFormat.getNumberInstance();
175
                numberFormat.setMinimumFractionDigits(0);
176

    
177
                do {
178
                        if (gBytes > 0) {
179
                                numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(gBytes));
180
                                texto = numberFormat.format(gBytes) + " GB";
181
                                break;
182
                        }
183
                        if (mBytes > 0) {
184
                                numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(mBytes));
185
                                texto = numberFormat.format(mBytes) + " MB";
186
                                break;
187
                        }
188
                        if (kBytes > 0) {
189
                                numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(kBytes));
190
                                texto = numberFormat.format(kBytes) + " KB";
191
                                break;
192
                        }
193
                        if (bytes != 0) {
194
                                numberFormat.setMaximumFractionDigits(0);
195
                                texto = numberFormat.format(bytes) + " bytes";
196
                                break;
197
                        }
198
                } while (false);
199

    
200
                numberFormat.setMaximumFractionDigits(0);
201

    
202
                return texto + " (" + numberFormat.format(bytes) + " bytes)";
203
        }
204

    
205
        /**
206
         * Obtiene la extensi?n del fichero a partir de su nombre.
207
         * @param file Nombre o ruta del fichero
208
         * @return Cadena con la extensi?n que representa el tipo de fichero. Devuelve
209
         *         null si no tiene extension.
210
         */
211
        public String getExtensionFromFileName(String file) {
212
                return file.substring(file.lastIndexOf(".") + 1).toLowerCase();
213
        }
214

    
215
        /**
216
         * Obtiene el nombre de fichero sin la extensi?n.
217
         * @param file Nombre o ruta del fichero
218
         * @return Cadena con la extensi?n que representa el tipo de fichero. Si no
219
         *         tiene extensi?n devuelve el mismo fichero de entrada
220
         */
221
        public String getNameWithoutExtension(String file) {
222
                if (file == null)
223
                        return null;
224

    
225
                int n = file.lastIndexOf(".");
226
                if (n != -1)
227
                        return file.substring(0, n);
228
                return file;
229
        }
230

    
231
        /**
232
         * Obtiene el nombre de fichero sin la extensi?n ni la ruta.
233
         * @param file Ruta del fichero
234
         * @return Cadena que representa el nombre del fichero sin extensi?n ni path de directorios
235
         */
236
        public String getFileNameFromCanonical(String file) {
237
                if (file == null)
238
                        return null;
239

    
240
                int n = file.lastIndexOf(".");
241
                if (n != -1)
242
                        file = file.substring(0, n);
243

    
244
                n = file.lastIndexOf(File.separator);
245
                if(n != -1)
246
                        file = file.substring(n + 1, file.length());
247

    
248
                return file;
249
        }
250

    
251
        /**
252
         * Obtiene el ?ltimo trozo de la cadena a partir de los caracteres que
253
         * coincidan con el patr?n. En caso de que el patr?n no exista en la cadena
254
         * devuelve esta completa
255
         * @param string
256
         * @param pattern
257
         * @return
258
         */
259
        public String getLastPart(String string, String pattern) {
260
                int n = string.lastIndexOf(pattern);
261
                if (n > 0)
262
                        return string.substring(n + 1, string.length());
263
                return string;
264
        }
265

    
266
        /**
267
         * Obtiene la codificaci?n de un fichero XML
268
         * @param file Nombre del fichero XML
269
         * @return Codificaci?n
270
         */
271
        public String readFileEncoding(String file) {
272
                FileReader fr;
273
                String encoding = null;
274
                try {
275
                        fr = new FileReader(file);
276
                        BufferedReader br = new BufferedReader(fr);
277
                        char[] buffer = new char[100];
278
                        br.read(buffer);
279
                        StringBuffer st = new StringBuffer(new String(buffer));
280
                        String searchText = "encoding=\"";
281
                        int index = st.indexOf(searchText);
282
                        if (index > -1) {
283
                                st.delete(0, index + searchText.length());
284
                                encoding = st.substring(0, st.indexOf("\""));
285
                        }
286
                        fr.close();
287
                } catch (FileNotFoundException ex) {
288
                        ex.printStackTrace();
289
                } catch (IOException e) {
290
                        e.printStackTrace();
291
                }
292
                return encoding;
293
        }
294

    
295
        /**
296
         * Obtiene el nombre del fichero RMF a partir del nombre del fichero. Si el
297
         * nombre del fichero tiene una extensi?n esta llamada sustituir? la extensi?n
298
         * existente por .rmf. Si el fichero pasado no tiene extensi?n esta llamada
299
         * a?adir? .rm al final.
300
         * @param fileName Nombre del fichero raster de origen
301
         * @return Nombre del fichero rmf asociado al raster.
302
         */
303
        public String getRMFNameFromFileName(String fileName) {
304
                return getNameWithoutExtension(fileName) + ".rmf";
305
        }
306
        
307
        /**
308
         * Recursive directory delete.
309
         * @param f
310
         */
311
        private void deleteDirectory(File f) {
312
                File[] files = f.listFiles();
313
                for (int i = 0; i < files.length; i++) {
314
                        if (files[i].isDirectory())
315
                                deleteDirectory(files[i]);
316
                        files[i].delete();
317
                }
318
        }
319
        
320
        //******* Servicio de directorios temporales **************
321
        
322
        /**
323
         * Directorio temporal para la cach?. Si gastamos el mismo que andami este se ocupar? de gestionar su
324
         * destrucci?n al cerrar gvSIG.
325
         */
326
        private String tempCacheDirectoryPath = System.getProperty("java.io.tmpdir")
327
                        + File.separator + "tmp-andami";
328
        
329
        /**
330
         * Elimina los ficheros del directorio temporal. Realizamos esta acci?n al
331
         * levantar la librer?a.
332
         */
333
        public void cleanUpTempFiles() {
334
                try {
335
                        File tempDirectory = new File(tempCacheDirectoryPath);
336

    
337
                        File[] files = tempDirectory.listFiles();
338
                        if (files != null)
339
                                for (int i = 0; i < files.length; i++) {
340
                                        // s?lo por si en un futuro se necesitan crear directorios temporales
341
                                        if (files[i].isDirectory())
342
                                                deleteDirectory(files[i]);
343
                                        files[i].delete();
344
                                }
345
                        tempDirectory.delete();
346
                } catch (Exception e) {
347
                }
348
        }
349

    
350
        /**
351
         * Esta funci?n crea el directorio para temporales y devuelve el manejador
352
         * del directorio
353
         * @return
354
         */
355
        public File getTemporalFile() {
356
                File tempDirectory = new File(tempCacheDirectoryPath);
357
                if (!tempDirectory.exists())
358
                        tempDirectory.mkdir();
359
                return tempDirectory;
360
        }
361
        
362
        /**
363
         * Esta funci?n crea el directorio para temporales y devuelve la ruta de este
364
         * @return
365
         */
366
        public String getTemporalPath() {
367
                return getTemporalFile().getAbsolutePath();
368
        }
369

    
370
        
371
        //******* Servicio de nombres de capas ?nicos **************
372
        /**
373
         * Contador global de las capas generadas para raster. Hay que contar con que esta
374
         * clase es un singleton desde el manager. Si hay varias instanciaciones layerCount 
375
         * dar? valores erroneos. 
376
         */
377
        private int                   layerCount = 1;
378
        private ArrayList<PropertyListener>     
379
                                                                        propetiesListeners = new ArrayList<PropertyListener>();
380

    
381
        /**
382
         * La gesti?n de nombres ?nicos en la generaci?n de capas se lleva de forma
383
         * autom?tica. Cuando alguien crea una capa nueva, si esta no tiene nombre especifico,
384
         * obtiene su nombre mediante este m?todo. La siguiente vez que se llame dar? un nombre
385
         * distinto. El nombre de la capa ser? NewLayer_ seguido de un contador de actualizaci?n
386
         * autom?tica cada vez que se usa.
387
         * @return Nombre ?nico para la capa.
388
         */
389
        public String usesOnlyLayerName() {
390
                String oldValue = getOnlyLayerName();
391
                String newValue = "NewLayer_" + (++layerCount);
392
                for (int i = 0; i < propetiesListeners.size(); i++)
393
                        if(propetiesListeners.get(i) instanceof PropertyListener)
394
                                ((PropertyListener)propetiesListeners.get(i)).actionValueChanged(new PropertyEvent(oldValue, "NewLayer", newValue, oldValue));
395
                return newValue;
396
        }
397

    
398
        /**
399
         * Obtiene el nombre ?nico de la siguiente capa sin actualizar el contador. Es
400
         * solo para consulta. La siguiente vez que se llama a getOnlyLayerName o usesOnlyLayerName
401
         * devolver? el mismo nomnbre.
402
         * @return Nombre ?nico para la capa.
403
         */
404
        public String getOnlyLayerName() {
405
                return "NewLayer_" + layerCount;
406
        }
407

    
408
        /**
409
         * A?adir un listener a la lista de eventos
410
         * @param listener
411
         */
412
        public void addOnlyLayerNameListener(PropertyListener listener) {
413
                if (!propetiesListeners.contains(listener))
414
                        propetiesListeners.add(listener);
415
        }
416

    
417
        /**
418
         * Elimina un listener de la lista de eventos
419
         * @param listener
420
         */
421
        public void removeOnlyLayerNameListener(PropertyListener listener) {
422
                for (int i = 0; i < propetiesListeners.size(); i++)
423
                        if(propetiesListeners.get(i) == listener)
424
                                propetiesListeners.remove(i);
425
        }
426

    
427
        //******* End: Servicio de nombres de capas ?nicos **************
428
}