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 @ 4436

History | View | Annotate | Download (11.8 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.net.URI;
37
import java.security.MessageDigest;
38
import java.security.NoSuchAlgorithmException;
39
import java.text.NumberFormat;
40
import java.util.ArrayList;
41

    
42
import org.apache.commons.lang3.StringUtils;
43

    
44
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
45
import org.gvsig.fmap.dal.coverage.util.FileUtils;
46
import org.gvsig.fmap.dal.coverage.util.PropertyEvent;
47
import org.gvsig.fmap.dal.coverage.util.PropertyListener;
48

    
49

    
50
/**
51
 * Utilities for files, directories and file names
52
 *
53
 * @author Nacho Brodin (nachobrodin@gmail.com)
54
 */
55
public class DefaultFileUtils implements FileUtils {
56

    
57
        public void copyFile(String pathOrig, String pathDst) throws FileNotFoundException, IOException {
58
                InputStream in;
59
                OutputStream out;
60

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

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

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

    
77
                dest = new File(pathDst);
78
                if(!dest.exists())
79
                        dest.createNewFile();
80

    
81
                in = new FileInputStream(pathOrig);
82
                out = new FileOutputStream(pathDst);
83

    
84
                byte[] buf = new byte[1024];
85
                int len;
86

    
87
                while ((len = in.read(buf)) > 0)
88
                        out.write(buf, 0, len);
89

    
90
                in.close();
91
                out.close();
92
        }
93

    
94
        public void createWorldFile(String fileName, Extent ext, int pxWidth, int pxHeight) throws IOException {
95
                File tfw = null;
96

    
97
                String extWorldFile = ".wld";
98
                if (fileName.endsWith("tif"))
99
                        extWorldFile = ".tfw";
100
                if (fileName.endsWith("jpg") || fileName.endsWith("jpeg"))
101
                        extWorldFile = ".jpgw";
102

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

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

    
116
        public void createWorldFile(String fileName, AffineTransform at, int pxWidth, int pxHeight) throws IOException {
117
                File tfw = null;
118

    
119
                String extWorldFile = ".wld";
120
                if (fileName.endsWith("tif"))
121
                        extWorldFile = ".tfw";
122
                if (fileName.endsWith("jpg") || fileName.endsWith("jpeg"))
123
                        extWorldFile = ".jpgw";
124

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

    
127
                // Generamos un world file para gdal
128
                DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tfw)));
129
                dos.writeBytes(at.getScaleX() + "\n");
130
                dos.writeBytes(at.getShearX() + "\n");
131
                dos.writeBytes(at.getShearY() + "\n");
132
                dos.writeBytes(at.getScaleY() + "\n");
133
                dos.writeBytes("" + at.getTranslateX() + "\n");
134
                dos.writeBytes("" + at.getTranslateY() + "\n");
135
                dos.close();
136
        }
137

    
138
        public String formatFileSize(long size) {
139
                double bytes = size;
140
                double kBytes = 0.0;
141
                double mBytes = 0.0;
142
                double gBytes = 0.0;
143
                if (bytes >= 1024.0) {
144
                        kBytes = bytes / 1024.0;
145
                        if (kBytes >= 1024.0) {
146
                                mBytes = kBytes / 1024.0;
147
                                if (mBytes >= 1024.0)
148
                                        gBytes = mBytes / 1024.0;
149
                        }
150
                }
151

    
152
                String texto = "";
153
                NumberFormat numberFormat = NumberFormat.getNumberInstance();
154
                numberFormat.setMinimumFractionDigits(0);
155

    
156
                do {
157
                        if (gBytes > 0) {
158
                                numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(gBytes));
159
                                texto = numberFormat.format(gBytes) + " GB";
160
                                break;
161
                        }
162
                        if (mBytes > 0) {
163
                                numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(mBytes));
164
                                texto = numberFormat.format(mBytes) + " MB";
165
                                break;
166
                        }
167
                        if (kBytes > 0) {
168
                                numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(kBytes));
169
                                texto = numberFormat.format(kBytes) + " KB";
170
                                break;
171
                        }
