Statistics
| Revision:

svn-gvsig-desktop / tags / gvSIGv0_6_1RELEASE / extensions / extWCS / src / es / uji / lsi / wcs / client / WCSClient.java @ 5222

History | View | Annotate | Download (17.7 KB)

1
package es.uji.lsi.wcs.client;
2
/*
3
 * WCSclient.java
4
 *
5
 * Created on 1 de diciembre de 2004, 21:56
6
 * 
7
 * This file is supposed to implement the interface beetween server and client.
8
 * It will implement the GetCapabilities, DescribeCoverage and GetCoverage
9
 * operations. 
10
 */
11
import java.io.BufferedOutputStream;
12
import java.io.DataOutputStream;
13
import java.io.File;
14
import java.io.FileNotFoundException;
15
import java.io.FileOutputStream;
16
import java.io.FileReader;
17
import java.io.IOException;
18
import java.io.InputStream;
19
import java.net.ConnectException;
20
import java.net.MalformedURLException;
21
import java.net.URL;
22
import java.net.UnknownHostException;
23

    
24
import com.devx.io.TempFileManager;
25

    
26
import es.uji.lsi.wcs.XmlWcsParsing.Capabilities;
27
import es.uji.lsi.wcs.XmlWcsParsing.CoverageOffering;
28
import es.uji.lsi.wcs.XmlWcsParsing.DescribeCoverageResponse;
29
import es.uji.lsi.wcs.XmlWcsParsing.WCSExceptionResponse;
30
import es.uji.lsi.wcs.XmlWcsParsing.XMLNode;
31

    
32

    
33
/**
34
 *
35
 * @author  jaume
36
 */
