Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libRemoteServices / src / org / gvsig / remoteclient / utils / Utilities.java @ 29671

History | View | Annotate | Download (21.7 KB)

1
package org.gvsig.remoteclient.utils;
2
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
3
 *
4
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
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., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
19
 *
20
 * For more information, contact:
21
 *
22
 *  Generalitat Valenciana
23
 *   Conselleria d'Infraestructures i Transport
24
 *   Av. Blasco Ib??ez, 50
25
 *   46010 VALENCIA
26
 *   SPAIN
27
 *
28
 *      +34 963862235
29
 *   gvsig@gva.es
30
 *      www.gvsig.gva.es
31
 *
32
 *    or
33
 *
34
 *   IVER T.I. S.A
35
 *   Salamanca 50
36
 *   46005 Valencia
37
 *   Spain
38
 *
39
 *   +34 963163400
40
 *   dac@iver.es
41
 */
42

    
43
import java.io.BufferedOutputStream;
44
import java.io.DataInputStream;
45
import java.io.DataOutputStream;
46
import java.io.File;
47
import java.io.FileNotFoundException;
48
import java.io.FileOutputStream;
49
import java.io.FileReader;
50
import java.io.IOException;
51
import java.io.InputStream;
52
import java.io.OutputStream;
53
import java.io.OutputStreamWriter;
54
import java.net.ConnectException;
55
import java.net.HttpURLConnection;
56
import java.net.URL;
57
import java.net.URLConnection;
58
import java.net.UnknownHostException;
59
import java.rmi.NoSuchObjectException;
60
import java.security.KeyManagementException;
61
import java.security.NoSuchAlgorithmException;
62
import java.util.Hashtable;
63
import java.util.StringTokenizer;
64
import java.util.Vector;
65

    
66
import javax.net.ssl.HttpsURLConnection;
67
import javax.net.ssl.SSLContext;
68
import javax.net.ssl.TrustManager;
69
import javax.net.ssl.X509TrustManager;
70

    
71
import org.gvsig.remoteclient.wms.ICancellable;
72

    
73

    
74

    
75

    
76
/**
77
 * Clase con m?todos de utilidad en el protocolo WMS
78
 *
79
 * @authors Laura D?az, jaume dominguez faus
80
 */
