Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *    Release: 1.4.0
12
 *
13
 *   '$Author: jones $'
14
 *     '$Date: 2004-04-05 16:25:54 -0700 (Mon, 05 Apr 2004) $'
15
 * '$Revision: 2106 $'
16
 *
17
 * This program is free software; you can redistribute it and/or modify
18
 * it under the terms of the GNU General Public License as published by
19
 * the Free Software Foundation; either version 2 of the License, or
20
 * (at your option) any later version.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
 * GNU General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU General Public License
28
 * along with this program; if not, write to the Free Software
29
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30
 */
31

    
32
package edu.ucsb.nceas.metacat;
33

    
34
import java.io.BufferedWriter;
35
import java.io.File;
36
import java.io.FileInputStream;
37
import java.io.FileReader;
38
import java.io.FileWriter;
39
import java.io.IOException;
40
import java.io.InputStream;
41
import java.io.PrintWriter;
42
import java.io.Reader;
43
import java.io.StringReader;
44
import java.io.StringWriter;
45
import java.sql.PreparedStatement;
46
import java.sql.ResultSet;
47
import java.sql.SQLException;
48
import java.util.Enumeration;
49
import java.util.Hashtable;
50
import java.util.StringTokenizer;
51
import java.util.Vector;
52
import java.util.zip.ZipEntry;
53
import java.util.zip.ZipOutputStream;
54

    
55
import javax.servlet.ServletOutputStream;
56
import javax.servlet.http.HttpServletResponse;
57

    
58

    
59
import edu.ucsb.nceas.morpho.datapackage.Triple;
60
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
61

    
62
/**
63
 * A Class that searches a relational DB for elements and attributes that have
64
 * free text matches a query string, or structured query matches to a path
65
 * specified node in the XML hierarchy. It returns a result set consisting of
66
 * the document ID for each document that satisfies the query
67
 */
68
public class DBQuery
69
{
70

    
71
    static final int ALL = 1;
72

    
73
    static final int WRITE = 2;
74

    
75
    static final int READ = 4;
76

    
77
    //private Connection conn = null;
78
    private String parserName = null;
79

    
80
    private MetaCatUtil util = new MetaCatUtil();
81

    
82
    /**
83
     * the main routine used to test the DBQuery utility.
84
     * <p>
85
     * Usage: java DBQuery <xmlfile>
86
     *
87
     * @param xmlfile the filename of the xml file containing the query
88
     */
89
    static public void main(String[] args)
90
    {
91

    
92
        if (args.length < 1) {
93
            System.err.println("Wrong number of arguments!!!");
94
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
95
            return;
96
        } else {
97
            try {
98

    
99
                int i = 0;
100
                boolean showRuntime = false;
101
                boolean useXMLIndex = false;
102
                if (args[i].equals("-t")) {
103
                    showRuntime = true;
104
                    i++;
105
                }
106
                if (args[i].equals("-index")) {
107
                    useXMLIndex = true;
108
                    i++;
109
                }
110
                String xmlfile = args[i];
111

    
112
                // Time the request if asked for
113
                double startTime = System.currentTimeMillis();
114

    
115
                // Open a connection to the database
116
                MetaCatUtil util = new MetaCatUtil();
117
                //Connection dbconn = util.openDBConnection();
118

    
119
                double connTime = System.currentTimeMillis();
120

    
121
                // Execute the query
122
                DBQuery queryobj = new DBQuery(MetaCatUtil
123
                        .getOption("saxparser"));
124
                FileReader xml = new FileReader(new File(xmlfile));
125
                Hashtable nodelist = null;
126
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
127

    
128
                // Print the reulting document listing
129
                StringBuffer result = new StringBuffer();
130
                String document = null;
131
                String docid = null;
132
                result.append("<?xml version=\"1.0\"?>\n");
133
                result.append("<resultset>\n");
134

    
135
                if (!showRuntime) {
136
                    Enumeration doclist = nodelist.keys();
137
                    while (doclist.hasMoreElements()) {
138
                        docid = (String) doclist.nextElement();
139
                        document = (String) nodelist.get(docid);
140
                        result.append("  <document>\n    " + document
141
                                + "\n  </document>\n");
142
                    }
143

    
144
                    result.append("</resultset>\n");
145
                }
146
                // Time the request if asked for
147
                double stopTime = System.currentTimeMillis();
148
                double dbOpenTime = (connTime - startTime) / 1000;
149
                double readTime = (stopTime - connTime) / 1000;
150
                double executionTime = (stopTime - startTime) / 1000;
151
                if (showRuntime) {
152
                    System.out.print("  " + executionTime);
153
                    System.out.print("  " + dbOpenTime);
154
                    System.out.print("  " + readTime);
155
                    System.out.print("  " + nodelist.size());
156
                    System.out.println();
157
                }
158
                //System.out.println(result);
159
                //write into a file "result.txt"
160
                if (!showRuntime) {
161
                    File f = new File("./result.txt");
162
                    FileWriter fw = new FileWriter(f);
163
                    BufferedWriter out = new BufferedWriter(fw);
164
                    out.write(result.toString());
165
                    out.flush();
166
                    out.close();
167
                    fw.close();
168
                }
169

    
170
            } catch (Exception e) {
171
                System.err.println("Error in DBQuery.main");
172
                System.err.println(e.getMessage());
173
                e.printStackTrace(System.err);
174
            }
175
        }
176
    }
177

    
178
    /**
179
     * construct an instance of the DBQuery class
180
     *
181
     * <p>
182
     * Generally, one would call the findDocuments() routine after creating an
183
     * instance to specify the search query
184
     * </p>
185
     *
186

    
187
     * @param parserName the fully qualified name of a Java class implementing
188
     *            the org.xml.sax.XMLReader interface
189
     */
190
    public DBQuery(String parserName)
191
    {
192
       this.parserName = parserName;
193
    }
194

    
195

    
196
  /**
197
   * Method put the search result set into out printerwriter
198
   * @param resoponse the return response
199
   * @param out the output printer
200
   * @param params the paratermer hashtable
201
   * @param user the user name (it maybe different to the one in param)
202
   * @param groups the group array
203
   * @param sessionid  the sessionid
204
   */
205
  public void findDocuments(HttpServletResponse response,
206
                                       PrintWriter out, Hashtable params,
207
                                       String user, String[] groups,
208
                                       String sessionid)
209
  {
210
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
211
               .booleanValue();
212
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
213

    
214
  }
215

    
216

    
217
    /**
218
     * Method put the search result set into out printerwriter
219
     * @param resoponse the return response
220
     * @param out the output printer
221
     * @param params the paratermer hashtable
222
     * @param user the user name (it maybe different to the one in param)
223
     * @param groups the group array
224
     * @param sessionid  the sessionid
225
     */
226
    public void findDocuments(HttpServletResponse response,
227
                                         PrintWriter out, Hashtable params,
228
                                         String user, String[] groups,
229
                                         String sessionid, boolean useXMLIndex)
230
    {
231
      // get query and qformat
232
      String xmlquery = ((String[])params.get("query"))[0];
233
      xmlquery = transformQuery(xmlquery);
234
      MetaCatUtil.debugMessage("xmlquery: " + xmlquery, 30);
235
      String qformat = ((String[])params.get("qformat"))[0];
236
      MetaCatUtil.debugMessage("qformat: " + qformat, 30);
237

    
238
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
239
      {
240
        //xml format
241
        response.setContentType("text/xml");
242
        createResultDocument(xmlquery, out, user, groups, useXMLIndex);
243
      }//if
244
      else
245
      {
246
        //knb format, in this case we will get whole result and sent it out
247
        response.setContentType("text/html");
248
        PrintWriter nonout = null;
249
        StringBuffer xml =
250
              createResultDocument(xmlquery, nonout, user, groups, useXMLIndex);
251
        //transfer the xml to html
252
        try
253
        {
254

    
255
         DBTransform trans = new DBTransform();
256
         response.setContentType("text/html");
257
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
258
                                 "-//W3C//HTML//EN", qformat, out, params,
259
                                 sessionid);
260

    
261
        }
262
        catch(Exception e)
263
        {
264
         MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
265
                                +e.getMessage(), 30);
266
         }
267

    
268
      }//else
269

    
270
    }
271

    
272
  /*
273
   * Transforms a hashtable of documents to an xml or html result and sent
274
   * the content to outputstream. Keep going untill hastable is empty. stop it.   *
275
   */
276
  private StringBuffer createResultDocument(String xmlquery, PrintWriter out,
277
                                            String user, String[] groups,
278
                                            boolean useXMLIndex)