37
public class WCSClient {
38
    
39
        public Capabilities capabilities;
40
    public DescribeCoverageResponse describeCoverageResponse;
41
    
42
    private OperationGetCapabilities operationGetCapabilities;
43
    private OperationDescribeCoverage operationDescribeCoverage;
44
    private OperationGetCoverage operationGetCoverage;
45
    private WCSExceptionResponse wcs_exception;
46
    // the working address
47
    private String working_address;
48
    
49
    // When working off-line (for development uses only)
50
    private boolean working_offline = false;
51
    private File file = null; 
52
    
53
    private File fileGetCapabilities, fileDescribeCoverage, fileGetCoverage;
54
    private String path, datapath, coveragefilename, coveragefileextension;
55
    private static String characters;
56
        
57
    static {
58
            characters = "";
59
                for (int j = 32; j<=127; j++){
60
                        characters += (char) j;
61
                }
62
                characters += "?????????????????????????????????????????????????\n\r\f\t";
63
    }
64
    
65
    /** Creates a new instance of WCSclient */
66
    public WCSClient(String text) {
67
        this.working_address = text;
68
        operationGetCapabilities = new OperationGetCapabilities();
69
        operationDescribeCoverage = new OperationDescribeCoverage();
70
        operationGetCoverage = new OperationGetCoverage();
71
    }
72
    
73
    public WCSClient(){
74
        working_address = "http://localhost:8080";
75
        operationGetCapabilities = new OperationGetCapabilities();
76
        operationDescribeCoverage = new OperationDescribeCoverage();
77
        operationGetCoverage = new OperationGetCoverage();
78
    }
79
    
80
    public WCSClient(File file){
81
        working_offline = true;
82
        this.file = file;
83
        operationGetCapabilities = new OperationGetCapabilities();
84
        operationDescribeCoverage = new OperationDescribeCoverage();
85
        operationGetCoverage = new OperationGetCoverage();
86

    
87
    }
88
    
89
    public Capabilities getTheCapabilities(){
90
        return capabilities;
91
    } 
92
    /**
93
     * @deprecated
94
     */
95
    public void _getCapabilities(){
96
        // Opens the source of the GetCapabilities XML description
97
            // System.out.println("WCSClient>>> GetCapabilities");
98
        try {
99
            
100
            XMLNode node;
101
            if (working_offline) node = new XMLNode(file);
102
            else{
103
                URL url = new URL(construyeURL(working_address, operationGetCapabilities.getParamsString()));
104
                node = new XMLNode(url.openStream()); 
105
                // System.out.println("WCSClient>>> GetCapabilities done...");
106
            } 
107
            capabilities = new Capabilities(node);
108
            
109
        } catch (MalformedURLException e){
110
            new Error("Bad URL");
111
        } catch (IOException e){
112
            new Error("Unable to retrieve server capabilities");
113
        } catch (Exception e){
114
            new Error();
115
        }            
116

    
117
    }
118
    
119
    /**
120
     * Creates a WCS compliant request URL.
121
     * 
122
     * @param dir
123
     * @param param
124
     * @return string
125
     */
126
    private String construyeURL(String dir, String param){
127
            if (dir.indexOf('?')==-1) return dir+"?"+param;
128
            else return dir+"&"+param;
129
    }
130
    
131
    /**
132
     * Opens the source of the GetCapabilities XML description and
133
     * loads it into the capabilities field.
134
     * 
135
     * @throws ServerOutOfOrderException
136
     */
137
    public void getCapabilities() throws ServerOutOfOrderException{
138
        try {
139
            
140
            XMLNode node;
141
            if (working_offline) node = new XMLNode(file);
142
            else{
143
                URL url = new URL(construyeURL(working_address, operationGetCapabilities.getParamsString()));
144
                fileGetCapabilities = downloadFile(url, "wcs_GetCapabilities");
145
                node = new XMLNode(fileGetCapabilities); 
146
            } 
147
            capabilities = new Capabilities(node);
148
            if (capabilities == null){
149
                    throw new ServerOutOfOrderException();
150
            }
151
        } catch (UnknownHostException uhe){ 
152
                throw new ServerOutOfOrderException();
153
        }  catch (ConnectException ce){ 
154
                throw new ServerOutOfOrderException();
155
        } catch (MalformedURLException e){
156
            new Error("Bad URL");
157
        } catch (IOException e){
158
                throw new ServerOutOfOrderException();
159
        } catch (Exception e){
160
            new Error();
161
        }            
162

    
163
    }
164

    
165
    
166
    /**
167
     * Returns a description offered by the DescribeCoverage
168
     * 
169
     * Devuelve la descripci?n de la cobertura ofrecida en el DescribeCoverage
170
     * 
171
     * @param nomCobertura
172
     * @return es.uji.lsi.XmlWcsParsing.CoverageOffering 
173
     */
174
    public CoverageOffering getCoverageDescription(String nomCobertura){
175
            return describeCoverageResponse.getCoverageOffering(nomCobertura);
176
        }
177
    
178
    
179
    /**
180
     * Unused
181
     * 
182
     * Sin uso
183
     * 
184
     * @deprecated
185
     * @param url
186
     */
187
    
188
    public void describeCoverage(URL url){
189
            XMLNode node;
190
            try {
191
                    downloadFile(url, this.datapath);
192
            node = new XMLNode(url.openStream());
193
            } catch (Exception e){
194
                    new Error(e.getMessage());
195
            }
196
    }
197

    
198
    /**
199
     * Launches a DescribeCoverage request.
200
     *
201
     */
202
    public void describeCoverage(){ 
203
        try {
204
            XMLNode node;
205
            if (working_offline) node = new XMLNode(file);
206
            else{
207
                URL url = new URL(construyeURL(working_address, operationDescribeCoverage.getParamsString()));
208
                fileDescribeCoverage = downloadFile(url, "wcs_DescribeCoverage");
209
                node = new XMLNode(fileDescribeCoverage);  
210
            } 
211
            describeCoverageResponse = new DescribeCoverageResponse(node, capabilities);
212
        } catch (MalformedURLException e){
213
            new Error("Bad URL");
214
        } catch (IOException e){
215
            new Error("Unable to retrieve coverage description, connection error.");
216
        } catch (Exception e){
217
            new Error();
218
        }            
219
    }
220
    /**
221
     * Unused
222
     * @deprecated
223
     *
224
     */
225
    public void _describeCoverage(){    
226
        try {
227
            XMLNode node;
228
            if (working_offline) node = new XMLNode(file);
229
            else{
230
                URL url = new URL(construyeURL(working_address, operationDescribeCoverage.getParamsString()));
231
                node = new XMLNode(url.openStream());  
232
            } 
233
            describeCoverageResponse = new DescribeCoverageResponse(node, capabilities);
234
        } catch (MalformedURLException e){
235
            new Error("Bad URL");
236
        } catch (IOException e){
237
            new Error("Unable to retrieve coverage description, connection error.");
238
        } catch (Exception e){
239
            new Error();
240
        }            
241
    }
242
    
243
    /**
244
     * Launches a coverage specific DescribeCoverage operation (unused in gvSIG)
245
     * 
246
     * @param coverage_name
247
     */
248
    public void describeCoverage(String coverage_name){
249
        try {
250
            operationDescribeCoverage.setParam("coverage", coverage_name);
251
            describeCoverage();
252
        } catch (Exception e){
253
            new Error("Fallo asignando valor al par?metro <coverage>");
254
        }
255
    }
256
    
257
    /**
258
     * Unused
259
     * @deprecated
260
     * @return
261
     * @throws ServerErrorResponseException
262
     */
263
    public boolean _getCoverage() throws ServerErrorResponseException{
264
        try {
265
            String s = construyeURL(working_address, operationGetCoverage.getParamsString());
266
            URL miurl = new URL(s);
267
            downloadFile(miurl, this.datapath);
268
            return (this.coveragefilename!=null);
269
        } catch (MalformedURLException e){
270
            new Error("WCS: GetCoverage> URL error.");
271
        } catch (IOException ioe){
272
                new Error("Unable to retrieve coverage.");
273
        }
274
        return false;
275
    }
276
    /**
277
     * Launches a GetCoverage exception. It downloads the coverage to a temporary
278
     * file. If the answer wasn't a coverage but was an error it throws an exception
279
     * 
280
     * @return the file downloaded
281
     * @throws ServerErrorResponseException
282
     */
283
    public File getCoverage() throws ServerErrorResponseException, IOException{
284
        try {
285
            String s = construyeURL(working_address, operationGetCoverage.getParamsString());
286
            URL miurl = new URL(s);
287
            
288
            File coverageFile = downloadFile(miurl, "wcs_getCoverage");
289
            boolean correcto = checkExceptionResponse(coverageFile);
290
            
291
            if (!correcto){
292
                    String message = parseException(coverageFile);
293
                    if (message!=null)
294
                            throw new ServerErrorResponseException(message);
295
                    else
296
                            throw new ServerErrorResponseException();
297
            }
298
            return coverageFile;
299
        } catch (MalformedURLException e){
300
            new Error("WCS: GetCoverage> URL error.");
301
        }/* catch (IOException ioe){
302
                new Error("Unable to retrieve coverage.");
303
        }*/
304
        return null;
305
    }
306
    
307
    /**
308
     * Gets an string containing the currently set parameters for the GetCoverage
309
     * request.
310
     * 
311
     * @return String
312
     */
313
    public String getCovergeParamString(){
314
            return operationGetCoverage.getParamsString();
315
    }
316
    
317
    /**
318
     * Gets an string containing the currently set parameters for the DescribeCoverage
319
     * request.
320
     * 
321
     * @return String
322
     */
323
    public String getDescribeCoverageParamString(){
324
            return operationDescribeCoverage.getParamsString();
325
    }
326
    
327
    /**
328
     * Sets the DescribeCoverage Operation parameters.
329
     * 
330
     * @param params
331
     * @return
332
     */
333
    public void setDescribeCoverageParams(String paramString){
334
            String[] params = paramString.split("&");
335
            operationDescribeCoverage.cleanParams();
336
            try{
337
                    for (int i = 0; i < params.length; i++) {
338
                            String[] par_nombreValor = params[i].split("="); 
339
                            //System.out.prinln(par_nombreValor[0]+"="+par_nombreValor[1]);)
340
                            operationDescribeCoverage.setParam(par_nombreValor[0],par_nombreValor[1]);
341
                    }
342
            } catch (Exception e){
343
                    e.printStackTrace();
344
            }
345
    }
346

    
347
    /**
348
     * Sets the GetCapabilities Operation parameters.
349
     * 
350
     * @param params
351
     * @return
352
     */
353
    public void setGetCapabilitiesParams(String paramString){
354
            String[] params = paramString.split("&");
355
            operationGetCapabilities.cleanParams();
356
            try{
357
                    for (int i = 0; i < params.length; i++) {
358
                            String[] par_nombrevalor = params[i].split("="); 
359
                            operationGetCapabilities.setParam(par_nombrevalor[0],par_nombrevalor[1]);
360
                    }
361
            } catch (Exception e){
362
                    e.printStackTrace();
363
            }
364
    }
365
    /**
366
     * Sets the GetCoverage Operation parameters.
367
     * 
368
     * @param params
369
     * @return
370
     */
371
    public void setGetCoverageParams(String paramString){
372
            String[] params = paramString.split("&");
373
            operationGetCoverage.cleanParams();
374
            try{
375
                    for (int i = 0; i < params.length; i++) {
376
                            String[] par_nombrevalor = params[i].split("=");
377
                            if (par_nombrevalor.length==2 && par_nombrevalor[0]!=null && par_nombrevalor[1]!=null)
378
                            operationGetCoverage.setParam(par_nombrevalor[0],par_nombrevalor[1]);
379
                            //System.out.println(par_nombrevalor[0]+par_nombrevalor[1]);
380
                    }
381
            } catch (Exception e){
382
                    e.printStackTrace();
383
            }
384
    }
385
    
386
    /**
387
     * Downloads an URL into a temporary file that is removed the next time the 
388
     * tempFileManager class is called, which means the next time gvSIG is launched.
389
     * 
390
     * @param url
391
     * @param name
392
     * @return
393
     * @throws IOException
394
     * @throws ServerErrorResponseException
395
     * @throws ConnectException
396
     * @throws UnknownHostException
397
     */
398
    public File downloadFile(URL url, String name) throws IOException, ServerErrorResponseException, ConnectException, UnknownHostException{
399
            File f = null;
400
            try{
401
                    f = TempFileManager.createTempFile(name, "tmp");
402
                    System.out.println("downloading '"+url.toString()+"' to: "+f.getAbsolutePath());
403
                         
404
                    f.deleteOnExit();
405
                    
406
            } catch (IOException io) {
407
                    io.printStackTrace();
408
            }
409
            DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)));
