Statistics
| Revision:

root / trunk / extensions / extWCS / src / es / uji / lsi / wcs / client / WCSClient.java @ 3414

History | View | Annotate | Download (17.4 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{
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
                            operationGetCoverage.setParam(par_nombrevalor[0],par_nombrevalor[1]);
378
                            //System.out.println(par_nombrevalor[0]+par_nombrevalor[1]);
379
                    }
380
            } catch (Exception e){
381
                    e.printStackTrace();
382
            }
383
    }
384
    
385
    /**
386
     * Downloads an URL into a temporary file that is removed the next time the 
387
     * tempFileManager class is called, which means the next time gvSIG is launched.
388
     * 
389
     * @param url
390
     * @param name
391
     * @return
392
     * @throws IOException
393
     * @throws ServerErrorResponseException
394
     * @throws ConnectException
395
     * @throws UnknownHostException
396
     */
397
    public File downloadFile(URL url, String name) throws IOException, ServerErrorResponseException, ConnectException, UnknownHostException{
398
            File f = null;
399
            try{
400
                    f = TempFileManager.createTempFile(name, "tmp");
401
                    System.out.println("downloading '"+url.toString()+"' to: "+f.getAbsolutePath());
402
                         
403
                    f.deleteOnExit();
404
                    
405
            } catch (IOException io) {
406
                    io.printStackTrace();
407
            }
408
            DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f)));
409
            byte[] buffer = new byte[1024*256];
410
            InputStream is = url.openStream();
411
            long readed = 0;
412
            for (int i = is.read(buffer); i>0; i = is.read(buffer)){
413
                    dos.write(buffer, 0, i);
414
                    readed += i;
415
            }
416
            dos.close();
417
            /*if (!isNotAnException(f))
418
                    // SI que es una excepci?n
419
                    throw new ServerErrorResponseException();*/
420
            return f;
421
        }
422

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

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

    
591