81
public class Utilities {
82
        private static String characters;
83
        static boolean canceled;
84
        static final long latency = 500;
85
        /**
86
         * Used to cancel a group of files
87
         * <b>key</b>: Group id, <b>value</b>: Boolean (true if
88
         * the group has to be canceled. Otherwise it is
89
         * false)
90
         */
91
        static Hashtable canceledGroup = new Hashtable();
92
        /**
93
         * <b>key</b>: URL, <b>value</b>: path to the downloaded file.
94
         */
95
        private static Hashtable downloadedFiles;
96
        static Exception downloadException;
97
        private static final String tempDirectoryPath = System.getProperty("java.io.tmpdir")+"/tmp-andami";
98

    
99

    
100
        static {
101
                characters = "";
102
                for (int j = 32; j<=127; j++){
103
                        characters += (char) j;
104
                }
105
                characters += "?????????????????????????????????????????????????\n\r\f\t??";
106
        }
107

    
108

    
109
        /**
110
         * Checks a File and tries to figure if the file is a text or a binary file.<br>
111
         * Keep in mind that binary files are those that contains at least one
112
         * non-printable character.
113
         *
114
         * @param file
115
         * @return <b>true</b> when the file is <b>pretty problably</b> text,
116
         * <b>false</b> if the file <b>is</b> binary.
117
         */
118
        public static boolean isTextFile(File file){
119
                return isTextFile(file, 1024);
120
        }
121

    
122
        /**
123
         * Checks a File and tries to figure if the file is a text or a binary file.<br>
124
         * Keep in mind that binary files are those that contains at least one
125
         * non-printable character.
126
         *
127
         * @param file
128
         * @param byteAmount, number of bytes to check.
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, int byteAmount){
133
                int umbral = byteAmount;
134
                try {
135
                        FileReader fr = new FileReader(file);
136
                        for (int i = 0; i < umbral; i++) {
137
                                int c = fr.read();
138
                                if (c==-1){
139
                                        // End of file. If we reach this
140
                                        // everything before is printable data.
141
                                        return true;
142
                                }
143
                                char ch = (char) c;
144
                                if (characters.indexOf(ch)==-1){
145
                                        // We've found a non-printable character.
146
                                        // Then we'll assume that this file is binary.
147
                                        return false;
148
                                }
149
                        }
150
                } catch (FileNotFoundException e) {
151
                        e.printStackTrace();
152
                } catch (IOException e) {
153
                        e.printStackTrace();
154
                }
155
                return true;
156
        }
157

    
158
        /**
159
         * Checks a byte array and tells if it contains only text or contains
160
         * any binary data.
161
         *
162
         * @param file
163
         * @return <b>true</b> when the data is <b>only</b> text, <b>false</b> otherwise.
164
         * @deprecated
165
         */
166
        public static boolean isTextData(byte[] data){
167
                char[] charData = new char[data.length];
168
                for (int i = 0; i<data.length; i++){
169
                        charData[i] = (char) data[i];
170
                }
171

    
172
                for (int i = 0; i < data.length; i++) {
173
                        int c = charData[i];
174

    
175

    
176
                        if (c==-1){
177
                                // End of file. If we reach this
178
                                // everything before is printable data.
179
                                return true;
180
                        }
181
                        char ch = (char) c;
182
                        if (characters.indexOf(ch)==-1){
183
                                // We've found a non-printable character.
184
                                // Then we'll assume that this file is binary.
185

    
186
                                //System.out.println(ch+" at "+i);
187
                                return false;
188
                        }
189
                }
190
                return true;
191
        }
192

    
193

    
194

    
195

    
196
        /**
197
         * Copia el contenido de un InputStream en un OutputStream
198
         *
199
         * @param in InputStream
200
         * @param out OutputStream
201
         */
202
        public static void serializar(InputStream in, OutputStream out) {
203
                byte[] buffer = new byte[102400];
204

    
205
                int n;
206

    
207
                try {
208
                        while ((n = in.read(buffer)) != -1) {
209
                                out.write(buffer, 0, n);
210
                        }
211
                } catch (IOException e) {
212
                        e.printStackTrace();
213
                }
214
        }
215

    
216
        /**
217
         * Elimina del xml la declaraci?n del DTD
218
         *
219
         * @param bytes bytes del fichero XML de respuesta a getCapabilities
220
         * @param startTag Tag raiz del xml respuesta a getCapabilities
221
         *
222
         * @return bytes del fichero XML sin la declaraci?n del DTD
223
         */
224
        public static byte[] eliminarDTD(byte[] bytes, String startTag) {
225
                String text = new String(bytes);
226
                int index1 = text.indexOf("?>") + 2;
227
                int index2;
228

    
229
                try {
230
                        index2 = findBeginIndex(bytes, startTag);
231
                } catch (NoSuchObjectException e) {
232
                        return bytes;
233
                }
234

    
235
                byte[] buffer = new byte[bytes.length - (index2 - index1)];
236
                System.arraycopy(bytes, 0, buffer, 0, index1);
237
                System.arraycopy(bytes, index2, buffer, index1, bytes.length - index2);
238

    
239
                return buffer;
240
        }
241

    
242
        /**
243
         * Obtiene el ?ndice del comienzo del xml
244
         *
245
         * @param bytes bytes del fichero XML en el que se busca
246
         * @param tagRaiz Tag raiz del xml respuesta a getCapabilities
247
         *
248
         * @return ?ndice donde empieza el tag raiz
249
         *
250
         * @throws NoSuchObjectException Si no se encuentra el tag
251
         */
252
        private static int findBeginIndex(byte[] bytes, String tagRaiz)
253
        throws NoSuchObjectException {
254
                try {
255
                        int nodo = 0;
256
                        int ret = -1;
257

    
258
                        int i = 0;
259

    
260
                        while (true) {
261
                                switch (nodo) {
262
                                case 0:
263

    
264
                                        if (bytes[i] == '<') {
265
                                                ret = i;
266
                                                nodo = 1;
267
                                        }
268

    
269
                                        break;
270

    
271
                                case 1:
272

    
273
                                        if (bytes[i] == ' ') {
274
                                        } else if (bytes[i] == tagRaiz.charAt(0)) {
275
                                                nodo = 2;
276
                                        } else {
277
                                                nodo = 0;
278
                                        }
279

    
280
                                        break;
281

    
282
                                case 2:
283

    
284
                                        String aux = new String(bytes, i, 18);
285

    
286
                                        if (aux.equalsIgnoreCase(tagRaiz.substring(1))) {
287
                                                return ret;
288
                                        }
289

    
290
                                        nodo = 0;
291

    
292
                                        break;
293
                                }
294

    
295
                                i++;
296
                        }
297
                } catch (Exception e) {
298
                        throw new NoSuchObjectException("No se pudo parsear el xml");
299
                }
300
        }
301

    
302
        /**
303
         * Converts the contents of a Vector to a comma separated list
304
         *
305
         * */
306
        public static String Vector2CS(Vector v)
307
        {
308
                String str = new String();
309
                if (v != null)
310
                {
311
                        int i;
312
                        for (i=0; i<v.size() ;i++)
313
                        {
314
                                str = str + v.elementAt(i);
315
                                if (i<v.size()-1)
316
                                        str = str + ",";
317
                        }
318
                }
319
                return str;
320
        }
321

    
322
        public static boolean isValidVersion(String version)
323
        {
324
                if(version.trim().length() == 5)
325
                {
326
                        if ( (version.charAt(1)=='.') && (version.charAt(3)=='.'))
327
                        {
328
                                char x = version.charAt(0);
329
                                char y = version.charAt(2);
330
                                char z = version.charAt(4);
331

    
332
                                if ((Character.isDigit(x)) && (Character.isDigit(y)) && (Character.isDigit(z)))
333
                                {
334
                                        return true;
335
                                }
336
                                else
337
                                {
338
                                        return false;
339
                                }
340
                        }
341
                        else
342
                        {
343
                                return false;
344
                        }
345
                }
346
                else
347
                {
348
                        return false;
349
                }
350
        }
351

    
352
        /**
353
         * Crea un fichero temporal con un nombre concreto y unos datos pasados por
354
         * par?metro.
355
         * @param fileName Nombre de fichero
356
         * @param data datos a guardar en el fichero
357
         */
358
        public static void createTemp(String fileName, String data)throws IOException{
359
                File f = new File(fileName);
360
                DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)) );
