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

History | View | Annotate | Download (13.1 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
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
26
 *
27
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
28
 *
29
 * This program is free software; you can redistribute it and/or
30
 * modify it under the terms of the GNU General Public License
31
 * as published by the Free Software Foundation; either version 2
32
 * of the License, or (at your option) any later version.
33
 *
34
 * This program is distributed in the hope that it will be useful,
35
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37
 * GNU General Public License for more details.
38
 *
39
 * You should have received a copy of the GNU General Public License
40
 * along with this program; if not, write to the Free Software
41
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
42
 *
43
 * For more information, contact:
44
 *
45
 *  Generalitat Valenciana
46
 *   Conselleria d'Infraestructures i Transport
47
 *   Av. Blasco Ib??ez, 50
48
 *   46010 VALENCIA
49
 *   SPAIN
50
 *
51
 *      +34 963862235
52
 *   gvsig@gva.es
53
 *      www.gvsig.gva.es
54
 *
55
 *    or
56
 *
57
 *   IVER T.I. S.A
58
 *   Salamanca 50
59
 *   46005 Valencia
60
 *   Spain
61
 *
62
 *   +34 963163400
63
 *   dac@iver.es
64
 */
65

    
66
import java.io.BufferedOutputStream;
67
import java.io.DataOutputStream;
68
import java.io.File;
69
import java.io.FileNotFoundException;
70
import java.io.FileOutputStream;
71
import java.io.FileReader;
72
import java.io.IOException;
73
import java.io.InputStream;
74
import java.io.OutputStream;
75
import java.net.ConnectException;
76
import java.net.URL;
77
import java.net.UnknownHostException;
78
import java.util.Hashtable;
79
import java.util.StringTokenizer;
80
import java.util.Vector;
81

    
82
import org.gvsig.compat.CompatLocator;
83
import org.gvsig.compat.net.Downloader;
84
import org.gvsig.compat.net.ICancellable;
85

    
86

    
87

    
88

    
89
/**
90
 * Clase con m?todos de utilidad en el protocolo WMS
91
 *
92
 * @authors Laura D?az, jaume dominguez faus
93
 */
94
public class Utilities {
95
        private static final Downloader downloader = CompatLocator.getDownloader();
96
    private static String characters;
97
        static boolean canceled;
98
        static final long latency = 500;
99
        /**
100
         * Used to cancel a group of files
101
         * <b>key</b>: Group id, <b>value</b>: Boolean (true if
102
         * the group has to be canceled. Otherwise it is
103
         * false)
104
         */
105
        static Hashtable canceledGroup = new Hashtable();
106
        /**
107
         * <b>key</b>: URL, <b>value</b>: path to the downloaded file.
108
         */
109
        private static Hashtable downloadedFiles;
110
        static Exception downloadException;
111
        private static final String tempDirectoryPath = System.getProperty("java.io.tmpdir")+"/tmp-andami";
112

    
113

    
114
        static {
115
                characters = "";
116
                for (int j = 32; j<=127; j++){
117
                        characters += (char) j;
118
                }
119
                characters += "?????????????????????????????????????????????????\n\r\f\t??";
120
        }
121

    
122

    
123
        /**
124
         * Checks a File and tries to figure if the file is a text or a binary file.<br>
125
         * Keep in mind that binary files are those that contains at least one
126
         * non-printable character.
127
         *
128
         * @param file
129
         * @return <b>true</b> when the file is <b>pretty problably</b> text,
130
         * <b>false</b> if the file <b>is</b> binary.
131
         */
132
        public static boolean isTextFile(File file){
133
                return isTextFile(file, 1024);
134
        }
135

    
136
        /**
137
         * Checks a File and tries to figure if the file is a text or a binary file.<br>
138
         * Keep in mind that binary files are those that contains at least one
139
         * non-printable character.
140
         *
141
         * @param file
142
         * @param byteAmount, number of bytes to check.
143
         * @return <b>true</b> when the file is <b>pretty problably</b> text,
144
         * <b>false</b> if the file <b>is</b> binary.
145
         */
146
        public static boolean isTextFile(File file, int byteAmount){
147
                int umbral = byteAmount;
148
                try {
149
                        FileReader fr = new FileReader(file);
150
                        for (int i = 0; i < umbral; i++) {
151
                                int c = fr.read();
152
                                if (c==-1){
153
                                        // End of file. If we reach this
154
                                        // everything before is printable data.
155
                                        return true;
156
                                }
157
                                char ch = (char) c;
158
                                if (characters.indexOf(ch)==-1){
159
                                        // We've found a non-printable character.
160
                                        // Then we'll assume that this file is binary.
161
                                        return false;
162
                                }
163
                        }
164
                } catch (FileNotFoundException e) {
165
                        e.printStackTrace();
166
                } catch (IOException e) {
167
                        e.printStackTrace();
168
                }
169
                return true;
170
        }
171

    
172
        /**
173
         * Checks a byte array and tells if it contains only text or contains
174
         * any binary data.
175
         *
176
         * @param file
177
         * @return <b>true</b> when the data is <b>only</b> text, <b>false</b> otherwise.
178
         * @deprecated
179
         */
180
        public static boolean isTextData(byte[] data){
181
                char[] charData = new char[data.length];
182
                for (int i = 0; i<data.length; i++){
183
                        charData[i] = (char) data[i];
184
                }
185

    
186
                for (int i = 0; i < data.length; i++) {
187
                        int c = charData[i];
188

    
189

    
190
                        if (c==-1){
191
                                // End of file. If we reach this
192
                                // everything before is printable data.
193
                                return true;
194
                        }
195
                        char ch = (char) c;
196
                        if (characters.indexOf(ch)==-1){
197
                                // We've found a non-printable character.
198
                                // Then we'll assume that this file is binary.
199

    
200
                                //System.out.println(ch+" at "+i);
201
                                return false;
202
                        }
203
                }
204
                return true;
205
        }
206

    
207

    
208

    
209

    
210
        /**
211
         * Copia el contenido de un InputStream en un OutputStream
212
         *
213
         * @param in InputStream
214
         * @param out OutputStream
215
         */
216
        public static void serializar(InputStream in, OutputStream out) {
217
                byte[] buffer = new byte[102400];
218

    
219
                int n;
220

    
221
                try {
222
                        while ((n = in.read(buffer)) != -1) {
223
                                out.write(buffer, 0, n);
224
                        }
225
                } catch (IOException e) {
226
                        e.printStackTrace();
227
                }
228
        }
229

    
230
        /**
231
         * Elimina del xml la declaraci?n del DTD
232
         *
233
         * @param bytes bytes del fichero XML de respuesta a getCapabilities
234
         * @param startTag Tag raiz del xml respuesta a getCapabilities
235
         *
236
         * @return bytes del fichero XML sin la declaraci?n del DTD
237
         */
238
        public static byte[] eliminarDTD(byte[] bytes, String startTag) {
239
                String text = new String(bytes);
240
                int index1 = text.indexOf("?>") + 2;
241
                int index2;
242

    
243
                try {
244
                        index2 = findBeginIndex(bytes, startTag);
245
                } catch (Exception e) {
246
                        return bytes;
247
                }
248

    
249
                byte[] buffer = new byte[bytes.length - (index2 - index1)];
250
                System.arraycopy(bytes, 0, buffer, 0, index1);
251
                System.arraycopy(bytes, index2, buffer, index1, bytes.length - index2);
252

    
253
                return buffer;
254
        }
255

    
256
        /**
257
         * Obtiene el ?ndice del comienzo del xml
258
         *
259
         * @param bytes bytes del fichero XML en el que se busca
260
         * @param tagRaiz Tag raiz del xml respuesta a getCapabilities
261
         *
262
         * @return ?ndice donde empieza el tag raiz
263
         *
264
         * @throws Exception Si no se encuentra el tag
265
         */
266
        private static int findBeginIndex(byte[] bytes, String tagRaiz)
267
        throws Exception {
268
                try {
269
                        int nodo = 0;
270
                        int ret = -1;
271

    
272
                        int i = 0;
273

    
274
                        while (true) {
275
                                switch (nodo) {
276
                                case 0:
277

    
278
                                        if (bytes[i] == '<') {
279
                                                ret = i;
280
                                                nodo = 1;
281
                                        }
282

    
283
                                        break;
284

    
285
                                case 1:
286

    
287
                                        if (bytes[i] == ' ') {
288
                                        } else if (bytes[i] == tagRaiz.charAt(0)) {
289
                                                nodo = 2;
290
                                        } else {
291
                                                nodo = 0;
292
                                        }
293

    
294
                                        break;
295

    
296
                                case 2:
297

    
298
                                        String aux = new String(bytes, i, 18);
299

    
300
                                        if (aux.equalsIgnoreCase(tagRaiz.substring(1))) {
301
                                                return ret;
302
                                        }
303

    
304
                                        nodo = 0;
305

    
306
                                        break;
307
                                }
308

    
309
                                i++;
310
                        }
311
                } catch (Exception e) {
312
                        throw new Exception("No se pudo parsear el xml", e);
313
                }
314
        }
315

    
316
        /**
317
         * Converts the contents of a Vector to a comma separated list
318
         *
319
         * */
320
        public static String Vector2CS(Vector v)
321
        {
322
                String str = new String();
323
                if (v != null)
324
                {
325
                        int i;
326
                        for (i=0; i<v.size() ;i++)
327
                        {
328
                                str = str + v.elementAt(i);
329
                                if (i<v.size()-1)
330
                                        str = str + ",";
331
                        }
332
                }
333
                return str;
334
        }
335

    
336
        public static boolean isValidVersion(String version)
337
        {
338
                if(version.trim().length() == 5)
339
                {
340
                        if ( (version.charAt(1)=='.') && (version.charAt(3)=='.'))
341
                        {
342
                                char x = version.charAt(0);
343
                                char y = version.charAt(2);
344
                                char z = version.charAt(4);
345

    
346
                                if ((Character.isDigit(x)) && (Character.isDigit(y)) && (Character.isDigit(z)))
347
                                {
348
                                        return true;
349
                                }
350
                                else
351
                                {
352
                                        return false;
353
                                }
354
                        }
355
                        else
356
                        {
357
                                return false;
358
                        }
359
                }
360
                else
361
                {
362
                        return false;
363
                }
364
        }
365

    
366
        /**
367
         * Crea un fichero temporal con un nombre concreto y unos datos pasados por
368
         * par?metro.
369
         * @param fileName Nombre de fichero
370
         * @param data datos a guardar en el fichero
371
         */
372
        public static void createTemp(String fileName, String data)throws IOException{
373
                File f = new File(fileName);
374
                DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)) );