279
  {
280
    DBConnection dbconn = null;
281
    int serialNumber = -1;
282
    StringBuffer resultset = new StringBuffer();
283
    resultset.append("<?xml version=\"1.0\"?>\n");
284
    resultset.append("<resultset>\n");
285
    resultset.append("  <query>" + xmlquery + "</query>");
286
    // sent query part out
287
    if (out != null)
288
    {
289
      out.println(resultset.toString());
290
    }
291
    try
292
    {
293
      // Get the XML query and covert it into a SQL statment
294
      QuerySpecification qspec = new QuerySpecification(xmlquery,
295
                   parserName, MetaCatUtil.getOption("accNumSeparator"));
296
      //checkout the dbconnection
297
      dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
298
      serialNumber = dbconn.getCheckOutSerialNumber();
299

    
300
      //print out the search result
301
      // search the doc list
302
      resultset = findResultDoclist(qspec, resultset, out, user, groups,
303
                                    dbconn, useXMLIndex);
304

    
305

    
306
    }//try
307
    catch (IOException ioe)
308
    {
309
       MetaCatUtil.debugMessage("IO error in DBQuery.findDocuments:", 30);
310
       MetaCatUtil.debugMessage(ioe.getMessage(), 30);
311

    
312
    }
313
    catch (SQLException e)
314
    {
315
      MetaCatUtil.debugMessage("SQL Error in DBQuery.findDocuments: "
316
                   + e.getMessage(), 30);
317
    }
318
    catch (Exception ee)
319
    {
320
      MetaCatUtil.debugMessage("Exception in DBQuery.findDocuments: "
321
                   + ee.getMessage(), 30);
322
    }
323
    finally
324
    {
325
       DBConnectionPool.returnDBConnection(dbconn, serialNumber);
326
    }//finally
327
    String closeRestultset = "</resultset>";
328
    resultset.append(closeRestultset);
329
    if (out != null)
330
    {
331
      out.println(closeRestultset);
332
    }
333
    return resultset;
334
  }//createResultDocuments
335

    
336

    
337

    
338
    /*
339
     * Find the doc list which match the query
340
     */
341
    private StringBuffer findResultDoclist(QuerySpecification qspec,
342
                                      StringBuffer resultsetBuffer,
343
                                      PrintWriter out,
344
                                      String user, String[]groups,
345
                                      DBConnection dbconn, boolean useXMLIndex )
346
                                      throws Exception
347
    {
348
      int offset = 1;
349
      // this is a hack for offset
350
      if (out == null)
351
      {
352
        // for html page, we put everything into one page
353
        offset = 500000;
354
      }
355
      else
356
      {
357
          offset =
358
              (new Integer(MetaCatUtil.getOption("resultsetsize"))).intValue();
359
      }
360
      int count = 0;
361
      int index = 0;
362
      Hashtable docListResult = new Hashtable();
363
      PreparedStatement pstmt = null;
364
      String docid = null;
365
      String docname = null;
366
      String doctype = null;
367
      String createDate = null;
368
      String updateDate = null;
369
      StringBuffer document = null;
370
      int rev = 0;
371
      String query = qspec.printSQL(useXMLIndex);
372
      String ownerQuery = getOwnerQuery(user);
373
      MetaCatUtil.debugMessage("query: " + query, 30);
374
      //MetaCatUtil.debugMessage("query: "+ownerQuery, 30);
375
      // if query is not the owner query, we need to check the permission
376
      // otherwise we don't need (owner has all permission by default)
377
      if (!query.equals(ownerQuery))
378
      {
379
        // set user name and group
380
        qspec.setUserName(user);
381
        qspec.setGroup(groups);
382
        // Get access query
383
        String accessQuery = qspec.getAccessQuery();
384
        query = query + accessQuery;
385
        MetaCatUtil.debugMessage(" final query: " + query, 30);
386
      }
387

    
388
      double startTime = System.currentTimeMillis() / 1000;
389
      pstmt = dbconn.prepareStatement(query);
390

    
391
      // Execute the SQL query using the JDBC connection
392
      pstmt.execute();
393
      ResultSet rs = pstmt.getResultSet();
394
      double queryExecuteTime = System.currentTimeMillis() / 1000;
395
      MetaCatUtil.debugMessage("Time for execute query: "
396
                    + (queryExecuteTime - startTime), 30);
397
      boolean tableHasRows = rs.next();
398
      while (tableHasRows)
399
      {
400
        docid = rs.getString(1).trim();
401
        docname = rs.getString(2);
402
        doctype = rs.getString(3);
403
        createDate = rs.getString(4);
404
        updateDate = rs.getString(5);
405
        rev = rs.getInt(6);
406

    
407
        // if there are returndocs to match, backtracking can be performed
408
        // otherwise, just return the document that was hit
409
        Vector returndocVec = qspec.getReturnDocList();
410
         if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
411
                        && !qspec.isPercentageSearch())
412
        {
413
           MetaCatUtil.debugMessage("Back tracing now...", 20);
414
           String sep = MetaCatUtil.getOption("accNumSeparator");
415
           StringBuffer btBuf = new StringBuffer();
416
           btBuf.append("select docid from xml_relation where ");
417

    
418
           //build the doctype list for the backtracking sql statement
419
           btBuf.append("packagetype in (");
420
           for (int i = 0; i < returndocVec.size(); i++)
421
           {
422
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
423
             if (i != (returndocVec.size() - 1))
424
             {
425
                btBuf.append(", ");
426
              }
427
            }
428
            btBuf.append(") ");
429
            btBuf.append("and (subject like '");
430
            btBuf.append(docid).append("'");
431
            btBuf.append("or object like '");
432
            btBuf.append(docid).append("')");
433

    
434
            PreparedStatement npstmt = dbconn.prepareStatement(btBuf.toString());
435
            //should incease usage count
436
            dbconn.increaseUsageCount(1);
437
            npstmt.execute();
438
            ResultSet btrs = npstmt.getResultSet();
439
            boolean hasBtRows = btrs.next();
440
            while (hasBtRows)
441
            {
442
               //there was a backtrackable document found
443
               DocumentImpl xmldoc = null;
444
               String packageDocid = btrs.getString(1);
445
               MetaCatUtil.debugMessage("Getting document for docid: "
446
                                         + packageDocid, 40);
447
                try
448
                {
449
                    //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not
450
                    // needed here
451
                    // xmldoc = new DocumentImpl(dbconn, packageDocid);
452
                    //  thus use the following to get the doc info only
453
                    //  xmldoc = new DocumentImpl(dbconn);
454
                    xmldoc = new DocumentImpl(packageDocid, false);
455
                    if (xmldoc == null)
456
                    {
457
                       MetaCatUtil.debugMessage("Document was null for: "
458
                                                + packageDocid, 50);
459
                    }
460
                }
461
                catch (Exception e)
462
                {
463
                    System.out.println("Error getting document in "
464
                                       + "DBQuery.findDocuments: "
465
                                       + e.getMessage());
466
                }
467

    
468
                String docid_org = xmldoc.getDocID();
469
                if (docid_org == null)
470
                {
471
                   MetaCatUtil.debugMessage("Docid_org was null.", 40);
472
                   //continue;
473
                }
474
                docid = docid_org.trim();
475
                docname = xmldoc.getDocname();
476
                doctype = xmldoc.getDoctype();
477
                createDate = xmldoc.getCreateDate();
478
                updateDate = xmldoc.getUpdateDate();
479
                rev = xmldoc.getRev();
480
                document = new StringBuffer();
481

    
482
                String completeDocid = docid
483
                                + MetaCatUtil.getOption("accNumSeparator");
484
                completeDocid += rev;
485
                document.append("<docid>").append(completeDocid);
486
                document.append("</docid>");
487
                if (docname != null)
488
                {
489
                  document.append("<docname>" + docname + "</docname>");
490
                }
491
                if (doctype != null)
492
                {
493
                  document.append("<doctype>" + doctype + "</doctype>");
494
                }
495
                if (createDate != null)
496
                {
497
                 document.append("<createdate>" + createDate + "</createdate>");
498
                }
499
                if (updateDate != null)
500
                {
501
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
502
                }
503
                // Store the document id and the root node id
504
                docListResult.put(docid, (String) document.toString());
505
                count++;
506

    
507

    
508
                // Get the next package document linked to our hit
509
                hasBtRows = btrs.next();
510
              }//while
511
              npstmt.close();
512
              btrs.close();
513
        }
514
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
515
        {
516

    
517
           document = new StringBuffer();
518

    
519
           String completeDocid = docid
520
                            + MetaCatUtil.getOption("accNumSeparator");
521
           completeDocid += rev;
522
           document.append("<docid>").append(completeDocid).append("</docid>");
523
           if (docname != null)
524
           {
525
               document.append("<docname>" + docname + "</docname>");
526
            }
527
            if (doctype != null)
528
            {
529
               document.append("<doctype>" + doctype + "</doctype>");
530
            }
531
            if (createDate != null)
532
            {
533
                document.append("<createdate>" + createDate + "</createdate>");
534
             }
535
             if (updateDate != null)
536
             {
537
               document.append("<updatedate>" + updateDate + "</updatedate>");
538
             }
539
              // Store the document id and the root node id
540
              docListResult.put(docid, (String) document.toString());
541
              count++;
542

    
543

    
544
        }//else
545
        // when doclist reached the offset number, send out doc list and empty
546
        // the hash table
547
        if (count == offset)
548
        {
549
          //reset count
550
          count = 0;
551
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
552
                              user, groups,dbconn, useXMLIndex);
553
          // reset docListResult
554
          docListResult = new Hashtable();
555

    
556
        }
