Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: jones $'
7
 *     '$Date: 2006-04-14 16:39:52 -0700 (Fri, 14 Apr 2006) $'
8
 * '$Revision: 2986 $'
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 2 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
 */
24

    
25
package edu.ucsb.nceas.metacat.client;
26

    
27
import java.io.BufferedReader;
28
import java.io.InputStream;
29
import java.io.InputStreamReader;
30
import java.io.PushbackReader;
31
import java.io.StringReader;
32
import java.io.IOException;
33
import java.io.StringWriter;
34
import java.io.Reader;
35
import java.net.URL;
36
import java.util.Properties;
37

    
38
import org.w3c.dom.Node;
39

    
40
import edu.ucsb.nceas.utilities.HttpMessage;
41
import edu.ucsb.nceas.utilities.IOUtil;
42
import edu.ucsb.nceas.utilities.XMLUtilities;
43
import java.io.File;
44

    
45

    
46
/**
47
 *  This interface provides methods for initializing and logging in to a
48
 *  Metacat server, and then querying, reading, transforming, inserting,
49
 *  updating and deleting documents from that server.
50
 */
51
public class MetacatClient implements Metacat
52
{
53
    /** The URL string for the metacat server */
54
    private String metacatUrl;
55

    
56
    /** The session identifier for the session */
57
    private String sessionId;
58

    
59
    /**
60
     * Constructor to create a new instance. Protected because instances
61
     * should only be created by the factory MetacatFactory.
62
     */
63
    protected MetacatClient()
64
    {
65
        this.metacatUrl = null;
66
        this.sessionId = null;
67
    }
68

    
69
    /**
70
     *  Method used to log in to a metacat server. Implementations will need
71
     *  to cache a cookie value to make the session persistent.  Each time a
72
     *  call is made to one of the other methods (e.g., read), the cookie will
73
     *  need to be passed back to the metacat server along with the request.
74
     *
75
     *  @param username   the username of the user, like an LDAP DN
76
     *  @param password   the password for that user for authentication
77
     *  @return the response string from metacat in XML format
78
     *  @throws MetacatAuthException when the username/password could
79
     *                    not be authenticated
80
     */
81
    public String login(String username, String password)
82
           throws MetacatAuthException, MetacatInaccessibleException
83
    {
84
        Properties prop = new Properties();
85
        prop.put("action", "login");
86
        prop.put("qformat", "xml");
87
        prop.put("username", username);
88
        prop.put("password", password);
89

    
90
        String response = null;
91
        try {
92
            response = sendDataForString(prop, null, null, 0);
93
        } catch (Exception e) {
94
            throw new MetacatInaccessibleException(e.getMessage());
95
        }
96

    
97
        if (response.indexOf("<login>") == -1) {
98
            setSessionId("");
99
            throw new MetacatAuthException(response);
100
        } else {
101
            int start = response.indexOf("<sessionId>") + 11;
102
            int end = response.indexOf("</sessionId>");
103
            if ((start != -1) && (end != -1)) {
104
                setSessionId(response.substring(start,end));
105
            }
106
        }
107
        return response;
108
    }
109
    
110
    /**
111
     *  Method used to log in to a metacat server. Implementations will need
112
     *  to cache a cookie value to make the session persistent.  Each time a
113
     *  call is made to one of the other methods (e.g., read), the cookie will
114
     *  need to be passed back to the metacat server along with the request.
115
     *
116
     *  @param username   the username of the user, like an LDAP DN
117
     *  @param password   the password for that user for authentication
118
     *  @return the response string from metacat in XML format
119
     *  @throws MetacatAuthException when the username/password could
120
     *                    not be authenticated
121
     */
122
    public String getloggedinuserinfo() throws MetacatInaccessibleException
123
    {
124
        Properties prop = new Properties();
125
        prop.put("action", "getloggedinuserinfo");
126
        prop.put("qformat", "xml");
127

    
128
        String response = null;
129
        try {
130
            response = sendDataForString(prop, null, null, 0);
131
        } catch (Exception e) {
132
            throw new MetacatInaccessibleException(e.getMessage());
133
        }
134

    
135
        return response;
136
    }
137

    
138
    /**
139
     *  Method used to log out a metacat server. The Metacat server will end
140
     *  the session when this call is invoked.
141
     *
142
     *  @return the response string from metacat in XML format
143
     *  @throws MetacatInaccessibleException when the metacat server can not be
144
     *                                    reached or does not respond
145
     */
146
    public String logout() throws MetacatInaccessibleException, MetacatException
147
    {
148
        Properties prop = new Properties();
149
        prop.put("action", "logout");
150
        prop.put("qformat", "xml");
151

    
152
        String response = null;
153
        try {
154
            response = sendDataForString(prop, null, null, 0);
155
        } catch (Exception e) {
156
            throw new MetacatInaccessibleException(e.getMessage());
157
        }
158

    
159
        if (response.indexOf("<logout>") == -1) {
160
            throw new MetacatException(response);
161
        }
162
        setSessionId("");
163
        return response;
164
    }
165

    
166
    /**
167
     * Read an XML document from the metacat server session, accessed by docid,
168
     * and returned as a Reader.
169
     *
170
     * @param docid the identifier of the document to be read
171
     * @return a Reader for accessing the document
172
     * @throws InsufficientKarmaException when the user has insufficent rights
173
     *                                    for the operation
174
     * @throws MetacatInaccessibleException when the metacat server can not be
175
     *                                    reached or does not respond
176
     * @throws MetacatException when the metacat server generates another error
177
     */
178
    public Reader read(String docid) throws InsufficientKarmaException,
179
        MetacatInaccessibleException, MetacatException
180
    {
181
        PushbackReader pbr = null;
182

    
183
        Properties prop = new Properties();
184
        prop.put("action", "read");
185
        prop.put("qformat", "xml");
186
        prop.put("docid", docid);
187

    
188
        InputStream response = null;
189
        try {
190
            response = sendData(prop, null, null, 0);
191
        } catch (Exception e) {
192
            throw new MetacatInaccessibleException(e.getMessage());
193
        }
194

    
195
        pbr = new PushbackReader(new InputStreamReader(response), 512);
196
        try {
197
            char[] characters = new char[512];
198
            int len = pbr.read(characters, 0, 512);
199
            StringWriter sw = new StringWriter();
200
            sw.write(characters, 0, len);
201
            String message = sw.toString();
202
            sw.close();
203
            pbr.unread(characters, 0, len);
204

    
205
            if (message.indexOf("<error>") != -1) {
206
                if (message.indexOf("does not have permission") != -1) {
207
                    throw new InsufficientKarmaException(message);
208
                } else {
209
                    throw new MetacatException(message);
210
                }
211
            }
212
        } catch (IOException ioe) {
213
            throw new MetacatException(
214
                    "MetacatClient: Error converting Reader to String."
215
                    + ioe.getMessage());
216
        }
217

    
218
        return pbr;
219
    }
220

    
221

    
222
    /**
223
        * Read inline data from the metacat server session, accessed by
224
        * inlinedataid and returned as a Reader.
225
        *
226
        * @param inlinedataid the identifier of the data to be read
227
        * @return a Reader for accessing the document
228
        * @throws InsufficientKarmaException when the user has insufficent rights
229
        *                                    for the operation
230
        * @throws MetacatInaccessibleException when the metacat server can not be
231
        *                                    reached or does not respond
232
        * @throws MetacatException when the metacat server generates another error
233
        */
234
       public Reader readInlineData(String inlinedataid)
235
           throws InsufficientKarmaException,
236
           MetacatInaccessibleException, MetacatException
237
       {
238
           PushbackReader pbr = null;
239

    
240
           Properties prop = new Properties();
241
           prop.put("action", "readinlinedata");
242
           prop.put("inlinedataid", inlinedataid);
243

    
244
           InputStream response = null;
245
           try {
246
               response = sendData(prop, null, null, 0);
247
           } catch (Exception e) {
248
               throw new MetacatInaccessibleException(e.getMessage());
249
           }
250

    
251
           pbr = new PushbackReader(new InputStreamReader(response), 512);
252
           try {
253
               char[] characters = new char[512];
254
               int len = pbr.read(characters, 0, 512);
255
               StringWriter sw = new StringWriter();
256
               sw.write(characters, 0, len);
257
               String message = sw.toString();
258
               sw.close();
259
               pbr.unread(characters, 0, len);
260

    
261
               if (message.indexOf("<error>") != -1) {
262
                   if (message.indexOf("does not have permission") != -1) {
263
                       throw new InsufficientKarmaException(message);
264
                   } else {
265
                       throw new MetacatException(message);
266
                   }
267
               }
268
           } catch (IOException ioe) {
269
               throw new MetacatException(
270
                       "MetacatClient: Error converting Reader to String."
271
                       + ioe.getMessage());
272
           }
273

    
274
           return pbr;
275
       }
276

    
277
    /**
278
     * Query the metacat document store with the given metacat-compatible
279
     * query document, and return the result set as a Reader.
280
     *
281
     * @param xmlQuery a Reader for accessing the XML version of the query
282
     * @return a Reader for accessing the result set
283
     */
284
    public Reader query(Reader xmlQuery) throws MetacatInaccessibleException,
285
                                                IOException
286
    {
287
        Reader reader = null;
288
        String query = null;
289
        try {
290
          query = IOUtil.getAsString(xmlQuery, true);
291
        } catch (IOException ioE) {
292
          throw ioE;
293
        }
294

    
295
        //set up properties
296
        Properties prop = new Properties();
297
        prop.put("action", "squery");
298
        prop.put("qformat", "xml");
299
        prop.put("query", query);
300

    
301
        InputStream response = null;
302
        try {
303
            response = sendData(prop, null, null, 0);
304
        } catch (Exception e) {
305
            throw new MetacatInaccessibleException(e.getMessage());
306
        }
307
        reader = new InputStreamReader(response);
308
        return reader;
309
    }
310

    
311
    /**
312
     * Insert an XML document into the repository.
313
     *
314
     * @param docid the docid to insert the document
315
     * @param xmlDocument a Reader for accessing the XML document to be inserted
316
     * @param schema a Reader for accessing the DTD or XML Schema for
317
     *               the document
318
     * @return the metacat response message
319
     * @throws InsufficientKarmaException when the user has insufficent rights
320
     *                                    for the operation
321
     * @throws MetacatInaccessibleException when the metacat server can not be
322
     *                                    reached or does not respond
323
     * @throws MetacatException when the metacat server generates another error
324
     * @throws IOException when there is an error reading the xml document
325
     */
326
    public String insert(String docid, Reader xmlDocument, Reader schema)
327
        throws InsufficientKarmaException, MetacatException, IOException,
328
        MetacatInaccessibleException
329
    {
330
        Reader reader = null;
331
        String doctext = null;
332
        String schematext = null;
333
        try {
334
          doctext = IOUtil.getAsString(xmlDocument, true);
335
          if (schema != null) {
336
              schematext = IOUtil.getAsString(schema, true);
337
          }
338
        } catch (IOException ioE) {
339
          throw ioE;
340
        }
341

    
342
        //set up properties
343
        Properties prop = new Properties();
344
        prop.put("action", "insert");
345
        prop.put("docid", docid);
346
        prop.put("doctext", doctext);
347
        if (schematext != null) {
348
            prop.put("dtdtext", schematext);
349
        }
350

    
351
        String response = null;
352
        try {
353
            response = sendDataForString(prop, null, null, 0);
354
        } catch (Exception e) {
355
            throw new MetacatInaccessibleException(e.getMessage());
356
        }
357

    
358
        // Check for an error condition
359
        if (response.indexOf("<error>") != -1) {
360
            if (response.indexOf("does not have permission") != -1) {
361
                throw new InsufficientKarmaException(response);
362
            } else {
363
                throw new MetacatException(response);
364
            }
365
        }
366

    
367
        return response;
368
    }
369

    
370
    /**
371
     * Update an XML document in the repository.
372
     *
373
     * @param docid the docid to update
374
     * @param xmlDocument a Reader for accessing the XML text to be updated
375
     * @param schema a Reader for accessing the DTD or XML Schema for
376
     *               the document
377
     * @return the metacat response message
378
     * @throws InsufficientKarmaException when the user has insufficent rights
379
     *                                    for the operation
380
     * @throws MetacatInaccessibleException when the metacat server can not be
381
     *                                    reached or does not respond
382
     * @throws MetacatException when the metacat server generates another error
383
     * @throws IOException when there is an error reading the xml document
384
     */
385
    public String update(String docid, Reader xmlDocument, Reader schema)
386
        throws InsufficientKarmaException, MetacatException, IOException,
387
        MetacatInaccessibleException
388
    {
389
        Reader reader = null;
390
        String doctext = null;
391
        String schematext = null;
392
        try {
393
          doctext = IOUtil.getAsString(xmlDocument, true);
394
          if (schema != null) {
395
              schematext = IOUtil.getAsString(schema, true);
396
          }
397
        } catch (IOException ioE) {
398
          throw ioE;
399
        }
400

    
401
        //set up properties
402
        Properties prop = new Properties();
403
        prop.put("action", "update");
404
        prop.put("docid", docid);
405
        prop.put("doctext", doctext);
406
        if (schematext != null) {
407
            prop.put("dtdtext", schematext);
408
        }
409

    
410
        String response = null;
411
        try {
412
            response = sendDataForString(prop, null, null, 0);
413
        } catch (Exception e) {
414
            throw new MetacatInaccessibleException(e.getMessage());
415
        }
416

    
417
        // Check for an error condition
418
        if (response.indexOf("<error>") != -1) {
419
            if (response.indexOf("does not have permission") != -1) {
420
                throw new InsufficientKarmaException(response);
421
            } else {
422
                throw new MetacatException(response);
423
            }
424
        }
425

    
426
        return response;
427
    }
428

    
429
    /**
430
       * Upload a data document into the repository.
431
       *
432
       * @param docid the docid to insert the document
433
       * @param document a Reader for accessing the document to be uploaded
434
       * @return the metacat response message
435
       * @throws InsufficientKarmaException when the user has insufficent rights
436
       *                                    for the operation
437
       * @throws MetacatInaccessibleException when the metacat server can not be
438
       *                                    reached or does not respond
439
       * @throws MetacatException when the metacat server generates another error
440
       * @throws IOException when there is an error reading the xml document
441
       */
442
      public String upload(String docid, File file)
443
          throws InsufficientKarmaException, MetacatException, IOException,
444
          MetacatInaccessibleException
445
      {
446

    
447
          URL url = new URL(metacatUrl.trim());
448
          HttpMessage msg = new HttpMessage(url);
449
          //set up properties
450
          Properties arg = new Properties();
451
          arg.put("action", "upload");
452
          arg.put("docid", docid);
453

    
454
          Properties filenames = new Properties();
455
          String filename = file.getAbsolutePath();
456
          filenames.put("datafile", filename);
457

    
458
          String response = null;
459
          try {
460
            response = sendDataForString(arg, filenames, null, 0);
461
          } catch (Exception e) {
462
            throw new MetacatInaccessibleException(e.getMessage());
463
          }
464

    
465
          // Check for an error condition
466
          if (response.indexOf("<error>") != -1) {
467
            if (response.indexOf("does not have permission") != -1) {
468
              throw new InsufficientKarmaException(response);
469
            } else {
470
              throw new MetacatException(response);
471
            }
472
          }
473

    
474
          return response;
475
      }
476

    
477
        /**
478
          * Upload a data document into the repository.
479
          *
480
          * @param docid the docid to insert the document
481
          * @param document a Reader for accessing the document to be uploaded
482
          * @return the metacat response message
483
          * @throws InsufficientKarmaException when the user has insufficent rights
484
          *                                    for the operation
485
          * @throws MetacatInaccessibleException when the metacat server can not be
486
          *                                    reached or does not respond
487
          * @throws MetacatException when the metacat server generates another error
488
          * @throws IOException when there is an error reading the xml document
489
          */
490

    
491

    
492
      public String upload(String docid, String filename, InputStream fileData,
493
                           int size)
494
          throws InsufficientKarmaException, MetacatException, IOException,
495
          MetacatInaccessibleException {
496

    
497
          URL url = new URL(metacatUrl.trim());
498
          HttpMessage msg = new HttpMessage(url);
499
          //set up properties
500
          Properties arg = new Properties();
501
          arg.put("action", "upload");
502
          arg.put("docid", docid);
503

    
504
          Properties filenames = new Properties();
505
          filenames.put("datafile", filename);
506

    
507
          String response = null;
508
          try {
509
            response = sendDataForString(arg, filenames, fileData, size);
510
          } catch (Exception e) {
511
            throw new MetacatInaccessibleException(e.getMessage());
512
          }
513

    
514
          // Check for an error condition
515
          if (response.indexOf("<error>") != -1) {
516
            if (response.indexOf("does not have permission") != -1) {
517
              throw new InsufficientKarmaException(response);
518
            } else {
519
              throw new MetacatException(response);
520
            }
521
          }
522

    
523
          return response;
524
      }
525

    
526
    /**
527
     * Delete an XML document in the repository.
528
     *
529
     * @param docid the docid to delete
530
     * @return the metacat response message
531
     * @throws InsufficientKarmaException when the user has insufficent rights
532
     *                                    for the operation
533
     * @throws MetacatInaccessibleException when the metacat server can not be
534
     *                                    reached or does not respond
535
     * @throws MetacatException when the metacat server generates another error
536
     */
537
    public String delete(String docid)
538
        throws InsufficientKarmaException, MetacatException,
539
        MetacatInaccessibleException
540
    {
541
        //set up properties
542
        Properties prop = new Properties();
543
        prop.put("action", "delete");
544
        prop.put("docid", docid);
545

    
546
        String response = null;
547
        try {
548
            response = sendDataForString(prop, null, null, 0);
549
        } catch (Exception e) {
550
            throw new MetacatInaccessibleException(e.getMessage());
551
        }
552

    
553
        // Check for an error condition
554
        if (response.indexOf("<error>") != -1) {
555
            if (response.indexOf("does not have permission") != -1) {
556
                throw new InsufficientKarmaException(response);
557
            } else {
558
                throw new MetacatException(response);
559
            }
560
        }
561
        return response;
562
    }
563

    
564

    
565
    /**
566
     * set the access on an XML document in the repository.
567
     *
568
     * @param _docid the docid of the document for which the access should be applied.
569
     *
570
     * @param _principal the document's principal
571
     *
572
     * @param _permission the access permission to be applied to the docid
573
     *  {e.g. read,write,all}
574
     *
575
     * @param _permType the permission type to be applied to the document
576
     *  {e.g. allow or deny}
577
     *
578
     * @param _permOrder the order that the document's permissions should be
579
     *  processed {e.g. denyFirst or allowFirst}
580
     *
581
     *
582
     * @return the metacat response message
583
     *
584
     * @throws InsufficientKarmaException when the user has insufficent rights
585
     *                                    for the operation
586
     * @throws MetacatInaccessibleException when the metacat server can not be
587
     *                                    reached or does not respond
588
     * @throws MetacatException when the metacat server generates another error
589
     */
590
    public String setAccess(String _docid, String _principal, String
591
                            _permission, String _permType, 
592
                            String _permOrder )
593
        throws InsufficientKarmaException, MetacatException,
594
        MetacatInaccessibleException
595
    {  
596
        //set up properties
597
        Properties prop = new Properties();
598
        prop.put("action", "setaccess");
599
        prop.put("docid", _docid);
600
        prop.put("principal", _principal);
601
        prop.put("permission", _permission);
602
        prop.put("permType", _permType);
603
        prop.put("permOrder", _permOrder);
604

    
605
        String response = null;
606
        try {
607
            response = sendDataForString(prop, null, null, 0);
608
        } catch (Exception e) {
609
            throw new MetacatInaccessibleException(e.getMessage());
610
        }
611

    
612
        // Check for an error condition
613
        if (response.indexOf("<error>") != -1) {
614
            if (response.indexOf("does not have permission") != -1) {
615
                throw new InsufficientKarmaException(response);
616
            } else {
617
                throw new MetacatException(response);
618
            }
619
        }
620
        return response;
621
    }
622

    
623
    /**
624
     * When the MetacatFactory creates an instance it needs to set the
625
     * MetacatUrl to which connections should be made.
626
     *
627
     * @param metacatUrl the URL for the metacat server
628
     */
629
    public void setMetacatUrl(String metacatUrl)
630
    {
631
        this.metacatUrl = metacatUrl;
632
    }
633

    
634
    /**
635
     * Get the session identifier for this session.  This is only valid if
636
     * the login methods has been called successfully for this Metacat object
637
     * beforehand.
638
     *
639
     * @returns the sessionId as a String, or null if the session is invalid
640
     */
641
    public String getSessionId()
642
    {
643
        return this.sessionId;
644
    }
645

    
646
    /**
647
     * Set the session identifier for this session.  This identifier was
648
     * previously established with a call to login.  To continue to use the
649
     * same session, set the session id before making a call to one of the
650
     * metacat access methods (e.g., read, query, insert, etc.).
651
     *
652
     * @param String the sessionId from a previously established session
653
     */
654
    public void setSessionId(String sessionId)
655
    {
656
        this.sessionId = sessionId;
657
    }
658
    
659
    /**
660
     * The method will return the latest revision in metacat server 
661
     * for a given document id. If some error happens, this method will throw
662
     * an exception.   
663
     * @param docId String  the given docid you want to use. the docid it self
664
     *                      can have or haven't revision number
665
     * @throws MetacatException
666
     */
667
     public int getNewestDocRevision(String docId) throws MetacatException
668
     {
669
         int rev = 0;
670
         //set up properties
671
         Properties prop = new Properties();
672
         prop.put("action", "getrevisionanddoctype");
673
         prop.put("docid", docId);
674
         
675
         String response = null;
676
         try {
677
             response = sendDataForString(prop, null, null, 0);
678
             String revStr = parserRevisionResponse(response);
679
             Integer revObj = new Integer(revStr);
680
             rev = revObj.intValue();
681
             // Check for an error condition
682
             if (response.indexOf("<error>") != -1) {
683
                 throw new MetacatException(response);
684
             }
685
         } catch (Exception e) {
686
             throw new MetacatException(e.getMessage());
687
         }
688
         return rev;
689
     }
690

    
691
    /**
692
     * Return the highest document id for a given scope.  This is used by
693
     * clients to make it easier to determine the next free identifier in a
694
     * sequence for a given scope.  
695
     * @param scope String  the scope to use for looking up the latest id
696
     * @throws MetacatException when an error occurs
697
     */
698
    public String getLastDocid(String scope) throws MetacatException {
699
        String lastIdentifier = "";
700
        //set up properties
701
        Properties prop = new Properties();
702
        prop.put("action", "getlastdocid");
703
        prop.put("scope", scope);
704
         
705
        String response = null;
706
        try {
707
            response = sendDataForString(prop, null, null, 0);
708
            // Check for an error condition
709
            if (response.indexOf("<error>") != -1) {
710
               throw new MetacatException(response);
711
            } else {
712
                Reader responseReader = new StringReader(response);
713
                Node root = 
714
                    XMLUtilities.getXMLReaderAsDOMTreeRootNode(responseReader); 
715
                Node docidNode = 
716
                    XMLUtilities.getNodeWithXPath(root, "/lastDocid/docid");
717
                lastIdentifier = docidNode.getFirstChild().getNodeValue();
718
            }
719
        } catch (Exception e) {
720
            throw new MetacatException(e.getMessage());
721
        }
722
        return lastIdentifier;
723
    }
724

    
725
    /************************************************************************
726
     * PRIVATE METHODS
727
     ************************************************************************/
728

    
729
    /**
730
     * Send a request to metacat.
731
     *
732
     * @param prop the properties to be URL encoded and sent
733
     * @param filename  the properties to be sent to Metacat
734
     *                  in case of upload, otherwise null
735
     * @param fileData  the inputStream for the file data to be sent to Metacat
736
     *                  in case of upload, otherwise null
737
     * @param size      the size of the data being sent to Metacat
738
     *                  in case of upload, otherwise 0
739
     */
740
    synchronized private InputStream sendDataOnce(Properties args,
741
                                                  Properties filename,
742
                                                  InputStream fileData,
743
                                                  int size)
744
        throws Exception
745
    {
746
        InputStream returnStream = null;
747
        URL url = new URL(metacatUrl);
748
        HttpMessage msg = new HttpMessage(url);
749
        msg.setCookie("JSESSIONID="+this.sessionId);
750
        if (filename == null){
751
            returnStream = msg.sendPostData(args);
752
        } else if (fileData == null){
753
            returnStream = msg.sendPostData(args, filename);
754
        } else if (size > 0) {
755
            returnStream = msg.sendPostData(args, filename, fileData, size);
756
        } else {
757
            throw new MetacatException("Invalid size specified for " +
758
                                       "the input stream being passed");
759
        }
760
        return returnStream;
761
    }
762

    
763
    /**
764
     * Send a request to Metacat
765
     *
766
     * @param args  the properties to be sent to Metacat
767
     * @param filename  the properties to be sent to Metacat
768
     *                  in case of upload, otherwise null
769
     * @param fileData  the inputStream for the file data to be sent to Metacat
770
     *                  in case of upload, otherwise null
771
     * @param size      the size of the data being sent to Metacat
772
     *                  in case of upload, otherwise 0
773
     * @return      InputStream as returned by Metacat
774
     */
775
    synchronized private InputStream sendData(Properties args,
776
                                              Properties filename,
777
                                              InputStream fileData,
778
                                              int size)
779
        throws Exception
780
    {
781
        InputStream returnStream = null;
782

    
783
        /*
784
            Note:  The reason that there are three try statements all executing
785
            the same code is that there is a problem with the initial connection
786
            using the HTTPClient protocol handler.  These try statements make
787
            sure that a connection is made because it gives each connection a
788
            2nd and 3rd chance to work before throwing an error.
789
            THIS IS A TOTAL HACK.  THIS NEEDS TO BE LOOKED INTO AFTER THE BETA1
790
            RELEASE OF MORPHO!!!  cwb (7/24/01)
791
          */
792
        try {
793
           return sendDataOnce(args, filename, fileData, size);
794
        } catch (Exception e) {
795
            try {
796
                return sendDataOnce(args, filename, fileData, size);
797
            } catch (Exception e2) {
798
                try {
799
                    return sendDataOnce(args, filename, fileData, size);
800
                } catch (Exception e3) {
801
                    System.err.println(
802
                            "Failed to send data to metacat 3 times.");
803
                    throw e3;
804
                }
805
            }
806
        }
807
    }
808

    
809
    /**
810
     * Send a request to Metacat
811
     *
812
     * @param args      the properties to be sent to Metacat
813
     * @param filename  the properties to be sent to Metacat
814
     *                  in case of upload, otherwise null
815
     * @param fileData  the inputStream for the file data to be sent to Metacat
816
     *                  in case of upload, otherwise null
817
     * @param size      the size of the data being sent to Metacat
818
     *                  in case of upload, otherwise 0
819
     * @return          a string as returned by Metacat
820
     */
821
    synchronized private String sendDataForString(Properties args,
822
                                                  Properties filename,
823
                                                  InputStream fileData,
824
                                                  int size)
825
        throws Exception
826
    {
827
        String response = null;
828

    
829
        try {
830
            InputStreamReader returnStream =
831
                    new InputStreamReader(sendData(args, filename,
832
                                                   fileData, size));
833
            StringWriter sw = new StringWriter();
834
            int len;
835
            char[] characters = new char[512];
836
            while ((len = returnStream.read(characters, 0, 512)) != -1) {
837
                sw.write(characters, 0, len);
838
            }
839
            returnStream.close();
840
            response = sw.toString();
841
            sw.close();
842
        } catch (Exception e) {
843
            throw e;
844
        }
845
        return response;
846
    }
847
    
848
    /*
849
     * "getversionanddoctype" action will return a string from metacat server.
850
     * The string format is "revision;doctype"(This is bad idea, we should use xml)
851
     * This method will get revision string from the response string
852
     */
853
    private String parserRevisionResponse(String response) throws Exception
854
    {
855
      String revision = null;
856
      if (response != null)
857
      {
858
        int firstSemiCol = response.indexOf(";");
859
        revision = response.substring(0, firstSemiCol);
860
      }
861
      return revision;
862
    }
863
}
(4-4/7)