Project

General

Profile

« Previous | Next » 

Revision 3285

Added by barteau over 17 years ago

Metacat JSP API Additions. The new methods currently only handle inserts of new metadata files and related data files. It also handles instance creation and login support, with
a few convenience methodes intended to be called by a JSP file.
Update and delete support will be added. Also, the new methods currently only handle FGDC metadata files. More XML grammars will be added.

View differences:

src/edu/ucsb/nceas/metacat/client/MetacatClient.java
24 24

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

  
27
import com.oreilly.servlet.multipart.FilePart;
28
import com.oreilly.servlet.multipart.MultipartParser;
29
import com.oreilly.servlet.multipart.ParamPart;
30
import com.oreilly.servlet.multipart.Part;
31
import edu.ucsb.nceas.metacat.MetaCatUtil;
32
import java.io.BufferedInputStream;
27 33
import java.io.BufferedReader;
28 34
import java.io.InputStream;
29 35
import java.io.InputStreamReader;
......
33 39
import java.io.StringWriter;
34 40
import java.io.Reader;
35 41
import java.net.URL;
42
import java.util.HashMap;
43
import java.util.Iterator;
36 44
import java.util.Properties;
37 45
import java.util.Vector;
46
import javax.xml.xpath.XPath;
47
import javax.xml.xpath.XPathFactory;
48
import org.w3c.dom.Document;
49
import org.w3c.dom.DocumentType;
50
import org.w3c.dom.Element;
38 51

  
39 52
import org.w3c.dom.Node;
40 53
import org.w3c.dom.NodeList;
......
43 56
import edu.ucsb.nceas.utilities.IOUtil;
44 57
import edu.ucsb.nceas.utilities.XMLUtilities;
45 58
import java.io.File;
59
import javax.xml.xpath.XPathConstants;
60
import javax.xml.xpath.XPathExpressionException;
46 61

  
47 62

  
48 63
/**
......
50 65
 *  Metacat server, and then querying, reading, transforming, inserting,
51 66
 *  updating and deleting documents from that server.
52 67
 */