557
       // Advance to the next record in the cursor
558
       tableHasRows = rs.next();
559
     }//while
560
     rs.close();
561
     pstmt.close();
562
     //if docListResult is not empty, it need to be sent.
563
     if (!docListResult.isEmpty())
564
     {
565
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
566
                              user, groups,dbconn, useXMLIndex);
567
     }
568
     double docListTime = System.currentTimeMillis() / 1000;
569
     MetaCatUtil.debugMessage("prepare docid list time: "
570
                    + (docListTime - queryExecuteTime), 30);
571

    
572
     return resultsetBuffer;
573
    }//findReturnDoclist
574

    
575

    
576
    /*
577
     * Send completed search hashtable(part of reulst)to output stream
578
     * and buffer into a buffer stream
579
     */
580
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
581
                                           StringBuffer resultset,
582
                                           PrintWriter out, Hashtable partOfDoclist,
583
                                           String user, String[]groups,
584
                                       DBConnection dbconn, boolean useXMLIndex)
585
                                       throws Exception
586
   {
587
     //add return field
588
     partOfDoclist = addRetrunfield(partOfDoclist, qspec, user, groups,
589
                                        dbconn, useXMLIndex );
590
     //add relationship part part docid list
591
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
592
     // send the completed search item to output and store it in a buffer
593
     String key = null;
594
     String element = null;
595
     Enumeration keys = partOfDoclist.keys();
596
     while (keys.hasMoreElements())
597
     {
598
           key = (String) keys.nextElement();
599
           element = (String)partOfDoclist.get(key);
600
           // A string with element
601
           String xmlElement = "  <document>" + element + "</document>";
602
           //send single element to output
603
           if (out != null)
604
           {
605
             out.println(xmlElement);
606
           }
607
           resultset.append(xmlElement);
608
      }//while
609

    
610
      return resultset;
611
   }
612

    
613

    
614
    /*
615
     * A method to add return field to return doclist hash table
616
     */
617
    private Hashtable addRetrunfield(Hashtable docListResult,
618
                                      QuerySpecification qspec,
619
                                      String user, String[]groups,
620
                                      DBConnection dbconn, boolean useXMLIndex )
621
                                      throws Exception
622
    {
623
      PreparedStatement pstmt = null;
624
      ResultSet rs = null;
625
      String docid = null;
626
      String fieldname = null;
627
      String fielddata = null;
628
      String relation = null;
629

    
630
      if (qspec.containsExtendedSQL())
631
      {
632
        qspec.setUserName(user);
633
        qspec.setGroup(groups);
634
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
635
        Vector results = new Vector();
636
        Enumeration keylist = docListResult.keys();
637
        StringBuffer doclist = new StringBuffer();
638
        Vector parentidList = new Vector();
639
        Hashtable returnFieldValue = new Hashtable();
640
        while (keylist.hasMoreElements())
641
        {
642
          doclist.append("'");
643
          doclist.append((String) keylist.nextElement());
644
          doclist.append("',");
645
        }
646
        if (doclist.length() > 0)
647
        {
648
          Hashtable controlPairs = new Hashtable();
649
          double extendedQueryStart = System.currentTimeMillis() / 1000;
650
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
651
          // check if user has permission to see the return field data
652
          String accessControlSQL =
653
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
654
          pstmt = dbconn.prepareStatement(accessControlSQL);
655
          //increase dbconnection usage count
656
          dbconn.increaseUsageCount(1);
657
          pstmt.execute();
658
          rs = pstmt.getResultSet();
659
          boolean tableHasRows = rs.next();
660
          while (tableHasRows)
661
          {
662
            long startNodeId = rs.getLong(1);
663
            long endNodeId = rs.getLong(2);
664
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
665
            tableHasRows = rs.next();
666
          }
667

    
668
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
669
           MetaCatUtil.debugMessage( "Time for execute access extended query: "
670
                          + (extendedAccessQueryEnd - extendedQueryStart),30);
671

    
672
           String extendedQuery =
673
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
674
           MetaCatUtil.debugMessage("Extended query: " + extendedQuery, 30);
675
           pstmt = dbconn.prepareStatement(extendedQuery);
676
           //increase dbconnection usage count
677
           dbconn.increaseUsageCount(1);
678
           pstmt.execute();
679
           rs = pstmt.getResultSet();
680
           double extendedQueryEnd = System.currentTimeMillis() / 1000;
681
           MetaCatUtil.debugMessage("Time for execute extended query: "
682
                           + (extendedQueryEnd - extendedQueryStart), 30);
683
           tableHasRows = rs.next();
684
           while (tableHasRows)
685
           {
686
               ReturnFieldValue returnValue = new ReturnFieldValue();
687
               docid = rs.getString(1).trim();
688
               fieldname = rs.getString(2);
689
               fielddata = rs.getString(3);
690
               fielddata = MetaCatUtil.normalize(fielddata);
691
               String parentId = rs.getString(4);
692
               StringBuffer value = new StringBuffer();
693
               if (!containsKey(parentidList, parentId))
694
               {
695
                  // don't need to merger nodedata
696
                  value.append("<param name=\"");
697
                  value.append(fieldname);
698
                  value.append("\">");
699
                  value.append(fielddata);
700
                  value.append("</param>");
701
                  //set returnvalue
702
                  returnValue.setDocid(docid);
703
                  returnValue.setFieldValue(fielddata);
704
                  returnValue.setXMLFieldValue(value.toString());
705
                  // Store it in hastable
706
                  putInArray(parentidList, parentId, returnValue);
707
                }
708
                else
709
                {
710
                  // need to merge nodedata if they have same parent id and
711
                  // node type is text
712
                  fielddata = (String) ((ReturnFieldValue) getArrayValue(
713
                                    parentidList, parentId)).getFieldValue()
714
                                    + fielddata;
715
                  value.append("<param name=\"");
716
                  value.append(fieldname);
717
                  value.append("\">");
718
                  value.append(fielddata);
719
                  value.append("</param>");
720
                  returnValue.setDocid(docid);
721
                  returnValue.setFieldValue(fielddata);
722
                  returnValue.setXMLFieldValue(value.toString());
723
                  // remove the old return value from paretnidList
724
                  parentidList.remove(parentId);
725
                  // store the new return value in parentidlit
726
                  putInArray(parentidList, parentId, returnValue);
727
                }
728
              tableHasRows = rs.next();
729
            }//while
730
            rs.close();
731
            pstmt.close();
732

    
733
            // put the merger node data info into doclistReult
734
            Enumeration xmlFieldValue = (getElements(parentidList)).elements();
735
            while (xmlFieldValue.hasMoreElements())
736
            {
737
              ReturnFieldValue object =
738
                  (ReturnFieldValue) xmlFieldValue.nextElement();
739
              docid = object.getDocid();
740
              if (docListResult.containsKey(docid))
741
              {
742
                 String removedelement = (String) docListResult.remove(docid);
743
                 docListResult.
744
                         put(docid, removedelement+ object.getXMLFieldValue());
745
              }
746
              else
747
              {
748
                docListResult.put(docid, object.getXMLFieldValue());
749
               }
750
             }//while
751
             double docListResultEnd = System.currentTimeMillis() / 1000;
752
             MetaCatUtil.debugMessage("Time for prepare doclistresult after"
753
                                       + " execute extended query: "
754
                                       + (docListResultEnd - extendedQueryEnd),
755
                                      30);
756

    
757
              // get attribures return
758
              docListResult = getAttributeValueForReturn(qspec,
759
                            docListResult, doclist.toString(), useXMLIndex);
760
       }//if doclist lenght is great than zero
761

    
762
     }//if has extended query
763

    
764
      return docListResult;
765
    }//addReturnfield