375
                dos.writeBytes(data);
376
                dos.close();
377
                f.deleteOnExit();
378
        }
379

    
380
        /**
381
         * Checks if a String is a number or not
382
         *
383
         * @param String, s
384
         * @return boolean, true if s is a number
385
         */
386
        public static boolean isNumber(String s)
387
        {
388
                try
389
                {
390
                        //double d = Double.parseDouble(s);
391
                        return true;
392
                }
393
                catch(NumberFormatException e)
394
                {
395
                        return false;
396
                }
397

    
398
        }
399

    
400
        /**
401
         * Parses the String containing different items [character] separated and
402
         * creates a vector with them.
403
         * @param str String contains item1[c]item2[c]item3...
404
         * @param c is the string value for separating the items
405
         * @return Vector containing all the items
406
         */
407
        public static Vector createVector(String str, String c)
408
        {
409
                StringTokenizer tokens = new StringTokenizer(str, c);
410
                Vector v = new Vector();
411
                try
412
                {
413
                        while (tokens.hasMoreTokens())
414
                        {
415
                                v.addElement(tokens.nextToken());
416
                        }
417
                        return v;
418
                }
419
                catch (Exception e)
420
                {
421
                        return new Vector();
422
                }
423
        }
424

    
425
        /**
426
         * @param dimensions
427
         * @return
428
         */