410
            byte[] buffer = new byte[1024*256];
411
            InputStream is = url.openStream();
412
            long readed = 0;
413
            for (int i = is.read(buffer); i>0; i = is.read(buffer)){
414
                    dos.write(buffer, 0, i);
415
                    readed += i;
416
            }
417
            dos.close();
418
            /*if (!isNotAnException(f))
419
                    // SI que es una excepci?n
420
                    throw new ServerErrorResponseException();*/
421
            return f;
422
        }
423

    
424
    /**
425
     * @deprecated
426
     * @param url
427
     * @param targetdir
428
     */
429
    public void _downloadFile(URL url, String targetdir){
430
        try{
431
            String path = this.getDataPath();
432
            String filename = this.getCoverageFileName()+this.getCoverageFileExtension();
433
            String where = path+filename;
434
            DataOutputStream dos = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(where)));
435
            byte[] buffer = new byte[1024*256]; // 256KB
436
            InputStream is = url.openStream();
437
            long readed = 0;
438
            for (int i = is.read(buffer); i>0; i = is.read(buffer)){
439
                dos.write(buffer, 0, i);
440
                readed += i;
441
            }
442
            dos.close();
443
       
444
            
445
        } catch (IOException ie){
446
            new Error("La petici?n de la cobertura no tuvo ?xito.");
447
        }