766

    
767
    /*
768
    * A method to add relationship to return doclist hash table
769
    */
770
   private Hashtable addRelationship(Hashtable docListResult,
771
                                     QuerySpecification qspec,
772
                                     DBConnection dbconn, boolean useXMLIndex )
773
                                     throws Exception
774
  {
775
    PreparedStatement pstmt = null;
776
    ResultSet rs = null;
777
    StringBuffer document = null;
778
    double startRelation = System.currentTimeMillis() / 1000;
779
    Enumeration docidkeys = docListResult.keys();
780
    while (docidkeys.hasMoreElements())
781
    {
782
      //String connstring =
783
      // "metacat://"+util.getOption("server")+"?docid=";
784
      String connstring = "%docid=";
785
      String docidkey = (String) docidkeys.nextElement();
786
      pstmt = dbconn.prepareStatement(QuerySpecification
787
                      .printRelationSQL(docidkey));
788
      pstmt.execute();
789
      rs = pstmt.getResultSet();
790
      boolean tableHasRows = rs.next();
791
      while (tableHasRows)
792
      {
793
        String sub = rs.getString(1);
794
        String rel = rs.getString(2);
795
        String obj = rs.getString(3);
796
        String subDT = rs.getString(4);
797
        String objDT = rs.getString(5);
798

    
799
        document = new StringBuffer();
800
        document.append("<triple>");
801
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
802
        document.append("</subject>");
803
        if (subDT != null)
804
        {
805
          document.append("<subjectdoctype>").append(subDT);
806
          document.append("</subjectdoctype>");
807
        }
808
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
809
        document.append("</relationship>");
810
        document.append("<object>").append(MetaCatUtil.normalize(obj));
811
        document.append("</object>");
812
        if (objDT != null)
813
        {
814
          document.append("<objectdoctype>").append(objDT);
815
          document.append("</objectdoctype>");
816
        }
817
        document.append("</triple>");
818

    
819
        String removedelement = (String) docListResult.remove(docidkey);
820
        docListResult.put(docidkey, removedelement+ document.toString());
821
        tableHasRows = rs.next();
822
      }//while
823
      rs.close();
824
      pstmt.close();
825
    }//while
826
    double endRelation = System.currentTimeMillis() / 1000;
827
    MetaCatUtil.debugMessage("Time for adding relation to docListResult: "
828
                             + (endRelation - startRelation), 30);
829

    
830
    return docListResult;
831
  }//addRelation
832

    
833
  /**
834
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
835
   * string as a param instead of a hashtable.
836
   *
837
   * @param xmlquery a string representing a query.
838
   */
839
   private  String transformQuery(String xmlquery)
840
   {
841
     xmlquery = xmlquery.trim();
842
     int index = xmlquery.indexOf("?>");
843
     if (index != -1)
844
     {
845
       return xmlquery.substring(index + 2, xmlquery.length());
846
     }
847
     else
848
     {
849
       return xmlquery;
850
     }
851
   }
852

    
853

    
854
    /*
855
     * A method to search if Vector contains a particular key string
856
     */
857
    private boolean containsKey(Vector parentidList, String parentId)
858
    {
859

    
860
        Vector tempVector = null;
861

    
862
        for (int count = 0; count < parentidList.size(); count++) {
863
            tempVector = (Vector) parentidList.get(count);
864
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return false; }
865
        }
866
        return false;
867
    }
868

    
869
    /*
870
     * A method to put key and value in Vector
871
     */
872
    private void putInArray(Vector parentidList, String key,
873
            ReturnFieldValue value)
874
    {
875

    
876
        Vector tempVector = null;
877

    
878
        for (int count = 0; count < parentidList.size(); count++) {
879
            tempVector = (Vector) parentidList.get(count);
880

    
881
            if (key.compareTo((String) tempVector.get(0)) == 0) {
882
                tempVector.remove(1);
883
                tempVector.add(1, value);
884
                return;
885
            }
886
        }
887

    
888
        tempVector = new Vector();
889
        tempVector.add(0, key);
890
        tempVector.add(1, value);
891
        parentidList.add(tempVector);
892
        return;
893
    }
894

    
895
    /*
896
     * A method to get value in Vector given a key
897
     */
898
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
899
    {
900

    
901
        Vector tempVector = null;
902

    
903
        for (int count = 0; count < parentidList.size(); count++) {
904
            tempVector = (Vector) parentidList.get(count);
905

    
906
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
907
                    .get(1); }
908
        }
909
        return null;
910
    }
911

    
912
    /*
913
     * A method to get enumeration of all values in Vector
914
     */
915
    private Vector getElements(Vector parentidList)
916
    {
917
        Vector enum = new Vector();
918
        Vector tempVector = null;
919

    
920
        for (int count = 0; count < parentidList.size(); count++) {
921
            tempVector = (Vector) parentidList.get(count);
922

    
923
            enum.add(tempVector.get(1));
924
        }
925
        return enum;
926
    }
927

    
928
    /*
929
     * A method to return search result after running a query which return
930
     * field have attribue
931
     */
932
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
933
            Hashtable docInformationList, String docList, boolean useXMLIndex)
934
    {
935
        StringBuffer XML = null;
936
        String sql = null;
937
        DBConnection dbconn = null;
938
        PreparedStatement pstmt = null;
939
        ResultSet rs = null;
940
        int serialNumber = -1;
941
        boolean tableHasRows = false;
942

    
943
        //check the parameter
944
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
945

    
946
        // if has attribute as return field
947
        if (squery.containAttributeReturnField()) {
948
            sql = squery.printAttributeQuery(docList, useXMLIndex);
949
            try {
950
                dbconn = DBConnectionPool
951
                        .getDBConnection("DBQuery.getAttributeValue");
952
                serialNumber = dbconn.getCheckOutSerialNumber();
953
                pstmt = dbconn.prepareStatement(sql);
954
                pstmt.execute();
955
                rs = pstmt.getResultSet();
956
                tableHasRows = rs.next();
957
                while (tableHasRows) {
958
                    String docid = rs.getString(1).trim();
959
                    String fieldname = rs.getString(2);
960
                    String fielddata = rs.getString(3);
961
                    String attirbuteName = rs.getString(4);
962
                    XML = new StringBuffer();
963

    
964
                    XML.append("<param name=\"");
965
                    XML.append(fieldname);
966
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
967
                    XML.append(attirbuteName);
968
                    XML.append("\">");
969
                    XML.append(fielddata);
970
                    XML.append("</param>");
971
                    tableHasRows = rs.next();
972

    
973
                    if (docInformationList.containsKey(docid)) {
974
                        String removedelement = (String) docInformationList
975
                                .remove(docid);
976
                        docInformationList.put(docid, removedelement
977
                                + XML.toString());
978
                    } else {
979
                        docInformationList.put(docid, XML.toString());
980
                    }
981
                }//while
982
                rs.close();
983
                pstmt.close();
984
            } catch (Exception se) {
985
                MetaCatUtil.debugMessage(
986
                        "Error in DBQuery.getAttributeValue1: "
987
                                + se.getMessage(), 30);
988
            } finally {
989
                try {
990
                    pstmt.close();
991
                }//try
992
                catch (SQLException sqlE) {
993
                    MetaCatUtil.debugMessage(
994
                            "Error in DBQuery.getAttributeValue2: "
995
                                    + sqlE.getMessage(), 30);
996
                }//catch
997
                finally {
998
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
999
                }//finally
1000
            }//finally
1001
        }//if
1002
        return docInformationList;
1003

    
1004
    }
1005

    
1006
    /*
1007
     * A method to create a query to get owner's docid list
1008
     */
1009
    private String getOwnerQuery(String owner)
1010
    {
1011
        if (owner != null) {
1012
            owner = owner.toLowerCase();
1013
        }
1014
        StringBuffer self = new StringBuffer();
1015

    
1016
        self.append("SELECT docid,docname,doctype,");
1017
        self.append("date_created, date_updated, rev ");
1018
        self.append("FROM xml_documents WHERE docid IN (");
1019
        self.append("(");
1020
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1021
        self.append("nodedata LIKE '%%%' ");
1022
        self.append(") \n");
1023
        self.append(") ");
1024
        self.append(" AND (");
1025
        self.append(" lower(user_owner) = '" + owner + "'");
1026
        self.append(") ");
1027
        return self.toString();
1028
    }