429
        public static String Vector2URLParamString(Vector v) {
430
                if (v==null) return "";
431
                String s = "";
432
                for (int i = 0; i < v.size(); i++) {
433
                        s += v.get(i);
434
                        if (i<v.size()-1)
435
                                s += "&";
436
                }
437
                return s;
438
        }
439
        
440
        /**
441
         * Downloads an URL into a temporary file that is removed the next time the
442
         * tempFileManager class is called, which means the next time gvSIG is launched.
443
         *
444
         * @param url
445
         * @param name
446
         * @return
447
         * @throws IOException
448
         * @throws ServerErrorResponseException
449
         * @throws ConnectException
450
         * @throws UnknownHostException
451
         */
452
        public static synchronized File downloadFile(URL url, String name, ICancellable cancel) throws IOException,ConnectException, UnknownHostException{
453
            return downloader.downloadFile(url, name, cancel);
454
        }
455
        
456
        private static String calculateFileName(String name){
457
                int index = name.lastIndexOf(".");
458
                if (index > 0){
459
                        return tempDirectoryPath + "/" + name.substring(0,index) + System.currentTimeMillis() + 
460
                                name.substring(index, name.length());
461
                }
462
                return tempDirectoryPath+"/"+name+System.currentTimeMillis();
463
        }