361
                dos.writeBytes(data);
362
                dos.close();
363
                f.deleteOnExit();
364
        }
365

    
366
        /**
367
         * Checks if a String is a number or not
368
         *
369
         * @param String, s
370
         * @return boolean, true if s is a number
371
         */
372
        public static boolean isNumber(String s)
373
        {
374
                try
375
                {
376
                        //double d = Double.parseDouble(s);
377
                        return true;
378
                }
379
                catch(NumberFormatException e)
380
                {
381
                        return false;
382
                }
383

    
384
        }
385

    
386
        /**
387
         * Parses the String containing different items [character] separated and
388
         * creates a vector with them.
389
         * @param str String contains item1[c]item2[c]item3...
390
         * @param c is the string value for separating the items
391
         * @return Vector containing all the items
392
         */
393
        public static Vector createVector(String str, String c)
394
        {
395
                StringTokenizer tokens = new StringTokenizer(str, c);
396
                Vector v = new Vector();
397
                try
398
                {
399
                        while (tokens.hasMoreTokens())
400
                        {
401
                                v.addElement(tokens.nextToken());
402
                        }
403
                        return v;
404
                }
405
                catch (Exception e)
406
                {
407
                        return new Vector();
408
                }
409
        }
410

    
411
        /**
412
         * @param dimensions
413
         * @return
414
         */