1029

    
1030
    /**
1031
     * format a structured query as an XML document that conforms to the
1032
     * pathquery.dtd and is appropriate for submission to the DBQuery
1033
     * structured query engine
1034
     *
1035
     * @param params The list of parameters that should be included in the
1036
     *            query
1037
     */
1038
    public static String createSQuery(Hashtable params)
1039
    {
1040
        StringBuffer query = new StringBuffer();
1041
        Enumeration elements;
1042
        Enumeration keys;
1043
        String filterDoctype = null;
1044
        String casesensitive = null;
1045
        String searchmode = null;
1046
        Object nextkey;
1047
        Object nextelement;
1048
        //add the xml headers
1049
        query.append("<?xml version=\"1.0\"?>\n");
1050
        query.append("<pathquery version=\"1.2\">\n");
1051

    
1052

    
1053

    
1054
        if (params.containsKey("meta_file_id")) {
1055
            query.append("<meta_file_id>");
1056
            query.append(((String[]) params.get("meta_file_id"))[0]);
1057
            query.append("</meta_file_id>");
1058
        }
1059

    
1060
        if (params.containsKey("returndoctype")) {
1061
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1062
            for (int i = 0; i < returnDoctypes.length; i++) {
1063
                String doctype = (String) returnDoctypes[i];
1064

    
1065
                if (!doctype.equals("any") && !doctype.equals("ANY")
1066
                        && !doctype.equals("")) {
1067
                    query.append("<returndoctype>").append(doctype);
1068
                    query.append("</returndoctype>");
1069
                }
1070
            }
1071
        }
1072

    
1073
        if (params.containsKey("filterdoctype")) {
1074
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1075
            for (int i = 0; i < filterDoctypes.length; i++) {
1076
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1077
                query.append("</filterdoctype>");
1078
            }
1079
        }
1080

    
1081
        if (params.containsKey("returnfield")) {
1082
            String[] returnfield = ((String[]) params.get("returnfield"));
1083
            for (int i = 0; i < returnfield.length; i++) {
1084
                query.append("<returnfield>").append(returnfield[i]);
1085
                query.append("</returnfield>");
1086
            }
1087
        }
1088

    
1089
        if (params.containsKey("owner")) {
1090
            String[] owner = ((String[]) params.get("owner"));
1091
            for (int i = 0; i < owner.length; i++) {
1092
                query.append("<owner>").append(owner[i]);
1093
                query.append("</owner>");
1094
            }
1095
        }
1096

    
1097
        if (params.containsKey("site")) {
1098
            String[] site = ((String[]) params.get("site"));
1099
            for (int i = 0; i < site.length; i++) {
1100
                query.append("<site>").append(site[i]);
1101
                query.append("</site>");
1102
            }
1103
        }
1104

    
1105
        //allows the dynamic switching of boolean operators
1106
        if (params.containsKey("operator")) {
1107
            query.append("<querygroup operator=\""
1108
                    + ((String[]) params.get("operator"))[0] + "\">");
1109
        } else { //the default operator is UNION
1110
            query.append("<querygroup operator=\"UNION\">");
1111
        }
1112

    
1113
        if (params.containsKey("casesensitive")) {
1114
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1115
        } else {
1116
            casesensitive = "false";
1117
        }
1118

    
1119
        if (params.containsKey("searchmode")) {
1120
            searchmode = ((String[]) params.get("searchmode"))[0];
1121
        } else {
1122
            searchmode = "contains";
1123
        }
1124

    
1125
        //anyfield is a special case because it does a
1126
        //free text search. It does not have a <pathexpr>
1127
        //tag. This allows for a free text search within the structured
1128
        //query. This is useful if the INTERSECT operator is used.
1129
        if (params.containsKey("anyfield")) {
1130
            String[] anyfield = ((String[]) params.get("anyfield"));
1131
            //allow for more than one value for anyfield
1132
            for (int i = 0; i < anyfield.length; i++) {
1133
                if (!anyfield[i].equals("")) {
1134
                    query.append("<queryterm casesensitive=\"" + casesensitive
1135
                            + "\" " + "searchmode=\"" + searchmode
1136
                            + "\"><value>" + anyfield[i]
1137
                            + "</value></queryterm>");
1138
                }
1139
            }
1140
        }
1141

    
1142
        //this while loop finds the rest of the parameters
1143
        //and attempts to query for the field specified
1144
        //by the parameter.
1145
        elements = params.elements();
1146
        keys = params.keys();
1147
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1148
            nextkey = keys.nextElement();
1149
            nextelement = elements.nextElement();
1150

    
1151
            //make sure we aren't querying for any of these
1152
            //parameters since the are already in the query
1153
            //in one form or another.
1154
            Vector ignoredParams = new Vector();
1155
            ignoredParams.add("returndoctype");
1156
            ignoredParams.add("filterdoctype");
1157
            ignoredParams.add("action");
1158
            ignoredParams.add("qformat");
1159
            ignoredParams.add("anyfield");
1160
            ignoredParams.add("returnfield");
1161
            ignoredParams.add("owner");
1162
            ignoredParams.add("site");
1163
            ignoredParams.add("operator");
1164
            ignoredParams.add("sessionid");
1165

    
1166
            // Also ignore parameters listed in the properties file
1167
            // so that they can be passed through to stylesheets
1168
            String paramsToIgnore = MetaCatUtil
1169
                    .getOption("query.ignored.params");
1170
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1171
            while (st.hasMoreTokens()) {
1172
                ignoredParams.add(st.nextToken());
1173
            }
1174
            if (!ignoredParams.contains(nextkey.toString())) {
1175
                //allow for more than value per field name
1176
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1177
                    if (!((String[]) nextelement)[i].equals("")) {
1178
                        query.append("<queryterm casesensitive=\""
1179
                                + casesensitive + "\" " + "searchmode=\""
1180
                                + searchmode + "\">" + "<value>" +
1181
                                //add the query value
1182
                                ((String[]) nextelement)[i]
1183
                                + "</value><pathexpr>" +
1184
                                //add the path to query by
1185
                                nextkey.toString() + "</pathexpr></queryterm>");
1186
                    }
1187
                }
1188
            }
1189
        }
1190
        query.append("</querygroup></pathquery>");
1191
        //append on the end of the xml and return the result as a string
1192
        return query.toString();
1193
    }
1194

    
1195
    /**
1196
     * format a simple free-text value query as an XML document that conforms
1197
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1198
     * structured query engine
1199
     *
1200
     * @param value the text string to search for in the xml catalog
1201
     * @param doctype the type of documents to include in the result set -- use
1202
     *            "any" or "ANY" for unfiltered result sets
1203
     */
1204
    public static String createQuery(String value, String doctype)
1205
    {
1206
        StringBuffer xmlquery = new StringBuffer();
1207
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1208
        xmlquery.append("<pathquery version=\"1.0\">");
1209

    
1210
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1211
            xmlquery.append("<returndoctype>");
1212
            xmlquery.append(doctype).append("</returndoctype>");
1213
        }
1214

    
1215
        xmlquery.append("<querygroup operator=\"UNION\">");
1216
        //chad added - 8/14
1217
        //the if statement allows a query to gracefully handle a null
1218
        //query. Without this if a nullpointerException is thrown.
1219
        if (!value.equals("")) {
1220
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1221
            xmlquery.append("searchmode=\"contains\">");
1222
            xmlquery.append("<value>").append(value).append("</value>");
1223
            xmlquery.append("</queryterm>");
1224
        }
1225
        xmlquery.append("</querygroup>");
1226
        xmlquery.append("</pathquery>");
1227

    
1228
        return (xmlquery.toString());
1229
    }
1230

    
1231
    /**
1232
     * format a simple free-text value query as an XML document that conforms
1233
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1234
     * structured query engine
1235
     *
1236
     * @param value the text string to search for in the xml catalog
1237
     */
1238
    public static String createQuery(String value)
1239
    {
1240
        return createQuery(value, "any");
1241
    }
1242

    
1243
    /**
1244
     * Check for "READ" permission on @docid for @user and/or @group from DB
1245
     * connection
1246
     */
1247
    private boolean hasPermission(String user, String[] groups, String docid)
1248
            throws SQLException, Exception
1249
    {
1250
        // Check for READ permission on @docid for @user and/or @groups
1251
        PermissionController controller = new PermissionController(docid);
1252
        return controller.hasPermission(user, groups,
1253
                AccessControlInterface.READSTRING);
1254
    }
1255

    
1256
    /**
1257
     * Get all docIds list for a data packadge
1258
     *
1259
     * @param dataPackageDocid, the string in docId field of xml_relation table
1260
     */