448
        
449
    }
450
 
451
    /**
452
     * Gets the current working address.
453
     * 
454
     * @return
455
     */
456
    public String getWorkingAddress(){
457
        return working_address;
458
    }
459
    
460
    /**
461
     * Unused in gvSIG
462
     * @return
463
     */
464
    public String getDataPath(){
465
        return this.datapath;
466
    }
467
    
468
    /**
469
     * Unused in gvSIG
470
     */
471
    public String getCoverageFileName(){
472
        return this.coveragefilename;
473
    }
474
    
475
    /**
476
     * Unused in gvSIG
477
     */
478
   public String getCoverageFileExtension(){
479
        return this.coveragefileextension;
480
    }
481
    
482
   /**
483
    * Typical toString funtion.
484
    */
485
    public String toString(){
486
        return capabilities.toString();
487
    }
488
    
489
    /**
490
     * Unused in gvSIG
491
     */
492
    public void setBaseDirectory(String path){
493
        this.path = path;
494
        this.datapath = this.path+"/data/";
495
        
496
    }
497
    
498
    /**
499
     * Unused in gvSIG
500
     */
501
    public void setCoverageFileName(String name){
502
        this.coveragefilename = name;
503
    }
504

    
505
    /**
506
     * Unused in gvSIG
507
     */