415
        public static String Vector2URLParamString(Vector v) {
416
                if (v==null) return "";
417
                String s = "";
418
                for (int i = 0; i < v.size(); i++) {
419
                        s += v.get(i);
420
                        if (i<v.size()-1)
421
                                s += "&";
422
                }
423
                return s;
424
        }
425

    
426
        /**
427
         * Return the content of a file that has been created 
428
         * from a URL using the HTTP GET protocol
429
         * @param url
430
         * The URL
431
         * @return
432
         * File containing this URL's content or null if no file was found.
433
         */
434
        private static File getPreviousDownloadedURL(URL url){
435
                return getPreviousDownloaded(url);
436
        }
437

    
438
        /**
439
         * Return the content of a file that has been created 
440
         * from a URL using the HTTP POST protocol
441
         * @param url
442
         * The URL
443
         * @param data
444
         * The data to send on the query
445
         * @return
446
         * File containing this URL's content or null if no file was found.
447
         */
448
        private static File getPreviousDownloadedURL(URL url, String data){
449
                return getPreviousDownloaded(url+data);
450
        }
451

    
452
        /**
453
         * Returns the content of a URL as a file from the file system.<br>
454
         * <p>
455
         * If the URL has been already downloaded in this session and notified
456
         * to the system using the static <b>Utilities.addDownloadedURL(URL)</b>
457
         * method, it can be restored faster from the file system avoiding to
458
         * download it again.
459
         * </p>
460
         * @param url
461
         * @return File containing this URL's content or null if no file was found.
462
         */
463
        private static File getPreviousDownloaded(Object object){
464
                File f = null;
465
                if (downloadedFiles!=null && downloadedFiles.containsKey(object)){
466
                        String filePath = (String) downloadedFiles.get(object);
467
                        f = new File(filePath);
468
                        if (!f.exists())
469
                                return null;
470
                }
471
                return f;
472
        }
473

    
474
        /**
475
         * Adds an URL to the table of downloaded files for further uses. If the URL
476
         * already exists in the table its filePath value is updated to the new one and
477
         * the old file itself is removed from the file system.
478
         *
479
         * @param url
480
         * @param filePath
481
         */
482
        static void addDownloadedURL(URL url, String filePath){
483
                if (downloadedFiles==null)
484
                        downloadedFiles = new Hashtable();
485
                String fileName = (String) downloadedFiles.put(url, filePath);
486
                //JMV: No se puede eliminar el anterior porque puede que alguien lo
487
                // este usando
488
                /*
489
        if (fileName!=null){
490
            File f = new File(fileName);
491
            if (f.exists())
492
                f.delete();
493
        }
494
                 */
495
        }
496

    
497
        /**
498
         * Downloads an URL into a temporary file that is removed the next time the
499
         * tempFileManager class is called, which means the next time gvSIG is launched.
500
         *
501
         * @param url
502
         * @param name
503
         * @return
504
         * @throws IOException
505
         * @throws ServerErrorResponseException
506
         * @throws ConnectException
507
         * @throws UnknownHostException
508
         */
