Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.remoteclient / src / main / java / org / gvsig / remoteclient / utils / Utilities.java @ 40769

History | View | Annotate | Download (11.9 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
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 3
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.remoteclient.utils;
25

    
26
import java.io.BufferedOutputStream;
27
import java.io.DataOutputStream;
28
import java.io.File;
29
import java.io.FileNotFoundException;
30
import java.io.FileOutputStream;
31
import java.io.FileReader;
32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.io.OutputStream;
35
import java.net.ConnectException;
36
import java.net.URL;
37
import java.net.UnknownHostException;
38
import java.util.Hashtable;
39
import java.util.StringTokenizer;
40
import java.util.Vector;
41

    
42
import org.gvsig.compat.CompatLocator;
43
import org.gvsig.compat.net.Downloader;
44
import org.gvsig.compat.net.ICancellable;
45

    
46

    
47

    
48

    
49
/**
50
 * Clase con m?todos de utilidad en el protocolo WMS
51
 *
52
 * @authors Laura D?az, jaume dominguez faus
53
 */
54
public class Utilities {
55
        private static final Downloader downloader = CompatLocator.getDownloader();
56
    private static String characters;
57
        static boolean canceled;
58
        static final long latency = 500;
59
        /**
60
         * Used to cancel a group of files
61
         * <b>key</b>: Group id, <b>value</b>: Boolean (true if
62
         * the group has to be canceled. Otherwise it is
63
         * false)
64
         */
65
        static Hashtable canceledGroup = new Hashtable();
66
        /**
67
         * <b>key</b>: URL, <b>value</b>: path to the downloaded file.
68
         */
69
        private static Hashtable downloadedFiles;
70
        static Exception downloadException;
71
        private static final String tempDirectoryPath = System.getProperty("java.io.tmpdir")+"/tmp-andami";
72

    
73

    
74
        static {
75
                characters = "";
76
                for (int j = 32; j<=127; j++){
77
                        characters += (char) j;
78
                }
79
                characters += "?????????????????????????????????????????????????\n\r\f\t??";
80
        }
81

    
82

    
83
        /**
84
         * Checks a File and tries to figure if the file is a text or a binary file.<br>
85
         * Keep in mind that binary files are those that contains at least one
86
         * non-printable character.
87
         *
88
         * @param file
89
         * @return <b>true</b> when the file is <b>pretty problably</b> text,
90
         * <b>false</b> if the file <b>is</b> binary.
91
         */
92
        public static boolean isTextFile(File file){
93
                return isTextFile(file, 1024);
94
        }
95

    
96
        /**
97
         * Checks a File and tries to figure if the file is a text or a binary file.<br>
98
         * Keep in mind that binary files are those that contains at least one
99
         * non-printable character.
100
         *
101
         * @param file
102
         * @param byteAmount, number of bytes to check.
103
         * @return <b>true</b> when the file is <b>pretty problably</b> text,
104
         * <b>false</b> if the file <b>is</b> binary.
105
         */
106
        public static boolean isTextFile(File file, int byteAmount){
107
                int umbral = byteAmount;
108
                try {
109
                        FileReader fr = new FileReader(file);
110
                        for (int i = 0; i < umbral; i++) {
111
                                int c = fr.read();
112
                                if (c==-1){
113
                                        // End of file. If we reach this
114
                                        // everything before is printable data.
115
                                        return true;
116
                                }
117
                                char ch = (char) c;
118
                                if (characters.indexOf(ch)==-1){
119
                                        // We've found a non-printable character.
120
                                        // Then we'll assume that this file is binary.
121
                                        return false;
122
                                }
123
                        }
124
                } catch (FileNotFoundException e) {
125
                        e.printStackTrace();
126
                } catch (IOException e) {
127
                        e.printStackTrace();
128
                }
129
                return true;
130
        }
131

    
132
        /**
133
         * Checks a byte array and tells if it contains only text or contains
134
         * any binary data.
135
         *
136
         * @param file
137
         * @return <b>true</b> when the data is <b>only</b> text, <b>false</b> otherwise.
138
         * @deprecated
139
         */
140
        public static boolean isTextData(byte[] data){
141
                char[] charData = new char[data.length];
142
                for (int i = 0; i<data.length; i++){
143
                        charData[i] = (char) data[i];
144
                }
145

    
146
                for (int i = 0; i < data.length; i++) {
147
                        int c = charData[i];
148

    
149

    
150
                        if (c==-1){
151
                                // End of file. If we reach this
152
                                // everything before is printable data.
153
                                return true;
154
                        }
155
                        char ch = (char) c;
156
                        if (characters.indexOf(ch)==-1){
157
                                // We've found a non-printable character.
158
                                // Then we'll assume that this file is binary.
159

    
160
                                //System.out.println(ch+" at "+i);
161
                                return false;
162
                        }
163
                }
164
                return true;
165
        }
166

    
167

    
168

    
169

    
170
        /**
171
         * Copia el contenido de un InputStream en un OutputStream
172
         *
173
         * @param in InputStream
174
         * @param out OutputStream
175
         */
176
        public static void serializar(InputStream in, OutputStream out) {
177
                byte[] buffer = new byte[102400];
178

    
179
                int n;
180

    
181
                try {
182
                        while ((n = in.read(buffer)) != -1) {
183
                                out.write(buffer, 0, n);
184
                        }
185
                } catch (IOException e) {
186
                        e.printStackTrace();
187
                }
188
        }
189

    
190
        /**
191
         * Elimina del xml la declaraci?n del DTD
192
         *
193
         * @param bytes bytes del fichero XML de respuesta a getCapabilities
194
         * @param startTag Tag raiz del xml respuesta a getCapabilities
195
         *
196
         * @return bytes del fichero XML sin la declaraci?n del DTD
197
         */
198
        public static byte[] eliminarDTD(byte[] bytes, String startTag) {
199
                String text = new String(bytes);
200
                int index1 = text.indexOf("?>") + 2;
201
                int index2;
202

    
203
                try {
204
                        index2 = findBeginIndex(bytes, startTag);
205
                } catch (Exception e) {
206
                        return bytes;
207
                }
208

    
209
                byte[] buffer = new byte[bytes.length - (index2 - index1)];
210
                System.arraycopy(bytes, 0, buffer, 0, index1);
211
                System.arraycopy(bytes, index2, buffer, index1, bytes.length - index2);
212

    
213
                return buffer;
214
        }
215

    
216
        /**
217
         * Obtiene el ?ndice del comienzo del xml
218
         *
219
         * @param bytes bytes del fichero XML en el que se busca
220
         * @param tagRaiz Tag raiz del xml respuesta a getCapabilities
221
         *
222
         * @return ?ndice donde empieza el tag raiz
223
         *
224
         * @throws Exception Si no se encuentra el tag
225
         */
226
        private static int findBeginIndex(byte[] bytes, String tagRaiz)
227
        throws Exception {
228
                try {
229
                        int nodo = 0;
230
                        int ret = -1;
231

    
232
                        int i = 0;
233

    
234
                        while (true) {
235
                                switch (nodo) {
236
                                case 0:
237

    
238
                                        if (bytes[i] == '<') {
239
                                                ret = i;
240
                                                nodo = 1;
241
                                        }
242

    
243
                                        break;
244

    
245
                                case 1:
246

    
247
                                        if (bytes[i] == ' ') {
248
                                        } else if (bytes[i] == tagRaiz.charAt(0)) {
249
                                                nodo = 2;
250
                                        } else {
251
                                                nodo = 0;
252
                                        }
253

    
254
                                        break;
255

    
256
                                case 2:
257

    
258
                                        String aux = new String(bytes, i, 18);
259

    
260
                                        if (aux.equalsIgnoreCase(tagRaiz.substring(1))) {
261
                                                return ret;
262
                                        }
263

    
264
                                        nodo = 0;
265

    
266
                                        break;
267
                                }
268

    
269
                                i++;
270
                        }
271
                } catch (Exception e) {
272
                        throw new Exception("No se pudo parsear el xml", e);
273
                }
274
        }
275

    
276
        /**
277
         * Converts the contents of a Vector to a comma separated list
278
         *
279
         * */
280
        public static String Vector2CS(Vector v)
281
        {
282
                String str = new String();
283
                if (v != null)
284
                {
285
                        int i;
286
                        for (i=0; i<v.size() ;i++)
287
                        {
288
                                str = str + v.elementAt(i);
289
                                if (i<v.size()-1)
290
                                        str = str + ",";
291
                        }
292
                }
293
                return str;
294
        }
295

    
296
        public static boolean isValidVersion(String version)
297
        {
298
                if(version.trim().length() == 5)
299
                {
300
                        if ( (version.charAt(1)=='.') && (version.charAt(3)=='.'))
301
                        {
302
                                char x = version.charAt(0);
303
                                char y = version.charAt(2);
304
                                char z = version.charAt(4);
305

    
306
                                if ((Character.isDigit(x)) && (Character.isDigit(y)) && (Character.isDigit(z)))
307
                                {
308
                                        return true;
309
                                }
310
                                else
311
                                {
312
                                        return false;
313
                                }
314
                        }
315
                        else
316
                        {
317
                                return false;
318
                        }
319
                }
320
                else
321
                {
322
                        return false;
323
                }
324
        }
325

    
326
        /**
327
         * Crea un fichero temporal con un nombre concreto y unos datos pasados por
328
         * par?metro.
329
         * @param fileName Nombre de fichero
330
         * @param data datos a guardar en el fichero
331
         */
332
        public static void createTemp(String fileName, String data)throws IOException{
333
                File f = new File(fileName);
334
                DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)) );