1261
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1262
    {
1263
        DBConnection dbConn = null;
1264
        int serialNumber = -1;
1265
        Vector docIdList = new Vector();//return value
1266
        PreparedStatement pStmt = null;
1267
        ResultSet rs = null;
1268
        String docIdInSubjectField = null;
1269
        String docIdInObjectField = null;
1270

    
1271
        // Check the parameter
1272
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1273

    
1274
        //the query stirng
1275
        String query = "SELECT subject, object from xml_relation where docId = ?";
1276
        try {
1277
            dbConn = DBConnectionPool
1278
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1279
            serialNumber = dbConn.getCheckOutSerialNumber();
1280
            pStmt = dbConn.prepareStatement(query);
1281
            //bind the value to query
1282
            pStmt.setString(1, dataPackageDocid);
1283

    
1284
            //excute the query
1285
            pStmt.execute();
1286
            //get the result set
1287
            rs = pStmt.getResultSet();
1288
            //process the result
1289
            while (rs.next()) {
1290
                //In order to get the whole docIds in a data packadge,
1291
                //we need to put the docIds of subject and object field in
1292
                // xml_relation
1293
                //into the return vector
1294
                docIdInSubjectField = rs.getString(1);//the result docId in
1295
                                                      // subject field
1296
                docIdInObjectField = rs.getString(2);//the result docId in
1297
                                                     // object field
1298

    
1299
                //don't put the duplicate docId into the vector
1300
                if (!docIdList.contains(docIdInSubjectField)) {
1301
                    docIdList.add(docIdInSubjectField);
1302
                }
1303

    
1304
                //don't put the duplicate docId into the vector
1305
                if (!docIdList.contains(docIdInObjectField)) {
1306
                    docIdList.add(docIdInObjectField);
1307
                }
1308
            }//while
1309
            //close the pStmt
1310
            pStmt.close();
1311
        }//try
1312
        catch (SQLException e) {
1313
            MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1314
                    + e.getMessage(), 30);
1315
        }//catch
1316
        finally {
1317
            try {
1318
                pStmt.close();
1319
            }//try
1320
            catch (SQLException ee) {
1321
                MetaCatUtil.debugMessage(
1322
                        "Error in getDocidListForDataPackage: "
1323
                                + ee.getMessage(), 30);
1324
            }//catch
1325
            finally {
1326
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1327
            }//fianlly
1328
        }//finally
1329
        return docIdList;
1330
    }//getCurrentDocidListForDataPackadge()
1331

    
1332
    /**
1333
     * Get all docIds list for a data packadge
1334
     *
1335
     * @param dataPackageDocid, the string in docId field of xml_relation table
1336
     */
1337
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1338
    {
1339

    
1340
        Vector docIdList = new Vector();//return value
1341
        Vector tripleList = null;
1342
        String xml = null;
1343

    
1344
        // Check the parameter
1345
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1346

    
1347
        try {
1348
            //initial a documentImpl object
1349
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocid);
1350
            //transfer to documentImpl object to string
1351
            xml = packageDocument.toString();
1352

    
1353
            //create a tripcollection object
1354
            TripleCollection tripleForPackage = new TripleCollection(
1355
                    new StringReader(xml));
1356
            //get the vetor of triples
1357
            tripleList = tripleForPackage.getCollection();
1358

    
1359
            for (int i = 0; i < tripleList.size(); i++) {
1360
                //put subject docid into docIdlist without duplicate
1361
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1362
                        .getSubject())) {
1363
                    //put subject docid into docIdlist
1364
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1365
                }
1366
                //put object docid into docIdlist without duplicate
1367
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1368
                        .getObject())) {
1369
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1370
                }
1371
            }//for
1372
        }//try
1373
        catch (Exception e) {
1374
            MetaCatUtil.debugMessage("Error in getOldVersionAllDocumentImpl: "
1375
                    + e.getMessage(), 30);
1376
        }//catch
1377

    
1378
        // return result
1379
        return docIdList;
1380
    }//getDocidListForPackageInXMLRevisions()
1381

    
1382
    /**
1383
     * Check if the docId is a data packadge id. If the id is a data packadage
1384
     * id, it should be store in the docId fields in xml_relation table. So we
1385
     * can use a query to get the entries which the docId equals the given
1386
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1387
     * it is.
1388
     *
1389
     * @param docId, the id need to be checked
1390
     */
1391
    private boolean isDataPackageId(String docId)
1392
    {
1393
        boolean result = false;
1394
        PreparedStatement pStmt = null;
1395
        ResultSet rs = null;
1396
        String query = "SELECT docId from xml_relation where docId = ?";
1397
        DBConnection dbConn = null;
1398
        int serialNumber = -1;
1399
        try {
1400
            dbConn = DBConnectionPool
1401
                    .getDBConnection("DBQuery.isDataPackageId");
1402
            serialNumber = dbConn.getCheckOutSerialNumber();
1403
            pStmt = dbConn.prepareStatement(query);
1404
            //bind the value to query
1405
            pStmt.setString(1, docId);
1406
            //execute the query
1407
            pStmt.execute();
1408
            rs = pStmt.getResultSet();
1409
            //process the result
1410
            if (rs.next()) //There are some records for the id in docId fields
1411
            {
1412
                result = true;//It is a data packadge id
1413
            }
1414
            pStmt.close();
1415
        }//try
1416
        catch (SQLException e) {
1417
            MetaCatUtil.debugMessage("Error in isDataPackageId: "
1418
                    + e.getMessage(), 30);
1419
        } finally {
1420
            try {
1421
                pStmt.close();
1422
            }//try
1423
            catch (SQLException ee) {
1424
                MetaCatUtil.debugMessage("Error in isDataPackageId: "
1425
                        + ee.getMessage(), 30);
1426
            }//catch
1427
            finally {
1428
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1429
            }//finally
1430
        }//finally
1431
        return result;
1432
    }//isDataPackageId()
1433

    
1434
    /**
1435
     * Check if the user has the permission to export data package
1436
     *
1437
     * @param conn, the connection
1438
     * @param docId, the id need to be checked
1439
     * @param user, the name of user
1440
     * @param groups, the user's group
1441
     */
1442
    private boolean hasPermissionToExportPackage(String docId, String user,
1443
            String[] groups) throws Exception
1444
    {
1445
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1446
        return DocumentImpl.hasReadPermission(user, groups, docId);
1447
    }
1448

    
1449
    /**
1450
     * Get the current Rev for a docid in xml_documents table
1451
     *
1452
     * @param docId, the id need to get version numb If the return value is -5,
1453
     *            means no value in rev field for this docid
1454
     */
1455
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1456
            throws SQLException
1457
    {
1458
        int rev = -5;
1459
        PreparedStatement pStmt = null;
1460
        ResultSet rs = null;
1461
        String query = "SELECT rev from xml_documents where docId = ?";
1462
        DBConnection dbConn = null;
1463
        int serialNumber = -1;
1464
        try {
1465
            dbConn = DBConnectionPool
1466
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1467
            serialNumber = dbConn.getCheckOutSerialNumber();
1468
            pStmt = dbConn.prepareStatement(query);
1469
            //bind the value to query
1470
            pStmt.setString(1, docId);
1471
            //execute the query
1472
            pStmt.execute();
1473
            rs = pStmt.getResultSet();
1474
            //process the result
1475
            if (rs.next()) //There are some records for rev
1476
            {
1477
                rev = rs.getInt(1);
1478
                ;//It is the version for given docid
1479
            } else {
1480
                rev = -5;
1481
            }
1482

    
1483
        }//try
1484
        catch (SQLException e) {
1485
            MetaCatUtil.debugMessage(
1486
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1487
                            + e.getMessage(), 30);
1488
            throw e;
1489
        }//catch
1490
        finally {
1491
            try {
1492
                pStmt.close();
1493
            }//try
1494
            catch (SQLException ee) {
1495
                MetaCatUtil.debugMessage(
1496
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1497
                                + ee.getMessage(), 30);
1498
            }//catch
1499
            finally {
1500
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1501
            }//finally
1502
        }//finally
1503
        return rev;
1504
    }//getCurrentRevFromXMLDoumentsTable
1505

    
1506
    /**
1507
     * put a doc into a zip output stream
1508
     *
1509
     * @param docImpl, docmentImpl object which will be sent to zip output
1510
     *            stream
1511
     * @param zipOut, zip output stream which the docImpl will be put
1512
     * @param packageZipEntry, the zip entry name for whole package
1513
     */