509
        public static synchronized File downloadFile(URL url, String name, ICancellable cancel) throws IOException,ConnectException, UnknownHostException{
510
                File f = null;
511

    
512
                if ((f=getPreviousDownloadedURL(url))==null){
513
                        File tempDirectory = new File(tempDirectoryPath);
514
                        if (!tempDirectory.exists())
515
                                tempDirectory.mkdir();
516

    
517
                        f = new File(calculateFileName(name));
518

    
519
                        if (cancel == null) {
520
                                cancel = new ICancellable() {
521
                                        public boolean isCanceled() {
522
                                                return false;
523
                                        }
524
                                        public Object getID(){
525
                                                return Utilities.class.getName();
526
                                        }
527
                                };
528
                        }
529
                        Thread downloader = new Thread(new Downloader(url, f, cancel.getID()));
530
                        Thread monitor = new Thread(new Monitor(cancel));
531
                        monitor.start();
532
                        downloader.start();
533
                        while(!getCanceled(cancel.getID()) && downloader.isAlive()) {
534
                                try {
535
                                        Thread.sleep(latency);
536
                                } catch (InterruptedException e) {
537
                                        // TODO Auto-generated catch block
538
                                        e.printStackTrace();
539
                                }
540
                        }
541

    
542
                        if (getCanceled(cancel.getID()))
543
                                return null;
544
                        downloader = null;
545
                        monitor = null;
546
                        if (Utilities.downloadException!=null) {
547
                                Exception e = Utilities.downloadException;
548
                                if (e instanceof FileNotFoundException)
549
                                        throw (IOException) e;
550
                                else if (e instanceof IOException)
551
                                        throw (IOException) e;
552
                                else if (e instanceof ConnectException)
553
                                        throw (ConnectException) e;
554
                                else if (e instanceof UnknownHostException)
555
                                        throw (UnknownHostException) e;
556
                        }
557
                } else {
558
                        System.out.println(url.toString()+" cached at '"+f.getAbsolutePath()+"'");
559
                }
560

    
561
                return f;
562
        }
563
        
564
        private static String calculateFileName(String name){
565
                int index = name.lastIndexOf(".");
566
                if (index > 0){
567
                        return tempDirectoryPath + "/" + name.substring(0,index) + System.currentTimeMillis() + 
568
                                name.substring(index, name.length()-1);
569
                }
570
                return tempDirectoryPath+"/"+name+System.currentTimeMillis();
571
        }
572

    
573
        /**
574
         * Downloads a URL using the HTTP Post protocol
575
         * @param url
576
         * The server URL
577
         * @param data
578
         * The data to send in the request
579
         * @param name
580
         * A common name for all the retrieved files
581
         * @param cancel
582
         * Used to cancel the downloads
583
         * @return
584
         * The retrieved file
585
         * @throws IOException
586
         * @throws ConnectException
587
         * @throws UnknownHostException
588
         */
589
        public static synchronized File downloadFile(URL url, String data, String name, ICancellable cancel) throws IOException,ConnectException, UnknownHostException{
590
                File f = null;
591

    
592
                if ((f=getPreviousDownloadedURL(url,data))==null){
593
                        File tempDirectory = new File(tempDirectoryPath);
594
                        if (!tempDirectory.exists())
595
                                tempDirectory.mkdir();
596

    
597
                        f = new File(calculateFileName(name));
598

    
599
                        if (cancel == null) {
600
                                cancel = new ICancellable() {
601
                                        public boolean isCanceled() {
602
                                                return false;
603
                                        }
604
                                        public Object getID(){
605
                                                return Utilities.class.getName();
606
                                        }
607
                                };
608
                        }
609
                        Thread downloader = new Thread(new Downloader(url, data, f, cancel.getID()));
610
                        Thread monitor = new Thread(new Monitor(cancel));
611
                        monitor.start();
612
                        downloader.start();
613
                        while(!getCanceled(cancel.getID()) && downloader.isAlive()) {
614
                                try {
615
                                        Thread.sleep(latency);
616
                                } catch (InterruptedException e) {
617
                                        // TODO Auto-generated catch block
618
                                        e.printStackTrace();
619
                                }
620
                        }
621

    
622
                        if (getCanceled(cancel.getID()))
623
                                return null;
624
                        downloader = null;
625
                        monitor = null;
626
                        if (Utilities.downloadException!=null) {
627
                                Exception e = Utilities.downloadException;
628
                                if (e instanceof FileNotFoundException)
629
                                        throw (IOException) e;
630
                                else if (e instanceof IOException)
631
                                        throw (IOException) e;
632
                                else if (e instanceof ConnectException)
633
                                        throw (ConnectException) e;
634
                                else if (e instanceof UnknownHostException)
635
                                        throw (UnknownHostException) e;
636
                        }
637
                } else {
638
                        System.out.println(url.toString()+" cached at '"+f.getAbsolutePath()+"'");
639
                }
640

    
641
                return f;
642
        }