464

    
465
        /**
466
         * Downloads a URL using the HTTP Post protocol
467
         * @param url
468
         * The server URL
469
         * @param data
470
         * The data to send in the request
471
         * @param name
472
         * A common name for all the retrieved files
473
         * @param cancel
474
         * Used to cancel the downloads
475
         * @return
476
         * The retrieved file
477
         * @throws IOException
478
         * @throws ConnectException
479
         * @throws UnknownHostException
480
         */
481
        public static synchronized File downloadFile(URL url, String data, String name, ICancellable cancel) throws IOException,ConnectException, UnknownHostException{
482
            return downloader.downloadFile(url, data, name, cancel);
483
        }
484

    
485
        /**
486
         * Cleans every temporal file previously downloaded.
487
         */
488
        public static void cleanUpTempFiles() {
489
                downloader.cleanUpTempFiles();
490
        }
491

    
492

    
493
        /**
494
         * Remove an URL from the system cache. The file will remain in the file
495
         * system for further eventual uses.
496
         * @param request
497
         */
498
        public static void removeURL(URL url) {
499
                downloader.removeURL(url);
500
        }
501

    
502
        /**
503
         * Remove an URL from the system cache. The file will remain in the file
504
         * system for further eventual uses.
505
         * @param request
506
         */
507
        public static void removeURL(Object url) {
508
            downloader.removeURL(url);
509
        }
510
        
511
        /**
512
         * This class has to be deleted when all the classes uses the ICancellable
513
         * method from libCompat
514
         * @author gvSIG Team
515
         * @version $Id: Utilities.java 33983 2010-10-27 12:37:48Z nbrodin $
516
         * @deprecated You should use always org.gvsig.compat.net.ICancellable
517
         */
518
        /*private static class CancellableAdapter implements org.gvsig.compat.net.ICancellable {
519
            private ICancellable cancellable = null;
520

521
        public CancellableAdapter(
522
            org.gvsig.remoteclient.wms.ICancellable cancellable) {
523
            super();
524
            this.cancellable = cancellable;
525
        }
526

527
        public Object getID() {            
528
            return cancellable.getID();
529
        }
530

531
        public boolean isCanceled() {     
532
            return cancellable.isCanceled();
533
        }             
534
        }*/
535
}