1514
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1515
            ZipOutputStream zipOut, String packageZipEntry)
1516
            throws ClassNotFoundException, IOException, SQLException,
1517
            McdbException, Exception
1518
    {
1519
        byte[] byteString = null;
1520
        ZipEntry zEntry = null;
1521

    
1522
        byteString = docImpl.toString().getBytes();
1523
        //use docId as the zip entry's name
1524
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1525
                + docImpl.getDocID());
1526
        zEntry.setSize(byteString.length);
1527
        zipOut.putNextEntry(zEntry);
1528
        zipOut.write(byteString, 0, byteString.length);
1529
        zipOut.closeEntry();
1530

    
1531
    }//addDocToZipOutputStream()
1532

    
1533
    /**
1534
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1535
     * only inlcudes current version. If a DocumentImple object couldn't find
1536
     * for a docid, then the String of this docid was added to vetor rather
1537
     * than DocumentImple object.
1538
     *
1539
     * @param docIdList, a vetor hold a docid list for a data package. In
1540
     *            docid, there is not version number in it.
1541
     */
1542

    
1543
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1544
            throws McdbException, Exception
1545
    {
1546
        //Connection dbConn=null;
1547
        Vector documentImplList = new Vector();
1548
        int rev = 0;
1549

    
1550
        // Check the parameter
1551
        if (docIdList.isEmpty()) { return documentImplList; }//if
1552

    
1553
        //for every docid in vector
1554
        for (int i = 0; i < docIdList.size(); i++) {
1555
            try {
1556
                //get newest version for this docId
1557
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1558
                        .elementAt(i));
1559

    
1560
                // There is no record for this docId in xml_documents table
1561
                if (rev == -5) {
1562
                    // Rather than put DocumentImple object, put a String
1563
                    // Object(docid)
1564
                    // into the documentImplList
1565
                    documentImplList.add((String) docIdList.elementAt(i));
1566
                    // Skip other code
1567
                    continue;
1568
                }
1569

    
1570
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1571
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1572

    
1573
                //create new documentImpl object
1574
                DocumentImpl documentImplObject = new DocumentImpl(
1575
                        docidPlusVersion);
1576
                //add them to vector
1577
                documentImplList.add(documentImplObject);
1578
            }//try
1579
            catch (Exception e) {
1580
                MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1581
                        + e.getMessage(), 30);
1582
                // continue the for loop
1583
                continue;
1584
            }
1585
        }//for
1586
        return documentImplList;
1587
    }
1588

    
1589
    /**
1590
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
1591
     * object couldn't find for a docid, then the String of this docid was
1592
     * added to vetor rather than DocumentImple object.
1593
     *
1594
     * @param docIdList, a vetor hold a docid list for a data package. In
1595
     *            docid, t here is version number in it.
1596
     */
1597
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
1598
    {
1599
        //Connection dbConn=null;
1600
        Vector documentImplList = new Vector();
1601
        String siteCode = null;
1602
        String uniqueId = null;
1603
        int rev = 0;
1604

    
1605
        // Check the parameter
1606
        if (docIdList.isEmpty()) { return documentImplList; }//if
1607

    
1608
        //for every docid in vector
1609
        for (int i = 0; i < docIdList.size(); i++) {
1610

    
1611
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1612

    
1613
            try {
1614
                //create new documentImpl object
1615
                DocumentImpl documentImplObject = new DocumentImpl(
1616
                        docidPlusVersion);
1617
                //add them to vector
1618
                documentImplList.add(documentImplObject);
1619
            }//try
1620
            catch (McdbDocNotFoundException notFoundE) {
1621
                MetaCatUtil.debugMessage(
1622
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1623
                                + notFoundE.getMessage(), 30);
1624
                // Rather than add a DocumentImple object into vetor, a String
1625
                // object
1626
                // - the doicd was added to the vector
1627
                documentImplList.add(docidPlusVersion);
1628
                // Continue the for loop
1629
                continue;
1630
            }//catch
1631
            catch (Exception e) {
1632
                MetaCatUtil.debugMessage(
1633
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1634
                                + e.getMessage(), 30);
1635
                // Continue the for loop
1636
                continue;
1637
            }//catch
1638

    
1639
        }//for
1640
        return documentImplList;
1641
    }//getOldVersionAllDocumentImple
1642

    
1643
    /**
1644
     * put a data file into a zip output stream
1645
     *
1646
     * @param docImpl, docmentImpl object which will be sent to zip output
1647
     *            stream
1648
     * @param zipOut, the zip output stream which the docImpl will be put
1649
     * @param packageZipEntry, the zip entry name for whole package
1650
     */
1651
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
1652
            ZipOutputStream zipOut, String packageZipEntry)
1653
            throws ClassNotFoundException, IOException, SQLException,
1654
            McdbException, Exception
1655
    {
1656
        byte[] byteString = null;
1657
        ZipEntry zEntry = null;
1658
        // this is data file; add file to zip
1659
        String filePath = MetaCatUtil.getOption("datafilepath");
1660
        if (!filePath.endsWith("/")) {
1661
            filePath += "/";
1662
        }
1663
        String fileName = filePath + docImpl.getDocID();
1664
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
1665
        zipOut.putNextEntry(zEntry);
1666
        FileInputStream fin = null;
1667
        try {
1668
            fin = new FileInputStream(fileName);
1669
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1670
            int b = fin.read(buf);
1671
            while (b != -1) {
1672
                zipOut.write(buf, 0, b);
1673
                b = fin.read(buf);
1674
            }//while
1675
            zipOut.closeEntry();
1676
        }//try
1677
        catch (IOException ioe) {
1678
            MetaCatUtil.debugMessage("There is an exception: "
1679
                    + ioe.getMessage(), 30);
1680
        }//catch
1681
    }//addDataFileToZipOutputStream()
1682

    
1683
    /**
1684
     * create a html summary for data package and put it into zip output stream
1685
     *
1686
     * @param docImplList, the documentImpl ojbects in data package
1687
     * @param zipOut, the zip output stream which the html should be put
1688
     * @param packageZipEntry, the zip entry name for whole package
1689
     */
1690
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
1691
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
1692
    {
1693
        StringBuffer htmlDoc = new StringBuffer();
1694
        ZipEntry zEntry = null;
1695
        byte[] byteString = null;
1696
        InputStream source;
1697
        DBTransform xmlToHtml;
1698

    
1699
        //create a DBTransform ojbect
1700
        xmlToHtml = new DBTransform();
1701
        //head of html
1702
        htmlDoc.append("<html><head></head><body>");
1703
        for (int i = 0; i < docImplList.size(); i++) {
1704
            // If this String object, this means it is missed data file
1705
            if ((((docImplList.elementAt(i)).getClass()).toString())
1706
                    .equals("class java.lang.String")) {
1707

    
1708
                htmlDoc.append("<a href=\"");
1709
                String dataFileid = (String) docImplList.elementAt(i);
1710
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1711
                htmlDoc.append("Data File: ");
1712
                htmlDoc.append(dataFileid).append("</a><br>");
1713
                htmlDoc.append("<br><hr><br>");
1714

    
1715
            }//if
1716
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
1717
                    .compareTo("BIN") != 0) { //this is an xml file so we can
1718
                                              // transform it.
1719
                //transform each file individually then concatenate all of the
1720
                //transformations together.
1721

    
1722
                //for metadata xml title
1723
                htmlDoc.append("<h2>");
1724
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
1725
                        .getDocID());
1726
                //htmlDoc.append(".");
1727
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
1728
                htmlDoc.append("</h2>");
1729
                //do the actual transform
1730
                StringWriter docString = new StringWriter();
1731
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
1732
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
1733
                        "-//W3C//HTML//EN", "html", docString);
1734
                htmlDoc.append(docString.toString());
1735
                htmlDoc.append("<br><br><hr><br><br>");
1736
            }//if
1737
            else { //this is a data file so we should link to it in the html
1738
                htmlDoc.append("<a href=\"");
1739
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
1740
                        .getDocID();
1741
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1742
                htmlDoc.append("Data File: ");
1743
                htmlDoc.append(dataFileid).append("</a><br>");
1744
                htmlDoc.append("<br><hr><br>");
1745
            }//else
1746
        }//for
1747
        htmlDoc.append("</body></html>");
1748
        byteString = htmlDoc.toString().getBytes();
1749
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
1750
        zEntry.setSize(byteString.length);
1751
        zipOut.putNextEntry(zEntry);
1752
        zipOut.write(byteString, 0, byteString.length);
1753
        zipOut.closeEntry();
1754
        //dbConn.close();