508
    public void setCoverageFileExtension(String extension){
509
        this.coveragefileextension = "."+extension;
510
    }
511
    /**
512
     * Its use is unrecommended, use checkExceptionResponse and parseException
513
     * 
514
     * Su uso no est? recomendado, usar checkExceptionResponse y parseException
515
     * @deprecated
516
     * @param file
517
     * @return
518
     */
519
    public boolean isNotAnException(File file){
520
            if (file == null)
521
                    return false;
522
            
523
        this.wcs_exception = new WCSExceptionResponse(file);
524
        return (this.wcs_exception.getText() == null);
525
    }
526
    
527
    /**
528
     * Unused in gvSIG
529
     */
530
    public String getWCSException(){
531
        return this.wcs_exception.getText();
532
    }
533
    
534
    /**
535
     * Checks the server's answer.
536
     * TODO figure a good criteria out to catch every kind of error.
537
     * 
538
     * Comprueba si la respuesta ha sido un error o era lo que se
539
     * esperaba. (Versi?n en pruebas)
540
     * 
541
     * @param file
542
     * @return true si est? todo bien, false si hay errores.
543
     */
544
    private boolean checkExceptionResponse(File file){
545
            // TODO Aix? va b? si la resposta ?s un XML de WCS, per? tamb? s'ha de 
546
            // considerar si ?s alguna resposta d'error d'Apache o algo per l'estil
547
            
548
            // Un possible criteri ?s veure el tamany del fitxer, establim un l?mit de
549
            // fitxer a analitzar (umbral) i comprovem que el que s'analitza ?s text o
550
            // s?n dades binaries. Si ?s text, llavors no ?s una imatge i es tracta com
551
            // a error.
552
            wcs_exception = null;
553
            int umbral = 1024; 
554
            try {
555
                    FileReader fr = new FileReader(file);
556
                    for (int i = 0; i < umbral; i++) {
557
                            int c = fr.read();
558
                            if (c==-1){
559
                                    // End of file. If we reach this
560
                                    // everything before is printable data.
561
                                    return false;
562
                            } else {
563
                                    char ch = (char) c;
564
                                    if (characters.indexOf(ch)==-1){
565
                                            // We've found a non-printable character.
566
                                            // Then we'll assume that this file is binary.
567
                                            return true;
568
                                    }
569
                            }
570
                    }
571
            } catch (FileNotFoundException e) {
572
                    e.printStackTrace();
573
            } catch (IOException e) {
574
                        e.printStackTrace();
575
                }
576
            return false;
577
 }
578
    
579
    /**
580
     * Parses the OGC Exception XML documents and extracts the error message.
581
     * 
582
     * @param f
583
     * @return String containing the error message.
584
     */
585
    private String parseException(File f){
586
            wcs_exception = new WCSExceptionResponse(f);
587
            return wcs_exception.getText();
588
    }
589
    
590
}
591

    
592