643

    
644
        /**
645
         * Try if a group of downloads has been canceled
646
         * @param groupId
647
         * Group id
648
         * @return
649
         * If the group has been canceled
650
         */
651
        protected static boolean getCanceled(Object groupId){
652
                Object obj = canceledGroup.get(groupId);
653
                if (obj != null){
654
                        return ((Boolean)obj).booleanValue();
655
                }
656
                return false;
657
        }
658

    
659
        /**
660
         * Cancel a group of downloads
661
         * @param groupId
662
         * Group id
663
         * @param isCanceled
664
         * if the group has to be canceled
665
         */
666
        protected static void setCanceled(Object groupId, boolean isCanceled){
667
                if (groupId == null){
668
                        groupId = Utilities.class.getName();
669
                }
670
                canceledGroup.put(groupId,new Boolean(isCanceled));
671
        }
672

    
673
        /**
674
         * Cleans every temporal file previously downloaded.
675
         */
676
        public static void cleanUpTempFiles() {
677
                try{
678
                        File tempDirectory = new File(tempDirectoryPath);
679

    
680
                        File[] files = tempDirectory.listFiles();
681
                        if (files!=null) {
682
                                for (int i = 0; i < files.length; i++) {
683
                                        // s?lo por si en un futuro se necesitan crear directorios temporales
684
                                        if (files[i].isDirectory())        deleteDirectory(files[i]);
685
                                        files[i].delete();
686
                                }
687
                        }
688
                        tempDirectory.delete();
689
                } catch (Exception e) {        }
690

    
691
        }
692
        /**
693
         * Recursive directory delete.
694
         * @param f
695
         */
696
        private static void deleteDirectory(File f) {
697
                File[] files = f.listFiles();
698
                for (int i = 0; i < files.length; i++) {
699
                        if (files[i].isDirectory()) deleteDirectory(files[i]);
700
                        files[i].delete();
701
                }
702

    
703
        }
704

    
705

    
706
        /**
707
         * Remove an URL from the system cache. The file will remain in the file
708
         * system for further eventual uses.
709
         * @param request
710
         */
711
        public static void removeURL(URL url) {
712
                if (downloadedFiles != null && downloadedFiles.containsKey(url))
713
                        downloadedFiles.remove(url);
714
        }
715

    
716
        /**
717
         * Remove an URL from the system cache. The file will remain in the file
718
         * system for further eventual uses.
719
         * @param request
720
         */
721
        public static void removeURL(Object url) {
722
                if (downloadedFiles != null && downloadedFiles.containsKey(url))
723
                        downloadedFiles.remove(url);
724
        }