1755

    
1756
    }//addHtmlSummaryToZipOutputStream
1757

    
1758
    /**
1759
     * put a data packadge into a zip output stream
1760
     *
1761
     * @param docId, which the user want to put into zip output stream
1762
     * @param out, a servletoutput stream which the zip output stream will be
1763
     *            put
1764
     * @param user, the username of the user
1765
     * @param groups, the group of the user
1766
     */
1767
    public ZipOutputStream getZippedPackage(String docIdString,
1768
            ServletOutputStream out, String user, String[] groups,
1769
            String passWord) throws ClassNotFoundException, IOException,
1770
            SQLException, McdbException, NumberFormatException, Exception
1771
    {
1772
        ZipOutputStream zOut = null;
1773
        String elementDocid = null;
1774
        DocumentImpl docImpls = null;
1775
        //Connection dbConn = null;
1776
        Vector docIdList = new Vector();
1777
        Vector documentImplList = new Vector();
1778
        Vector htmlDocumentImplList = new Vector();
1779
        String packageId = null;
1780
        String rootName = "package";//the package zip entry name
1781

    
1782
        String docId = null;
1783
        int version = -5;
1784
        // Docid without revision
1785
        docId = MetaCatUtil.getDocIdFromString(docIdString);
1786
        // revision number
1787
        version = MetaCatUtil.getVersionFromString(docIdString);
1788

    
1789
        //check if the reqused docId is a data package id
1790
        if (!isDataPackageId(docId)) {
1791

    
1792
            /*
1793
             * Exception e = new Exception("The request the doc id "
1794
             * +docIdString+ " is not a data package id");
1795
             */
1796

    
1797
            //CB 1/6/03: if the requested docid is not a datapackage, we just
1798
            // zip
1799
            //up the single document and return the zip file.
1800
            if (!hasPermissionToExportPackage(docId, user, groups)) {
1801

    
1802
                Exception e = new Exception("User " + user
1803
                        + " does not have permission"
1804
                        + " to export the data package " + docIdString);
1805
                throw e;
1806
            }
1807

    
1808
            docImpls = new DocumentImpl(docId);
1809
            //checking if the user has the permission to read the documents
1810
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
1811
                    .getDocID())) {
1812
                zOut = new ZipOutputStream(out);
1813
                //if the docImpls is metadata
1814
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
1815
                    //add metadata into zip output stream
1816
                    addDocToZipOutputStream(docImpls, zOut, rootName);
1817
                }//if
1818
                else {
1819
                    //it is data file
1820
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
1821
                    htmlDocumentImplList.add(docImpls);
1822
                }//else
1823
            }//if
1824

    
1825
            zOut.finish(); //terminate the zip file
1826
            return zOut;
1827
        }
1828
        // Check the permission of user
1829
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
1830

    
1831
            Exception e = new Exception("User " + user
1832
                    + " does not have permission"
1833
                    + " to export the data package " + docIdString);
1834
            throw e;
1835
        } else //it is a packadge id
1836
        {
1837
            //store the package id
1838
            packageId = docId;
1839
            //get current version in database
1840
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
1841
            //If it is for current version (-1 means user didn't specify
1842
            // revision)
1843
            if ((version == -1) || version == currentVersion) {
1844
                //get current version number
1845
                version = currentVersion;
1846
                //get package zip entry name
1847
                //it should be docId.revsion.package
1848
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
1849
                        + version + MetaCatUtil.getOption("accNumSeparator")
1850
                        + "package";
1851
                //get the whole id list for data packadge
1852
                docIdList = getCurrentDocidListForDataPackage(packageId);
1853
                //get the whole documentImple object
1854
                documentImplList = getCurrentAllDocumentImpl(docIdList);
1855

    
1856
            }//if
1857
            else if (version > currentVersion || version < -1) {
1858
                throw new Exception("The user specified docid: " + docId + "."
1859
                        + version + " doesn't exist");
1860
            }//else if
1861
            else //for an old version
1862
            {
1863

    
1864
                rootName = docIdString
1865
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
1866
                //get the whole id list for data packadge
1867
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
1868

    
1869
                //get the whole documentImple object
1870
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
1871
            }//else
1872

    
1873
            // Make sure documentImplist is not empty
1874
            if (documentImplList.isEmpty()) { throw new Exception(
1875
                    "Couldn't find component for data package: " + packageId); }//if
1876

    
1877
            zOut = new ZipOutputStream(out);
1878
            //put every element into zip output stream
1879
            for (int i = 0; i < documentImplList.size(); i++) {
1880
                // if the object in the vetor is String, this means we couldn't
1881
                // find
1882
                // the document locally, we need find it remote
1883
                if ((((documentImplList.elementAt(i)).getClass()).toString())
1884
                        .equals("class java.lang.String")) {
1885
                    // Get String object from vetor
1886
                    String documentId = (String) documentImplList.elementAt(i);
1887
                    MetaCatUtil.debugMessage("docid: " + documentId, 30);
1888
                    // Get doicd without revision
1889
                    String docidWithoutRevision = MetaCatUtil
1890
                            .getDocIdFromString(documentId);
1891
                    MetaCatUtil.debugMessage("docidWithoutRevsion: "
1892
                            + docidWithoutRevision, 30);
1893
                    // Get revision
1894
                    String revision = MetaCatUtil
1895
                            .getRevisionStringFromString(documentId);
1896
                    MetaCatUtil.debugMessage("revsion from docIdentifier: "
1897
                            + revision, 30);
1898
                    // Zip entry string
1899
                    String zipEntryPath = rootName + "/data/";
1900
                    // Create a RemoteDocument object
1901
                    RemoteDocument remoteDoc = new RemoteDocument(
1902
                            docidWithoutRevision, revision, user, passWord,
1903
                            zipEntryPath);
1904
                    // Here we only read data file from remote metacat
1905
                    String docType = remoteDoc.getDocType();
1906
                    if (docType != null) {
1907
                        if (docType.equals("BIN")) {
1908
                            // Put remote document to zip output
1909
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
1910
                            // Add String object to htmlDocumentImplList
1911
                            String elementInHtmlList = remoteDoc
1912
                                    .getDocIdWithoutRevsion()
1913
                                    + MetaCatUtil.getOption("accNumSeparator")
1914
                                    + remoteDoc.getRevision();
1915
                            htmlDocumentImplList.add(elementInHtmlList);
1916
                        }//if
1917
                    }//if
1918

    
1919
                }//if
1920
                else {
1921
                    //create a docmentImpls object (represent xml doc) base on
1922
                    // the docId
1923
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
1924
                    //checking if the user has the permission to read the
1925
                    // documents
1926
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
1927
                            .getDocID())) {
1928
                        //if the docImpls is metadata
1929
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
1930
                            //add metadata into zip output stream
1931
                            addDocToZipOutputStream(docImpls, zOut, rootName);
1932
                            //add the documentImpl into the vetor which will
1933
                            // be used in html
1934
                            htmlDocumentImplList.add(docImpls);
1935

    
1936
                        }//if
1937
                        else {
1938
                            //it is data file
1939
                            addDataFileToZipOutputStream(docImpls, zOut,
1940
                                    rootName);
1941
                            htmlDocumentImplList.add(docImpls);
1942
                        }//else
1943
                    }//if
1944
                }//else
1945
            }//for
1946

    
1947
            //add html summary file
1948
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
1949
                    rootName);
1950
            zOut.finish(); //terminate the zip file
1951
            //dbConn.close();
1952
            return zOut;
1953
        }//else
1954
    }//getZippedPackage()
1955

    
1956
    private class ReturnFieldValue
1957
    {
1958

    
1959
        private String docid = null; //return field value for this docid
1960

    
1961
        private String fieldValue = null;
1962

    
1963
        private String xmlFieldValue = null; //return field value in xml
1964
                                             // format
1965

    
1966
        public void setDocid(String myDocid)
1967
        {
1968
            docid = myDocid;
1969
        }
1970

    
1971
        public String getDocid()
1972
        {
1973
            return docid;
1974
        }
1975

    
1976
        public void setFieldValue(String myValue)
1977
        {
1978
            fieldValue = myValue;
1979
        }
1980

    
1981
        public String getFieldValue()
1982
        {
1983
            return fieldValue;
1984
        }
1985

    
1986
        public void setXMLFieldValue(String xml)
1987
        {
1988
            xmlFieldValue = xml;
1989
        }
1990

    
1991
        public String getXMLFieldValue()
1992
        {
1993
            return xmlFieldValue;
1994
        }
1995

    
1996
    }
1997
}
(22-22/61)