172
                        if (bytes != 0) {
173
                                numberFormat.setMaximumFractionDigits(0);
174
                                texto = numberFormat.format(bytes) + " bytes";
175
                                break;
176
                        }
177
                } while (false);
178

    
179
                numberFormat.setMaximumFractionDigits(0);
180

    
181
                return texto + " (" + numberFormat.format(bytes) + " bytes)";
182
        }
183

    
184
        public String getExtensionFromFileName(String file) {
185
                return file.substring(file.lastIndexOf(".") + 1).toLowerCase();
186
        }
187

    
188
        public String getNameWithoutExtension(String file) {
189
                if (file == null)
190
                        return null;
191

    
192
                int n = file.lastIndexOf(".");
193
                if (n != -1)
194
                        return file.substring(0, n);
195
                return file;
196
        }
197

    
198
        public String getFileNameFromCanonical(String file) {
199
                if (file == null)
200
                        return null;
201

    
202
                int n = file.lastIndexOf(".");
203
                if (n != -1)
204
                        file = file.substring(0, n);
205

    
206
                n = file.lastIndexOf(File.separator);
207
                if(n != -1)
208
                        file = file.substring(n + 1, file.length());
209

    
210
                return file;
211
        }
212

    
213
        public String getLastPart(String string, String pattern) {
214
                int n = string.lastIndexOf(pattern);
215
                if (n > 0)
216
                        return string.substring(n + 1, string.length());
217
                return string;
218
        }
219

    
220
        public String readFileEncoding(String file) {
221
                FileReader fr;
222
                String encoding = null;
223
                try {
224
                        fr = new FileReader(file);
225
                        BufferedReader br = new BufferedReader(fr);
226
                        char[] buffer = new char[100];
227
                        br.read(buffer);
228
                        StringBuffer st = new StringBuffer(new String(buffer));
229
                        String searchText = "encoding=\"";
230
                        int index = st.indexOf(searchText);
231
                        if (index > -1) {
232
                                st.delete(0, index + searchText.length());
233
                                encoding = st.substring(0, st.indexOf("\""));
234
                        }
235
                        fr.close();
236
                } catch (FileNotFoundException ex) {
237
                        ex.printStackTrace();
238
                } catch (IOException e) {
239
                        e.printStackTrace();
240
                }
241
                return encoding;
242
        }
243

    
244
        public String getRMFNameFromFileName(String fileName) {
245
                return getNameWithoutExtension(fileName) + ".rmf";
246
        }
247

    
248
        /**
249
         * Recursive directory delete.
250
         * @param f
251
         */
252
        private void deleteDirectory(File f) {
253
                File[] files = f.listFiles();
254
                for (int i = 0; i < files.length; i++) {
255
                        if (files[i].isDirectory())
256
                                deleteDirectory(files[i]);
257
                        files[i].delete();
258
                }
259
        }
260

    
261
        //******* Servicio de directorios temporales **************
262

    
263
        /**
264
         * Directorio temporal para la cach?. Si gastamos el mismo que andami este se ocupar? de gestionar su
265
         * destrucci?n al cerrar gvSIG.
266
         */
267
        private String tempCacheDirectoryPath = System.getProperty("java.io.tmpdir")
268
                        + File.separator + "tmp-andami";
269

    
270
        public void cleanUpTempFiles() {
271
                try {
272
                        File tempDirectory = new File(tempCacheDirectoryPath);
273

    
274
                        File[] files = tempDirectory.listFiles();
275
                        if (files != null)
276
                                for (int i = 0; i < files.length; i++) {
277
                                        // s?lo por si en un futuro se necesitan crear directorios temporales
278
                                        if (files[i].isDirectory())
279
                                                deleteDirectory(files[i]);
280
                                        files[i].delete();
281
                                }
282
                        tempDirectory.delete();
283
                } catch (Exception e) {
284
                }
285
        }
286

    
287
        public File getTemporalFile() {
288
                File tempDirectory = new File(tempCacheDirectoryPath);
289
                if (!tempDirectory.exists())
290
                        tempDirectory.mkdir();
291
                return tempDirectory;
292
        }