725
}
726

    
727
final class Monitor implements Runnable {
728
        ICancellable c;
729
        public Monitor(ICancellable cancel) {
730
                Utilities.setCanceled(cancel.getID(),false);
731
                this.c = cancel;
732
        }
733
        public void run() {
734
                while (!c.isCanceled()) {
735
                        try {
736
                                Thread.sleep(Utilities.latency);
737
                        } catch (InterruptedException e) {
738
                                e.printStackTrace();
739
                        }
740
                }
741

    
742
                /*  WARNING!! This works because only one download is being processed at once.
743
                 *  You could prefer to start several transfers simultaneously. If so, you
744
                 *  should consideer using a non-static variable such is Utilities.canceled to
745
                 *  control when and which transfer in particular has been canceled.
746
                 *
747
                 *  The feature of transfer several files is at the moment under study. We are
748
                 *  planning to add an intelligent system that will give you a lot of services
749
                 *  and ease-of-use. So, we encourage you to wait for it instead of write your
750
                 *  own code.
751
                 */
752

    
753
                Utilities.setCanceled(c.getID(),true);
754
        }
755
}
756

    
757
final class Downloader implements Runnable {
758
        private URL url;
759
        private File dstFile;
760
        private Object groupID = null;
761
        private String data = null;
762

    
763
        public Downloader(URL url, File dstFile, Object groupID) {
764
                this.url = url;
765
                this.dstFile = dstFile;
766
                this.groupID = groupID;
767
                Utilities.downloadException = null;
768
        }
769

    
770
        public Downloader(URL url, String data, File dstFile, Object groupID) {
771
                this.url = url;
772
                this.data = data;
773
                this.dstFile = dstFile;
774
                this.groupID = groupID;
775
                Utilities.downloadException = null;
776
        }
777

    
778
        public void run() {
779
                System.out.println("downloading '"+url.toString()+"' to: "+dstFile.getAbsolutePath());
780

    
781
                DataOutputStream dos;
782
                try {
783
                        DataInputStream is;
784
                        OutputStreamWriter os = null;
785
                        HttpURLConnection connection = null;
786
                        //If the used protocol is HTTPS
787
                        if (url.getProtocol().equals("https")){
788
                                disableHttsValidation();
789
                        }
790
                        connection = (HttpURLConnection)url.openConnection();
791
                        //If it uses a HTTP POST
792
                        if (data != null){
793
                                connection.setRequestProperty("SOAPAction","post");
794
                                connection.setRequestMethod("POST");
795
                                connection.setDoOutput(true);
796
                                connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
797
                                os = new OutputStreamWriter(connection.getOutputStream());
798
                                os.write(data);
799
                                os.flush();        
800
                                is = new DataInputStream(connection.getInputStream());
801
                        }else{
802
                                is = new DataInputStream(url.openStream());
803
                        }
804
                        
805
                        dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(dstFile)));
806
                        byte[] buffer = new byte[1024*4];
807

    
808

    
809
                        long readed = 0;
810
                        for (int i = is.read(buffer); !Utilities.getCanceled(groupID) && i>0; i = is.read(buffer)){
811
                                dos.write(buffer, 0, i);
812
                                readed += i;
813

    
814
                        }
815
                        if(os != null){
816
                                os.close();
817
                        }
818
                        dos.close();
819
                        is.close();
820
                        is = null;
821
                        dos = null;
822
                        if (Utilities.getCanceled(groupID)) {
823
                                System.err.println("[RemoteServices] '"+url+"' CANCELED.");
824
                                dstFile.delete();
825
                                dstFile= null;
826
                        } else {
827
                                Utilities.addDownloadedURL(url, dstFile.getAbsolutePath());
828
                        }
829
                } catch (Exception e) {
830
                        e.printStackTrace();
831
                        Utilities.downloadException = e;
832
                }                
833
        }
834

    
835
        /**
836
         * This method disables the Https certificate validation.
837
         * @throws KeyManagementException
838
         * @throws NoSuchAlgorithmException
839
         */
840
        private void disableHttsValidation() throws KeyManagementException, NoSuchAlgorithmException{
841
                // Create a trust manager that does not validate certificate chains
842
                TrustManager[] trustAllCerts = new TrustManager[]{
843
                                new X509TrustManager() {
844
                                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
845
                                                return null;
846
                                        }
847
                                        public void checkClientTrusted(
848
                                                        java.security.cert.X509Certificate[] certs, String authType) {
849
                                        }
850
                                        public void checkServerTrusted(
851
                                                        java.security.cert.X509Certificate[] certs, String authType) {
852
                                        }
853
                                }
854
                };
855

    
856
                // Install the all-trusting trust manager
857
                SSLContext sc = SSLContext.getInstance("SSL");
858
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
859
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
860
        }
861
}