53
public class MetacatClient implements Metacat
54
{
68
public class MetacatClient implements Metacat {
55 69
    /** The URL string for the metacat server */
56 70
    private String metacatUrl;
57

  
71
    
58 72
    /** The session identifier for the session */
59 73
    private String sessionId;
60

  
74
    
75
    public static final String              FGDC_SYSTEM_ID = "http://www.fgdc.gov/metadata/fgdc-std-001-1998.dtd";
76
    private static XPath                    xpath = XPathFactory.newInstance().newXPath();
77
    private Document                        loginResponse = null, metadataDoc = null;
78
    private String                          user = null;
79
    
61 80
    /**
81
     * The Login cookie name.
82
     */
83
    public final static String                    LOGIN_COOOKIE = "cookie";
84
    
85
    /**
62 86
     * Constructor to create a new instance. Protected because instances
63 87
     * should only be created by the factory MetacatFactory.
64 88
     */
65
    protected MetacatClient()
66
    {
89
    protected MetacatClient() {
67 90
        this.metacatUrl = null;
68 91
        this.sessionId = null;
69 92
    }
70

  
93
    
71 94
    /**
72 95
     *  Method used to log in to a metacat server. Implementations will need
73 96
     *  to cache a cookie value to make the session persistent.  Each time a
......
81 104
     *                    not be authenticated
82 105
     */
83 106
    public String login(String username, String password)
84
           throws MetacatAuthException, MetacatInaccessibleException
85
    {
107
    throws MetacatAuthException, MetacatInaccessibleException {
86 108
        Properties prop = new Properties();
87 109
        prop.put("action", "login");
88 110
        prop.put("qformat", "xml");
89 111
        prop.put("username", username);
90 112
        prop.put("password", password);
91

  
113
        
92 114
        String response = null;
93 115
        try {
94 116
            response = sendDataForString(prop, null, null, 0);
95 117
        } catch (Exception e) {
96 118
            throw new MetacatInaccessibleException(e.getMessage());
97 119
        }
98

  
120
        
99 121
        if (response.indexOf("<login>") == -1) {
100 122
            setSessionId("");
101 123
            throw new MetacatAuthException(response);
......
121 143
     *  @throws MetacatAuthException when the username/password could
122 144
     *                    not be authenticated
123 145
     */
124
    public String getloggedinuserinfo() throws MetacatInaccessibleException
125
    {
146
    public String getloggedinuserinfo() throws MetacatInaccessibleException {
126 147
        Properties prop = new Properties();
127 148
        prop.put("action", "getloggedinuserinfo");
128 149
        prop.put("qformat", "xml");
129

  
150
        
130 151
        String response = null;
131 152
        try {
132 153
            response = sendDataForString(prop, null, null, 0);
133 154
        } catch (Exception e) {
134 155
            throw new MetacatInaccessibleException(e.getMessage());
135 156
        }
136

  
157
        
137 158
        return response;
138 159
    }
139

  
160
    
140 161
    /**
141 162
     *  Method used to log out a metacat server. The Metacat server will end
142 163
     *  the session when this call is invoked.
......
145 166
     *  @throws MetacatInaccessibleException when the metacat server can not be
146 167
     *                                    reached or does not respond
147 168
     */
148
    public String logout() throws MetacatInaccessibleException, MetacatException
149
    {
169
    public String logout() throws MetacatInaccessibleException, MetacatException {
150 170
        Properties prop = new Properties();
151 171
        prop.put("action", "logout");
152 172
        prop.put("qformat", "xml");
153

  
173
        
154 174
        String response = null;
155 175
        try {
156 176
            response = sendDataForString(prop, null, null, 0);
157 177
        } catch (Exception e) {
158 178
            throw new MetacatInaccessibleException(e.getMessage());
159 179
        }
160

  
180
        
161 181
        if (response.indexOf("<logout>") == -1) {
162 182
            throw new MetacatException(response);
163 183
        }
164 184
        setSessionId("");
165 185
        return response;
166 186
    }
167

  
187
    
168 188
    /**
169 189
     * Read an XML document from the metacat server session, accessed by docid,
170 190
     * and returned as a Reader.
......
178 198
     * @throws MetacatException when the metacat server generates another error
179 199
     */
180 200
    public Reader read(String docid) throws InsufficientKarmaException,
181
        MetacatInaccessibleException, MetacatException, DocumentNotFoundException
182
    {
201
            MetacatInaccessibleException, MetacatException, DocumentNotFoundException {
183 202
        PushbackReader pbr = null;
184

  
203
        
185 204
        Properties prop = new Properties();
186 205
        prop.put("action", "read");
187 206
        prop.put("qformat", "xml");
......
217 236
        }
218 237
        return pbr;
219 238
    }
220

  
221

  
239
    
240
    
222 241
    /**
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

  
242
     * Read inline data from the metacat server session, accessed by
243
     * inlinedataid and returned as a Reader.
244
     *
245
     * @param inlinedataid the identifier of the data to be read
246
     * @return a Reader for accessing the document
247
     * @throws InsufficientKarmaException when the user has insufficent rights
248
     *                                    for the operation
249
     * @throws MetacatInaccessibleException when the metacat server can not be
250
     *                                    reached or does not respond
251
     * @throws MetacatException when the metacat server generates another error
252
     */
253
    public Reader readInlineData(String inlinedataid)
254
    throws InsufficientKarmaException,
255
            MetacatInaccessibleException, MetacatException {
256
        PushbackReader pbr = null;
257
        
258
        Properties prop = new Properties();
259
        prop.put("action", "readinlinedata");
260
        prop.put("inlinedataid", inlinedataid);
261
        
262
        InputStream response = null;
263
        try {
264
            response = sendData(prop, null, null, 0);
265
        } catch (Exception e) {
266
            throw new MetacatInaccessibleException(e.getMessage());
267
        }
268
        
269
        pbr = new PushbackReader(new InputStreamReader(response), 512);
270
        try {
271
            char[] characters = new char[512];
272
            int len = pbr.read(characters, 0, 512);
273
            StringWriter sw = new StringWriter();
274
            sw.write(characters, 0, len);
275
            String message = sw.toString();
276
            sw.close();
277
            pbr.unread(characters, 0, len);
278
            
279
            if (message.indexOf("<error>") != -1) {
280
                if (message.indexOf("does not have permission") != -1) {
281
                    throw new InsufficientKarmaException(message);
282
                } else {
283
                    throw new MetacatException(message);
284
                }
285
            }
286
        } catch (IOException ioe) {
287
            throw new MetacatException(
288
                    "MetacatClient: Error converting Reader to String."
289
                    + ioe.getMessage());
290
        }
291
        
292
        return pbr;
293
    }
294
    
277 295
    /**
278 296
     * Query the metacat document store with the given metacat-compatible
279 297
     * query document, and return the result set as a Reader.
......
282 300
     * @return a Reader for accessing the result set
283 301
     */
284 302
    public Reader query(Reader xmlQuery) throws MetacatInaccessibleException,
285
                                                IOException
286
    {
303
            IOException {
287 304
        Reader reader = null;
288 305
        String query = null;
289 306
        try {
290
          query = IOUtil.getAsString(xmlQuery, true);
307
            query = IOUtil.getAsString(xmlQuery, true);
291 308
        } catch (IOException ioE) {
292
          throw ioE;
309
            throw ioE;
293 310
        }
294

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

  
317
        
301 318
        InputStream response = null;
302 319
        try {
303 320
            response = sendData(prop, null, null, 0);
......
307 324
        reader = new InputStreamReader(response);
308 325
        return reader;
309 326
    }
310

  
327
    
311 328
    /**
312 329
     * Insert an XML document into the repository.
313 330
     *
......
324 341
     * @throws IOException when there is an error reading the xml document
325 342
     */
326 343
    public String insert(String docid, Reader xmlDocument, Reader schema)
327
        throws InsufficientKarmaException, MetacatException, IOException,
328
        MetacatInaccessibleException
329
    {
344
    throws InsufficientKarmaException, MetacatException, IOException,
345
            MetacatInaccessibleException {
330 346
        Reader reader = null;
331 347
        String doctext = null;
332 348
        String schematext = null;
333 349
        try {
334
          doctext = IOUtil.getAsString(xmlDocument, true);
335
          if (schema != null) {
336
              schematext = IOUtil.getAsString(schema, true);
337
          }
350
            doctext = IOUtil.getAsString(xmlDocument, true);
351
            if (schema != null) {
352
                schematext = IOUtil.getAsString(schema, true);
353
            }
338 354
        } catch (IOException ioE) {
339
          throw ioE;
355
            throw ioE;
340 356
        }
341

  
357
        
342 358
        //set up properties
343 359
        Properties prop = new Properties();
344 360
        prop.put("action", "insert");
......
347 363
        if (schematext != null) {
348 364
            prop.put("dtdtext", schematext);
349 365
        }
350

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

  
373
        
358 374
        // Check for an error condition
359 375
        if (response.indexOf("<error>") != -1) {
360 376
            if (response.indexOf("does not have permission") != -1) {
......
363 379
                throw new MetacatException(response);
364 380
            }
365 381
        }
366

  
382
        
367 383
        return response;
368 384
    }
369

  
385
    
370 386
    /**
371 387
     * Update an XML document in the repository.
372 388
     *
......
383 399
     * @throws IOException when there is an error reading the xml document
384 400
     */
385 401
    public String update(String docid, Reader xmlDocument, Reader schema)
386
        throws InsufficientKarmaException, MetacatException, IOException,
387
        MetacatInaccessibleException
388
    {
402
    throws InsufficientKarmaException, MetacatException, IOException,
403
            MetacatInaccessibleException {
389 404
        Reader reader = null;
390 405
        String doctext = null;
391 406
        String schematext = null;
392 407
        try {
393
          doctext = IOUtil.getAsString(xmlDocument, true);
394
          if (schema != null) {
395
              schematext = IOUtil.getAsString(schema, true);
396
          }
408
            doctext = IOUtil.getAsString(xmlDocument, true);
409
            if (schema != null) {
410
                schematext = IOUtil.getAsString(schema, true);
411
            }
397 412
        } catch (IOException ioE) {
398
          throw ioE;
413
            throw ioE;
399 414
        }
400

  
415
        
401 416
        //set up properties
402 417
        Properties prop = new Properties();
403 418
        prop.put("action", "update");
......
406 421
        if (schematext != null) {
407 422
            prop.put("dtdtext", schematext);
408 423
        }
409

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

  
431
        
417 432
        // Check for an error condition
418 433
        if (response.indexOf("<error>") != -1) {
419 434
            if (response.indexOf("does not have permission") != -1) {
......
422 437
                throw new MetacatException(response);
423 438
            }
424 439
        }
425

  
440
        
426 441
        return response;
427 442
    }
428

  
443
    
429 444
    /**
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 {
445
     * Upload a data document into the repository.
446
     *
447
     * @param docid the docid to insert the document
448
     * @param document a Reader for accessing the document to be uploaded
449
     * @return the metacat response message
450
     * @throws InsufficientKarmaException when the user has insufficent rights
451
     *                                    for the operation
452
     * @throws MetacatInaccessibleException when the metacat server can not be
453
     *                                    reached or does not respond
454
     * @throws MetacatException when the metacat server generates another error
455
     * @throws IOException when there is an error reading the xml document
456
     */
457
    public String upload(String docid, File file)
458
    throws InsufficientKarmaException, MetacatException, IOException,
459
            MetacatInaccessibleException {
460
        
461
        URL url = new URL(metacatUrl.trim());
462
        HttpMessage msg = new HttpMessage(url);
463
        //set up properties
464
        Properties arg = new Properties();
465
        arg.put("action", "upload");
466
        arg.put("docid", docid);
467
        
468
        Properties filenames = new Properties();
469
        String filename = file.getAbsolutePath();
470
        filenames.put("datafile", filename);
471
        
472
        String response = null;
473
        try {
460 474
            response = sendDataForString(arg, filenames, null, 0);
461
          } catch (Exception e) {
475
        } catch (Exception e) {
462 476
            throw new MetacatInaccessibleException(e.getMessage());
463
          }
464

  
465
          // Check for an error condition
466
          if (response.indexOf("<error>") != -1) {
477
        }
478
        
479
        // Check for an error condition
480
        if (response.indexOf("<error>") != -1) {
467 481
            if (response.indexOf("does not have permission") != -1) {
468
              throw new InsufficientKarmaException(response);
482
                throw new InsufficientKarmaException(response);
469 483
            } else {
470
              throw new MetacatException(response);
484
                throw new MetacatException(response);
471 485
            }
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 {
486
        }
487
        
488
        return response;
489
    }
490
    
491
    /**
492
     * Upload a data document into the repository.
493
     *
494
     * @param docid the docid to insert the document
495
     * @param document a Reader for accessing the document to be uploaded
496
     * @return the metacat response message
497
     * @throws InsufficientKarmaException when the user has insufficent rights
498
     *                                    for the operation
499
     * @throws MetacatInaccessibleException when the metacat server can not be
500
     *                                    reached or does not respond
501
     * @throws MetacatException when the metacat server generates another error
502
     * @throws IOException when there is an error reading the xml document
503
     */
504
    
505
    
506
    public String upload(String docid, String filename, InputStream fileData,
507
            int size)
508
            throws InsufficientKarmaException, MetacatException, IOException,
509
            MetacatInaccessibleException {
510
        
511
        URL url = new URL(metacatUrl.trim());
512
        HttpMessage msg = new HttpMessage(url);
513
        //set up properties
514
        Properties arg = new Properties();
515
        arg.put("action", "upload");
516
        arg.put("docid", docid);
517
        
518
        Properties filenames = new Properties();
519
        filenames.put("datafile", filename);
520
        
521
        String response = null;
522
        try {
509 523
            response = sendDataForString(arg, filenames, fileData, size);
510
          } catch (Exception e) {
524
        } catch (Exception e) {
511 525
            throw new MetacatInaccessibleException(e.getMessage());
512
          }
513

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

  
523
          return response;
524
      }
525

  
535
        }
536
        
537
        return response;
538
    }
539
    
526 540
    /**
527 541
     * Delete an XML document in the repository.
528 542
     *
......
535 549
     * @throws MetacatException when the metacat server generates another error
536 550
     */
537 551
    public String delete(String docid)
538
        throws InsufficientKarmaException, MetacatException,
539
        MetacatInaccessibleException
540
    {
552
    throws InsufficientKarmaException, MetacatException,
553
            MetacatInaccessibleException {
541 554
        //set up properties
542 555
        Properties prop = new Properties();
543 556
        prop.put("action", "delete");
544 557
        prop.put("docid", docid);
545

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

  
565
        
553 566
        // Check for an error condition
554 567
        if (response.indexOf("<error>") != -1) {
555 568
            if (response.indexOf("does not have permission") != -1) {
......
560 573
        }
561 574
        return response;
562 575
    }
563

  
564

  
576
    
577
    
565 578
    /**
566 579
     * set the access on an XML document in the repository.
567 580
     *
......
588 601
     * @throws MetacatException when the metacat server generates another error
589 602
     */
590 603
    public String setAccess(String _docid, String _principal, String
591
                            _permission, String _permType, 
592
                            String _permOrder )
593
        throws InsufficientKarmaException, MetacatException,
594
        MetacatInaccessibleException
595
    {  
604
            _permission, String _permType,
605
            String _permOrder )
606
            throws InsufficientKarmaException, MetacatException,
607
            MetacatInaccessibleException {
596 608
        //set up properties
597 609
        Properties prop = new Properties();
598 610
        prop.put("action", "setaccess");
......
601 613
        prop.put("permission", _permission);
602 614
        prop.put("permType", _permType);
603 615
        prop.put("permOrder", _permOrder);
604

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

  
623
        
612 624
        // Check for an error condition
613 625
        if (response.indexOf("<error>") != -1) {
614 626
            if (response.indexOf("does not have permission") != -1) {
......
619 631
        }
620 632
        return response;
621 633
    }
622

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

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

  
655
    
646 656
    /**
647 657
     * Set the session identifier for this session.  This identifier was
648 658
     * previously established with a call to login.  To continue to use the
......
651 661
     *
652 662
     * @param String the sessionId from a previously established session
653 663
     */
654
    public void setSessionId(String sessionId)
655
    {
664
    public void setSessionId(String sessionId) {
656 665
        this.sessionId = sessionId;
657 666
    }
658 667
    
659 668
    /**
660
     * The method will return the latest revision in metacat server 
669
     * The method will return the latest revision in metacat server
661 670
     * for a given document id. If some error happens, this method will throw
662
     * an exception.   
671
     * an exception.
663 672
     * @param docId String  the given docid you want to use. the docid it self
664 673
     *                      can have or haven't revision number
665 674
     * @throws MetacatException
666 675
     */
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
             //parseRevisionResponse will return null if there is an 
679
             //error that it can't handle
680
             String revStr = parserRevisionResponse(response);
681
             Integer revObj = new Integer(revStr);
682
             rev = revObj.intValue();
683
             // Check for an error condition
684
             if (response.indexOf("<error>") != -1 && revStr == null) {
685
                 throw new MetacatException(response);
686
             }
687
         } catch (Exception e) {
688
             throw new MetacatException(e.getMessage());
689
         }
690
         return rev;
691
     }
692

  
676
    public int getNewestDocRevision(String docId) throws MetacatException {
677
        int rev = 0;
678
        //set up properties
679
        Properties prop = new Properties();
680
        prop.put("action", "getrevisionanddoctype");
681
        prop.put("docid", docId);
682
        
683
        String response = null;
684
        try {
685
            response = sendDataForString(prop, null, null, 0);
686
            //parseRevisionResponse will return null if there is an
687
            //error that it can't handle
688
            String revStr = parserRevisionResponse(response);
689
            Integer revObj = new Integer(revStr);
690
            rev = revObj.intValue();
691
            // Check for an error condition
692
            if (response.indexOf("<error>") != -1 && revStr == null) {
693
                throw new MetacatException(response);
694
            }
695
        } catch (Exception e) {
696
            throw new MetacatException(e.getMessage());
697
        }
698
        return rev;
699
    }
700
    
693 701
    /**
694 702
     * Return the highest document id for a given scope.  This is used by
695 703
     * clients to make it easier to determine the next free identifier in a
696
     * sequence for a given scope.  
704
     * sequence for a given scope.
697 705
     * @param scope String  the scope to use for looking up the latest id
698 706
     * @throws MetacatException when an error occurs
699 707
     */
......
703 711
        Properties prop = new Properties();
704 712
        prop.put("action", "getlastdocid");
705 713
        prop.put("scope", scope);
706
         
714
        
707 715
        String response = null;
708 716
        try {
709 717
            response = sendDataForString(prop, null, null, 0);
710 718
            // Check for an error condition
711 719
            if (response.indexOf("<error>") != -1) {
712
               throw new MetacatException(response);
720
                throw new MetacatException(response);
713 721
            } else {
714 722
                Reader responseReader = new StringReader(response);
715
                Node root = 
716
                    XMLUtilities.getXMLReaderAsDOMTreeRootNode(responseReader); 
717
                Node docidNode = 
718
                    XMLUtilities.getNodeWithXPath(root, "/lastDocid/docid");
723
                Node root =
724
                        XMLUtilities.getXMLReaderAsDOMTreeRootNode(responseReader);
725
                Node docidNode =
726
                        XMLUtilities.getNodeWithXPath(root, "/lastDocid/docid");
719 727
                lastIdentifier = docidNode.getFirstChild().getNodeValue();
720 728
            }
721 729
        } catch (Exception e) {
......
735 743
        //set up properties
736 744
        Properties prop = new Properties();
737 745
        prop.put("action", "getalldocids");
738
        if(scope != null)
739
        {
740
          prop.put("scope", scope);
746
        if(scope != null) {
747
            prop.put("scope", scope);
741 748
        }
742
         
749
        
743 750
        String response = null;
744 751
        try {
745 752
            response = sendDataForString(prop, null, null, 0);
746 753
            // Check for an error condition
747 754
            if (response.indexOf("<error>") != -1) {
748
               throw new MetacatException(response);
755
                throw new MetacatException(response);
749 756
            } else {
750 757
                Reader responseReader = new StringReader(response);
751
                Node root = 
752
                    XMLUtilities.getXMLReaderAsDOMTreeRootNode(responseReader); 
758
                Node root =
759
                        XMLUtilities.getXMLReaderAsDOMTreeRootNode(responseReader);
753 760
                NodeList nlist = root.getChildNodes();
754
                for(int i=0; i<nlist.getLength(); i++)
755
                {
756
                  Node n = nlist.item(i);
757
                  if(n.getNodeName().equals("docid"))
758
                  {
759
                    //add the content to the return vector
760
                    String nodeVal = n.getFirstChild().getNodeValue();
761
                    resultVec.addElement(nodeVal);
762
                  }
761
                for(int i=0; i<nlist.getLength(); i++) {
762
                    Node n = nlist.item(i);
763
                    if(n.getNodeName().equals("docid")) {
764
                        //add the content to the return vector
765
                        String nodeVal = n.getFirstChild().getNodeValue();
766
                        resultVec.addElement(nodeVal);
767
                    }
763 768
                }
764 769
                
765 770
            }
......
779 784
        //set up properties
780 785
        Properties prop = new Properties();
781 786
        prop.put("action", "isregistered");
782
        if(docid == null)
783
        {
784
          throw new MetacatException("<error>Cannot check if a null docid " +
785
            "is registered.</error>");
787
        if(docid == null) {
788
            throw new MetacatException("<error>Cannot check if a null docid " +
789
                    "is registered.</error>");
786 790
        }
787 791
        prop.put("docid", docid);
788
         
792
        
789 793
        String response = null;
790 794
        try {
791 795
            response = sendDataForString(prop, null, null, 0);
792 796
            // Check for an error condition
793 797
            if (response.indexOf("<error>") != -1) {
794
               throw new MetacatException(response);
798
                throw new MetacatException(response);
795 799
            } else {
796 800
                Reader responseReader = new StringReader(response);
797 801
                StringBuffer sb = new StringBuffer();
798 802
                char[] c = new char[1024];
799 803
                int numread = responseReader.read(c, 0, 1024);
800
                while(numread != -1)
801
                {
802
                  sb.append(new String(c, 0, numread));
803
                  numread = responseReader.read(c, 0, 1024);
804
                while(numread != -1) {
805
                    sb.append(new String(c, 0, numread));
806
                    numread = responseReader.read(c, 0, 1024);
804 807
                }
805 808
                
806 809
                String responseStr = sb.toString();
807
                if(responseStr.indexOf("true") != -1)
808
                {
809
                  return true;
810
                if(responseStr.indexOf("true") != -1) {
811
                    return true;
810 812
                }
811 813
                return false;
812 814
            }
......
814 816
            throw new MetacatException(e.getMessage());
815 817
        }
816 818
    }
817

  
819
    
818 820
    /************************************************************************
819 821
     * PRIVATE METHODS
820 822
     ************************************************************************/
821

  
823
    
822 824
    /**
823 825
     * Send a request to metacat.
824 826
     *
......
831 833
     *                  in case of upload, otherwise 0
832 834
     */
833 835
    synchronized private InputStream sendDataOnce(Properties args,
834
                                                  Properties filename,
835
                                                  InputStream fileData,
836
                                                  int size)
837
        throws Exception
838
    {
836
            Properties filename,
837
            InputStream fileData,
838
            int size)
839
            throws Exception {
839 840
        InputStream returnStream = null;
840 841
        URL url = new URL(metacatUrl);
841 842
        HttpMessage msg = new HttpMessage(url);
......
848 849
            returnStream = msg.sendPostData(args, filename, fileData, size);
849 850
        } else {
850 851
            throw new MetacatException("Invalid size specified for " +
851
                                       "the input stream being passed");
852
                    "the input stream being passed");
852 853
        }
853 854
        return returnStream;
854 855
    }
855

  
856
    
856 857
    /**
857 858
     * Send a request to Metacat
858 859
     *
......
866 867
     * @return      InputStream as returned by Metacat
867 868
     */
868 869
    synchronized private InputStream sendData(Properties args,
869
                                              Properties filename,
870
                                              InputStream fileData,
871
                                              int size)
872
        throws Exception
873
    {
870
            Properties filename,
871
            InputStream fileData,
872
            int size)
873
            throws Exception {
874 874
        InputStream returnStream = null;
875 875
        /*
876 876
            Note:  The reason that there are three try statements all executing
......
880 880
            2nd and 3rd chance to work before throwing an error.
881 881
            THIS IS A TOTAL HACK.  THIS NEEDS TO BE LOOKED INTO AFTER THE BETA1
882 882
            RELEASE OF MORPHO!!!  cwb (7/24/01)
883
          */
883
         */
884 884
        try {
885
           return sendDataOnce(args, filename, fileData, size);
885
            return sendDataOnce(args, filename, fileData, size);
886 886
        } catch (Exception e) {
887 887
            try {
888 888
                return sendDataOnce(args, filename, fileData, size);
......
898 898
            }
899 899
        }
900 900
    }
901

  
901
    
902 902
    /**
903 903
     * Send a request to Metacat
904 904
     *
......
912 912
     * @return          a string as returned by Metacat
913 913
     */
914 914
    synchronized private String sendDataForString(Properties args,
915
                                                  Properties filename,
916
                                                  InputStream fileData,
917
                                                  int size)
918
        throws Exception
919
    {
915
            Properties filename,
916
            InputStream fileData,
917
            int size)
918
            throws Exception {
920 919
        String response = null;
921

  
920
        
922 921
        try {
923 922
            InputStreamReader returnStream =
924 923
                    new InputStreamReader(sendData(args, filename,
925
                                                   fileData, size));
924
                    fileData, size));
926 925
            StringWriter sw = new StringWriter();
927 926
            int len;
928 927
            char[] characters = new char[512];
......
943 942
     * The string format is "revision;doctype"(This is bad idea, we should use xml)
944 943
     * This method will get revision string from the response string
945 944
     */
946
    private String parserRevisionResponse(String response) throws Exception
947
    {
948
      String revision = null;
949
      if (response != null)
950
      {
951
        if(response.indexOf("<error>") != -1)
952
        {
953
          if(response.indexOf("There is not record") != -1)
954
          {
955
            return "0";
956
          }
957
          else
958
          {
959
            return null;
960
          }
945
    private String parserRevisionResponse(String response) throws Exception {
946
        String revision = null;
947
        if (response != null) {
948
            if(response.indexOf("<error>") != -1) {
949
                if(response.indexOf("There is not record") != -1) {
950
                    return "0";
951
                } else {
952
                    return null;
953
                }
954
            } else {
955
                int firstSemiCol = response.indexOf(";");
956
                revision = response.substring(0, firstSemiCol);
957
            }
961 958
        }
959
        return revision;
960
    }
961
    
962
    /**
963
     * JSP API: This is a convenience method to reduce the amount of code in a Metacat Client
964
     * JSP.  It handles creating/reusing an instance of a MetacatClient.
965
     * @param request Since this is intended to be used by a JSP, it is passed the
966
     * available "request" variable (the HttpServletRequest).
967
     * @throws edu.ucsb.nceas.metacat.client.MetacatInaccessibleException Received by MetacatFactory.
968
     * @return MetacatClient instance.
969
     */
970
    public static MetacatClient getMetacatClient(javax.servlet.http.HttpServletRequest request) throws MetacatInaccessibleException {
971
        MetacatClient                       result;
972
        String                              metacatPath = "http://%1$s%2$s/metacat";
973
        String                              host, context;
974
        javax.servlet.http.HttpSession      session;
975
        
976
        session = request.getSession();
977
        result = (MetacatClient) session.getAttribute("MetacatClient");
978
        if (result == null) {
979
            host = request.getHeader("host");
980
            context = request.getContextPath();
981
            metacatPath = String.format(metacatPath, host, context);
982
            result = (MetacatClient) MetacatFactory.createMetacatConnection(metacatPath);
983
            session.setAttribute("MetacatClient", result);
984
        }
985
        return(result);
986
    }
987
    
988
    /**
989
     * JSP API: When the user logs in, the server will send back a string containing XML.  Calling
990
     * this method with the string will allow other methods to work, such as isLoggIn()
991
     * and getLoginResponseElement().
992
     * @param xmlString XML in String format.
993
     * @throws java.io.IOException Input/Output exception.
994
     */
995
    public void setLoginResponse(String xmlString) throws IOException {
996
        if (xmlString != null) {
997
            loginResponse = XMLUtilities.getXMLReaderAsDOMDocument(new StringReader(xmlString));
998
        }
999
    }
1000
    
1001
    private void setMetadataDoc(InputStream ioStream) throws IOException {
1002
        BufferedReader                          buffy;
1003
        
1004
        if (ioStream != null) {
1005
            buffy = new BufferedReader(new InputStreamReader(ioStream));
1006
            metadataDoc = XMLUtilities.getXMLReaderAsDOMDocument(buffy);
1007
        }
1008
    }
1009
    
1010
    /**
1011
     * JSP API: A convenient and efficient method to retrieve info from the "login response".
1012
     * @param elementName String of the elementName.
1013
     * NOTE: setLoginResponse() must have been called first,
1014
     * otherwise it will always return null.
1015
     * @throws javax.xml.xpath.XPathExpressionException XPath error.
1016
     * @return String containing the text content of the element, or null.
1017
     */
1018
    public String getLoginResponseElement(String elementName) throws XPathExpressionException {
1019
        String                      result = null;
1020
        
1021
        if (loginResponse != null) {
1022
            result = (String) xpath.evaluate(elementName, loginResponse.getDocumentElement(), XPathConstants.STRING);
1023
            if (result != null)
1024
                result = result.trim();
1025
        }
1026
        return(result);
1027
    }
1028
    
1029
    
1030
    /**
1031
     * JSP API: Easy way to get info from an uploaded metadata XML file.
1032
     * Note:  doMetadataUpload() must have been called first.
1033
     * @param elementName String containing the elemement name
1034
     * @throws javax.xml.xpath.XPathExpressionException Thrown by XPath
1035
     * @return String text content of the named element
1036
     */
1037
    public String getMetadataDocElement(String elementName) throws XPathExpressionException {
1038
        String                      result = null;
1039
        
1040
        if (metadataDoc != null) {
1041
            result = (String) xpath.evaluate(elementName, metadataDoc.getDocumentElement(), XPathConstants.STRING);
1042
            result = result.trim();
1043
        }
1044
        return(result);
1045
    }
1046
    
1047
    /**
1048
     * JSP API: A convenience method to be used by JSP or any other client code that requires
1049
     * the user to be logged in.  NOTE: setUser() must have been called first,
1050
     * otherwise it will always return false.
1051
     * @return boolean  true if user has logged in for this session, false otherwise.
1052
     */
1053
    public boolean isLoggedIn() {
1054
        return(user != null);
1055
    }
1056
    
1057
    /**
1058
     * JSP API: After calling "login(ldapUserName, pwd)", call this with the username
1059
     * and servers response message.  You can than use isLoggedIn() to determine if
1060
     * the user is logged in, getLoginResponseElement(), etc.  The user name will also
1061
     * used by calls to doMetadataUpload() for Document Id creation (scope).
1062
     * @param userName User name
1063
     * @param serverResponse XML login response sent from Metacat.
1064
     */
1065
    public void setUser(String userName, String serverResponse) {
1066
        if (serverResponse != null && serverResponse.contains("login"))
1067
            user = userName;
962 1068
        else
963
        {
964
          int firstSemiCol = response.indexOf(";");
965
          revision = response.substring(0, firstSemiCol);
1069
            user = null;
1070
    }
1071
    
1072
    /**
1073
     * JSP API:  Handles metadata file and data file uploads for inserting new
1074
     * Metacat data packages.  Note: if content type is not "multipart/form-data",
1075
     * nothing will happen; thus, it's safe to be (unintentionally) called by other
1076
     * types of form submissions.
1077
     * @param request HTTP request.
1078
     * @return A 1-line status message for the user.
1079
     */
1080
    public String doMetadataUpload(javax.servlet.http.HttpServletRequest request) {
1081
        String                      result = "", contentType, formatType;
1082
        String                      lastDocId, nextDocId, metaDocId;
1083
        StringBuilder               fileName = new StringBuilder();
1084
        Reader                      reader;
1085
        int                         sizeLimit;
1086
        MultipartParser             multipartParser;
1087
        InputStream                 inputStream;
1088
        Node                        newBranch, metaRootNode;
1089
        HashMap                     dataDocIDs;
1090
        
1091
        //*** Only process request if a file upload.
1092
        contentType = request.getContentType();
1093
        if (isLoggedIn() && contentType != null && contentType.contains("multipart/form-data")) {
1094
            try {
1095
                //*** Init the MultipartParser.
1096
                sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit"))).intValue();
1097
                multipartParser = new MultipartParser(request, sizeLimit * 1024 * 1024);
1098
                
1099
                //*** Get the First file, which should be the metadata file.
1100
                inputStream = getNextInputStream(multipartParser, fileName);
1101
                if (fileName.toString().toLowerCase().endsWith(".xml")) {
1102
                    setMetadataDoc(inputStream);
1103
                    
1104
                    //*** Get the Metadata File's DOC ID.
1105
                    lastDocId = getLastDocid(user);
1106
                    metaDocId = lastDocId = nextDocId(lastDocId);
1107
                    
1108
                    if (isFGDC()) {
1109
                        //*** Loop thru all of the data files, get fileName and inputStream.
1110
                        dataDocIDs = new HashMap();
1111
                        fileName = new StringBuilder();
1112
                        while ((inputStream = getNextInputStream(multipartParser, fileName)) != null) {
1113
                            //*** Get the data file's DOC ID.
1114
                            nextDocId = nextDocId(lastDocId);
1115
                            //*** Set the file format (just using file extension for now).
1116
                            formatType = fileName.substring(fileName.lastIndexOf(".")+1).toUpperCase();
1117
                            dataDocIDs.put(nextDocId, formatType);
1118
                            //*** Upload the data file to metacat.
1119
                            upload(nextDocId, fileName.toString(), inputStream, sizeLimit);
1120
                            
1121
                            lastDocId = nextDocId;
1122
                            fileName = new StringBuilder();
1123
                        }
1124
                        
1125
                        //*** Store the User Name and Doc Id in the FGDC document.
1126
                        newBranch = getFGDCdisinfo(getLoginResponseElement("name"), metaDocId, dataDocIDs);
1127
                        System.out.println("MetacatClient.doMetadataUpload: " + XMLUtilities.getDOMTreeAsString(newBranch));
1128
                        metaRootNode = addDistInfoToFGDC(newBranch);
1129
                        
1130
                        //*** Upload the metadata file to metacat.
1131
                        reader = XMLUtilities.getDOMTreeAsReader(metadataDoc.getDocumentElement(), false);
1132
                        insert(metaDocId, reader, null);
1133
                        
1134
                        result = "MetaCat Package Inserted:  Metadata Doc ID #" + metaDocId;
1135
                        reader.close();
1136
                    } else {
1137
                        System.out.println("MetacatClient.doUpload: not an FGDC file = " + fileName);
1138
                        result = fileName + " is not an FGDC file.  Files not uploaded.";
1139
                        //TODO add other types of metadata grammars here...
1140
                    }
1141
                } else {
1142
                    result = "The first file must be an XML Metadata file.  Files not uploaded.";
1143
                }
1144
                if (inputStream != null)
1145
                    inputStream.close();
1146
            } catch (MetacatException ex)  {
1147
                result = ex.getMessage();
1148
                System.out.println("MetacatClient.doUpload: MetacatException = " + result);
1149
            } catch (IOException ex)  {
1150
                System.out.println("MetacatClient.doUpload: " + ex);
1151
            } catch (Exception ex) {
1152
                System.out.println("MetacatClient.doUpload: " + ex);
1153
            } catch (Error err) {
1154
                System.out.println("MetacatClient.doUpload: ERR - " + err.getCause());
1155
                result = "ERR: " + err.getMessage();
1156
            }
966 1157
        }
967
      } 
968
      return revision;
1158
        return(result);
969 1159
    }
1160
    
1161
    private InputStream getNextInputStream(MultipartParser multipartParser, StringBuilder fileName) throws IOException {
1162
        InputStream                     result = null;
1163
        Part                            part;
1164
        String                          parmName = null, value = null, fnam;
1165
        
1166
        while ((part = multipartParser.readNextPart()) != null) {
1167
            if (part.isParam()) {
1168
                parmName = part.getName();
1169
                value = ((ParamPart) part).getStringValue();
1170
                System.out.println("MetacatClient.doUpload: parmName = " + parmName + "  value = " + value);
1171
                
1172
            } else if (part.isFile()) {
1173
                fnam = ((FilePart) part).getFileName();
1174
                if (fnam != null && !fnam.equals("")) {
1175
                    //*** File name is passed back via StringBuilder fileName param.
1176
                    fileName.append(fnam);
1177
                    result = ((FilePart) part).getInputStream();
1178
                    System.out.println("MetacatClient.doUpload: fileName = " + fileName + "  inputStream = " + result.toString());
1179
                    break;
1180
                }
1181
            }
1182
        }
1183
        return(result);
1184
    }
1185
    
1186
    private String nextDocId(String lastDocId) {
1187
        String                      result = null, tokens[];
1188
        int                         vers;
1189
        String                      template = user.toLowerCase() + ".%1$d.%2$d";
1190
        
1191
        if(lastDocId != null && lastDocId.contains(".")) {
1192
            lastDocId = lastDocId.replace('.','~'); //*** This is necessary for the split to work.
1193
            tokens = lastDocId.split("~");
1194
            if(tokens.length > 1 && !tokens[1].equals("")) {
1195
                try {
1196
                    vers = Integer.parseInt(tokens[1]);
1197
                    result = String.format(template, 1 + vers, 1);
1198
                } catch (NumberFormatException ex) {
1199
                    //*** In case the lastDocId has something other than a number.
1200
                    result = String.format(template, 1, 1);
1201
                }
1202
            } else {
1203
                //*** In case the lastDocId ends with a '.'
1204
                result = String.format(template, 1, 1);
1205
            }
1206
        } else {
1207
            //*** In case there isn't any doc Id's with the user name.
1208
            result = String.format(template, 1, 1);
1209
        }
1210
        return(result);
1211
    }
1212
    
1213
    private boolean isFGDC() {
1214
        boolean                     result = false;
1215
        DocumentType                docType;
1216
        String                      sysId, title = null;
1217
        final String                FGDC_TEST_EXPRESSION = "/metadata/idinfo/citation/citeinfo/title";
1218
        
1219
        //*** First, try the rigid proper way of determining it.
1220
        if (metadataDoc != null) {
1221
            docType = metadataDoc.getDoctype();
1222
            if (docType != null) {
1223
                sysId = docType.getSystemId();
1224
                if (sysId != null)
1225
                    result = sysId.contains(FGDC_SYSTEM_ID);
1226
            }
1227
        }
1228
        //*** It might not have a doc type line, so try another method.
1229
        if (!result) {
1230
            try {
1231
                title = getMetadataDocElement(FGDC_TEST_EXPRESSION);
1232
            } catch (XPathExpressionException ex) {
1233
                ex.printStackTrace();
1234
            }
1235
            result = (title != null && !title.equals(""));
1236
        }
1237
        return(result);
1238
    }
1239
    
1240
    private Node getFGDCdisinfo(String contactName, String resourceDescription, HashMap dataDocIDs) throws IOException {
1241
        Node                        result = null, node, digformBranch, formname, stdorder;
1242
        Document                    doc;
1243
        Iterator                    iterIt;
1244
        String                      key, value;
1245
        
1246
        //*** This is a valid/minimal FGDC "distinfo" branch.
1247
        final String XML = "<distinfo>"
1248
                + "    <distrib>"
1249
                + "        <cntinfo>"
1250
                + "            <cntperp>"
1251
                + "                <cntper></cntper>"
1252
                + "            </cntperp>"
1253
                + "            <cntaddr>"
1254
                + "                <addrtype></addrtype>"
1255
                + "                <address></address>"
1256
                + "                <city></city>"
1257
                + "                <state></state>"
1258
                + "                <postal></postal>"
1259
                + "                <country></country>"
1260
                + "            </cntaddr>"
1261
                + "            <cntvoice></cntvoice>"
1262
                + "        </cntinfo>"
1263
                + "    </distrib>"
1264
                + "    <resdesc></resdesc>"
1265
                + "    <distliab></distliab>"
1266
                + "    <stdorder>"
1267
                + "        <digform>"
1268
                + "            <digtinfo>"
1269
                + "                <formname></formname>"
1270
                + "            </digtinfo>"
1271
                + "            <digtopt>"
1272
                + "                <onlinopt>"
1273
                + "                    <computer>"
1274
                + "                        <networka>"
1275
                + "                            <networkr></networkr>"
1276
                + "                        </networka>"
1277
                + "                    </computer>"
1278
                + "                </onlinopt>"
1279
                + "            </digtopt>"
1280
                + "        </digform>"
1281
                + "        <fees></fees>"
1282
                + "    </stdorder>"
1283
                + "</distinfo>";
1284
        
1285
        doc = XMLUtilities.getXMLReaderAsDOMDocument(new StringReader(XML));
1286
        result = doc.getDocumentElement();
1287
        try {
1288
            //*** Set the Contact Person.
1289
            node = (Node) xpath.evaluate("/distinfo/distrib/cntinfo/cntperp/cntper", result, XPathConstants.NODE);
1290
            node.setTextContent(contactName);
1291
            //*** Set the metadata Doc Id.
1292
            node = (Node) xpath.evaluate("/distinfo/resdesc", result, XPathConstants.NODE);
1293
            node.setTextContent(resourceDescription);
1294
            
1295
            //*** Loop thru the files, setting their format and Doc Id.
1296
            stdorder = (Node) xpath.evaluate("/distinfo/stdorder", result, XPathConstants.NODE);
1297
            digformBranch = (Node) xpath.evaluate("/distinfo/stdorder/digform", result, XPathConstants.NODE);
1298
            iterIt = dataDocIDs.keySet().iterator();
1299
            while(iterIt.hasNext()) {
1300
                //*** Save the data file Doc ID (required).
1301
                key = (String) iterIt.next();
1302
                node = (Node) xpath.evaluate("digtopt/onlinopt/computer/networka/networkr", digformBranch, XPathConstants.NODE);
1303
                node.setTextContent(key);
1304
                //*** Save the data file format (optional).
1305
                formname = (Node) xpath.evaluate("digtinfo/formname", digformBranch, XPathConstants.NODE);
1306
                if ((value = (String) dataDocIDs.get(key)) != null && !value.equals("")) {
1307
                    formname.setTextContent(value);
1308
                } else {
1309
                    //*** We did a deep clone of the branch, so clear prior contents.
1310
                    formname.setTextContent("");
1311
                }
1312
                
1313
                //*** Clone branch for next file.
1314
                if (iterIt.hasNext()) {
1315
                    digformBranch = digformBranch.cloneNode(true);
1316
                    stdorder.appendChild(digformBranch);
1317
                }
1318
            }
1319
        } catch (XPathExpressionException ex) {
1320
            ex.printStackTrace();
1321
        }
1322
        return(result);
1323
    }
1324
    
1325
    private Node addDistInfoToFGDC(Node newBranch) {
1326
        Node                        result = null, node;
1327
        
1328
        if (newBranch != null) {
1329
            result = metadataDoc.getDocumentElement();
1330
            try {
1331
                //*** Get a reference to the FGDC required "metainfo" node (only 1 allowed).
1332
                node = (Node) xpath.evaluate("/metadata/metainfo", result, XPathConstants.NODE);
1333
                if (node != null) {
1334
                    newBranch = metadataDoc.importNode(newBranch, true);
1335
                    //*** Add the new "distinfo" before it.
1336
                    result.insertBefore(newBranch, node);
1337
                }
1338
            } catch (XPathExpressionException ex) {
1339
                ex.printStackTrace();
1340
            }
1341
        }
1342
        return(result);
1343
    }
1344
    
970 1345
}

Also available in: Unified diff