335
                dos.writeBytes(data);
336
                dos.close();
337
                f.deleteOnExit();
338
        }
339

    
340
        /**
341
         * Checks if a String is a number or not
342
         *
343
         * @param String, s
344
         * @return boolean, true if s is a number
345
         */
346
        public static boolean isNumber(String s)
347
        {
348
                try
349
                {
350
                        //double d = Double.parseDouble(s);
351
                        return true;
352
                }
353
                catch(NumberFormatException e)
354
                {
355
                        return false;
356
                }
357

    
358
        }
359

    
360
        /**
361
         * Parses the String containing different items [character] separated and
362
         * creates a vector with them.
363
         * @param str String contains item1[c]item2[c]item3...
364
         * @param c is the string value for separating the items
365
         * @return Vector containing all the items
366
         */
367
        public static Vector createVector(String str, String c)
368
        {
369
                StringTokenizer tokens = new StringTokenizer(str, c);
370
                Vector v = new Vector();
371
                try
372
                {
373
                        while (tokens.hasMoreTokens())
374
                        {
375
                                v.addElement(tokens.nextToken());
376
                        }
377
                        return v;
378
                }
379
                catch (Exception e)
380
                {
381
                        return new Vector();
382
                }
383
        }
384

    
385
        /**
386
         * @param dimensions
387
         * @return
388
         */