293

    
294
        public String getTemporalPath() {
295
                return getTemporalFile().getAbsolutePath();
296
        }
297

    
298
        /*
299
         * (non-Javadoc)
300
         * @see org.gvsig.fmap.dal.coverage.util.FileUtils#getFormatedRasterFileName(java.lang.String)
301
         */
302
        public String getFormatedRasterFileName(String name) {
303
            throw new UnsupportedOperationException("Deprecated (name = '"+name+"')");
304

    
305
//                if(name.startsWith("PG:host=")) {
306
//                        String newName = "";
307
//                        String schema = null;
308
//                        String table = null;
309
//                        int index = name.indexOf(" schema='") + 8;
310
//                        if(index != -1) {
311
//                                try {
312
//                                        schema = name.substring(index + 1, name.indexOf("'", index + 1));
313
//                                        newName += schema + ".";
314
//                                } catch (StringIndexOutOfBoundsException e) {
315
//                                }
316
//                        }
317
//                        index = name.indexOf(" table='") + 7;
318
//                        if(index != -1) {
319
//                                try {
320
//                                        table = name.substring(index + 1, name.indexOf("'", index + 1));
321
//                                        newName += table;
322
//                                } catch (StringIndexOutOfBoundsException e) {
323
//                                }
324
//                        }
325
//                        return newName;
326
//                }
327
//                return name;
328
        }
329

    
330
        public String convertPathToMD5(String path) throws NoSuchAlgorithmException {
331
                MessageDigest md = java.security.MessageDigest.getInstance("MD5");
332
                md.update(path.getBytes());
333
                return convertToHex(md.digest());
334
        }
335

    
336
        /**
337
         * Converts an array of bytes to hexadecimal string
338
         * @param data
339
         * @return
340
         */
341
        private String convertToHex(byte[] data) {
342
        StringBuffer buf = new StringBuffer();
343
        for (int i = 0; i < data.length; i++) {
344
            int halfbyte = (data[i] >>> 4) & 0x0F;
345
            int two_halfs = 0;
346
            do {
347
                if ((0 <= halfbyte) && (halfbyte <= 9))
348
                    buf.append((char) ('0' + halfbyte));
349
                else
350
                    buf.append((char) ('a' + (halfbyte - 10)));
351
                halfbyte = data[i] & 0x0F;
352
            } while(two_halfs++ < 1);
353
        }
354
        return buf.toString();
355
    }
356

    
357
        //******* Servicio de nombres de capas ?nicos **************
358
        /**
359
         * Contador global de las capas generadas para raster. Hay que contar con que esta
360
         * clase es un singleton desde el manager. Si hay varias instanciaciones layerCount
361
         * dar? valores erroneos.
362
         */
363
        private int                   layerCount = 1;
364
        private ArrayList<PropertyListener>
365
                                                                        propetiesListeners = new ArrayList<PropertyListener>();
366

    
367
        public String usesOnlyLayerName() {
368
                String oldValue = getOnlyLayerName();
369
                String newValue = "NewLayer_" + (++layerCount);
370
                for (int i = 0; i < propetiesListeners.size(); i++)
371
                        if(propetiesListeners.get(i) instanceof PropertyListener)
372
                                ((PropertyListener)propetiesListeners.get(i)).actionValueChanged(new PropertyEvent(oldValue, "NewLayer", newValue, oldValue));
373
                return newValue;
374
        }
375

    
376
        public String getOnlyLayerName() {
377
                return "NewLayer_" + layerCount;
378
        }
379

    
380
        public void addOnlyLayerNameListener(PropertyListener listener) {
381
                if (!propetiesListeners.contains(listener))
382
                        propetiesListeners.add(listener);
383
        }
384

    
385
        public void removeOnlyLayerNameListener(PropertyListener listener) {
386
                for (int i = 0; i < propetiesListeners.size(); i++)
387
                        if(propetiesListeners.get(i) == listener)
388
                                propetiesListeners.remove(i);
389
        }
390

    
391
        //******* End: Servicio de nombres de capas ?nicos **************
392
}