389
        public static String Vector2URLParamString(Vector v) {
390
                if (v==null) return "";
391
                String s = "";
392
                for (int i = 0; i < v.size(); i++) {
393
                        s += v.get(i);
394
                        if (i<v.size()-1)
395
                                s += "&";
396
                }
397
                return s;
398
        }
399
        
400
        /**
401
         * Downloads an URL into a temporary file that is removed the next time the
402
         * tempFileManager class is called, which means the next time gvSIG is launched.
403
         *
404
         * @param url
405
         * @param name
406
         * @return
407
         * @throws IOException
408
         * @throws ServerErrorResponseException
409
         * @throws ConnectException
410
         * @throws UnknownHostException
411
         */
412
        public static synchronized File downloadFile(URL url, String name, ICancellable cancel) throws IOException,ConnectException, UnknownHostException{
413
            return downloader.downloadFile(url, name, cancel);
414
        }
415
        
416
        private static String calculateFileName(String name){
417
                int index = name.lastIndexOf(".");
418
                if (index > 0){
419
                        return tempDirectoryPath + "/" + name.substring(0,index) + System.currentTimeMillis() + 
420
                                name.substring(index, name.length());
421
                }
422
                return tempDirectoryPath+"/"+name+System.currentTimeMillis();
423
        }
424

    
425
        /**
426
         * Downloads a URL using the HTTP Post protocol
427
         * @param url
428
         * The server URL
429
         * @param data
430
         * The data to send in the request
431
         * @param name
432
         * A common name for all the retrieved files
433
         * @param cancel
434
         * Used to cancel the downloads
435
         * @return
436
         * The retrieved file
437
         * @throws IOException
438
         * @throws ConnectException
439
         * @throws UnknownHostException
440
         */
441
        public static synchronized File downloadFile(URL url, String data, String name, ICancellable cancel) throws IOException,ConnectException, UnknownHostException{
442
            return downloader.downloadFile(url, data, name, cancel);
443
        }
444

    
445
        /**
446
         * Cleans every temporal file previously downloaded.
447
         */
448
        public static void cleanUpTempFiles() {
449
                downloader.cleanUpTempFiles();
450
        }
451

    
452

    
453
        /**
454
         * Remove an URL from the system cache. The file will remain in the file
455
         * system for further eventual uses.
456
         * @param request
457
         */
458
        public static void removeURL(URL url) {
459
                downloader.removeURL(url);
460
        }
461

    
462
        /**
463
         * Remove an URL from the system cache. The file will remain in the file
464
         * system for further eventual uses.
465
         * @param request
466
         */
467
        public static void removeURL(Object url) {
468
            downloader.removeURL(url);
469
        }
470
        
471
        /**
472
         * This class has to be deleted when all the classes uses the ICancellable
473
         * method from libCompat
474
         * @author gvSIG Team
475
         * @version $Id: Utilities.java 33983 2010-10-27 12:37:48Z nbrodin $
476
         * @deprecated You should use always org.gvsig.compat.net.ICancellable
477
         */
478
        /*private static class CancellableAdapter implements org.gvsig.compat.net.ICancellable {
479
            private ICancellable cancellable = null;
480

481
        public CancellableAdapter(
482
            org.gvsig.remoteclient.wms.ICancellable cancellable) {
483
            super();
484
            this.cancellable = cancellable;
485
        }
486

487
        public Object getID() {            
488
            return cancellable.getID();
489
        }
490

491
        public boolean isCanceled() {     
492
            return cancellable.isCanceled();
493
        }             
494
        }*/
495
}