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: tao $'
14
 *     '$Date: 2004-03-31 17:47:55 -0800 (Wed, 31 Mar 2004) $'
15
 * '$Revision: 2087 $'
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 = 800;
349
      int count = 0;
350
      int index = 0;
351
      Hashtable docListResult = new Hashtable();
352
      PreparedStatement pstmt = null;
353
      String docid = null;
354
      String docname = null;
355
      String doctype = null;
356
      String createDate = null;
357
      String updateDate = null;
358
      StringBuffer document = null;
359
      int rev = 0;
360
      String query = qspec.printSQL(useXMLIndex);
361
      String ownerQuery = getOwnerQuery(user);
362
      MetaCatUtil.debugMessage("query: " + query, 30);
363
      //MetaCatUtil.debugMessage("query: "+ownerQuery, 30);
364
      // if query is not the owner query, we need to check the permission
365
      // otherwise we don't need (owner has all permission by default)
366
      if (!query.equals(ownerQuery))
367
      {
368
        // set user name and group
369
        qspec.setUserName(user);
370
        qspec.setGroup(groups);
371
        // Get access query
372
        String accessQuery = qspec.getAccessQuery();
373
        query = query + accessQuery;
374
        MetaCatUtil.debugMessage(" final query: " + query, 30);
375
      }
376

    
377
      double startTime = System.currentTimeMillis() / 1000;
378
      pstmt = dbconn.prepareStatement(query);
379

    
380
      // Execute the SQL query using the JDBC connection
381
      pstmt.execute();
382
      ResultSet rs = pstmt.getResultSet();
383
      double queryExecuteTime = System.currentTimeMillis() / 1000;
384
      MetaCatUtil.debugMessage("Time for execute query: "
385
                    + (queryExecuteTime - startTime), 30);
386
      boolean tableHasRows = rs.next();
387
      while (tableHasRows)
388
      {
389
        docid = rs.getString(1).trim();
390
        docname = rs.getString(2);
391
        doctype = rs.getString(3);
392
        createDate = rs.getString(4);
393
        updateDate = rs.getString(5);
394
        rev = rs.getInt(6);
395

    
396
        // if there are returndocs to match, backtracking can be performed
397
        // otherwise, just return the document that was hit
398
        Vector returndocVec = qspec.getReturnDocList();
399
        if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
400
                        && !qspec.isPercentageSearch())
401
        {
402
           MetaCatUtil.debugMessage("Back tracing now...", 20);
403
           String sep = MetaCatUtil.getOption("accNumSeparator");
404
           StringBuffer btBuf = new StringBuffer();
405
           btBuf.append("select docid from xml_relation where ");
406

    
407
           //build the doctype list for the backtracking sql statement
408
           btBuf.append("packagetype in (");
409
           for (int i = 0; i < returndocVec.size(); i++)
410
           {
411
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
412
             if (i != (returndocVec.size() - 1))
413
             {
414
                btBuf.append(", ");
415
              }
416
            }
417
            btBuf.append(") ");
418
            btBuf.append("and (subject like '");
419
            btBuf.append(docid).append("'");
420
            btBuf.append("or object like '");
421
            btBuf.append(docid).append("')");
422

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

    
457
                String docid_org = xmldoc.getDocID();
458
                if (docid_org == null)
459
                {
460
                   MetaCatUtil.debugMessage("Docid_org was null.", 40);
461
                   continue;
462
                }
463
                docid = docid_org.trim();
464
                docname = xmldoc.getDocname();
465
                doctype = xmldoc.getDoctype();
466
                createDate = xmldoc.getCreateDate();
467
                updateDate = xmldoc.getUpdateDate();
468
                rev = xmldoc.getRev();
469
                document = new StringBuffer();
470

    
471
                String completeDocid = docid
472
                                + MetaCatUtil.getOption("accNumSeparator");
473
                completeDocid += rev;
474
                document.append("<docid>").append(completeDocid);
475
                document.append("</docid>");
476
                if (docname != null)
477
                {
478
                  document.append("<docname>" + docname + "</docname>");
479
                }
480
                if (doctype != null)
481
                {
482
                  document.append("<doctype>" + doctype + "</doctype>");
483
                }
484
                if (createDate != null)
485
                {
486
                 document.append("<createdate>" + createDate + "</createdate>");
487
                }
488
                if (updateDate != null)
489
                {
490
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
491
                }
492
                // Store the document id and the root node id
493
                docListResult.put(docid, (String) document.toString());
494
                count++;
495
                index++;
496

    
497
                // Get the next package document linked to our hit
498
                hasBtRows = btrs.next();
499
              }//while
500
              npstmt.close();
501
              btrs.close();
502
        }
503
        else if (returndocVec.size() != 0 && returndocVec.contains(doctype))
504
        {
505

    
506
           document = new StringBuffer();
507

    
508
           String completeDocid = docid
509
                            + MetaCatUtil.getOption("accNumSeparator");
510
           completeDocid += rev;
511
           document.append("<docid>").append(completeDocid).append("</docid>");
512
           if (docname != null)
513
           {
514
               document.append("<docname>" + docname + "</docname>");
515
            }
516
            if (doctype != null)
517
            {
518
               document.append("<doctype>" + doctype + "</doctype>");
519
            }
520
            if (createDate != null)
521
            {
522
                document.append("<createdate>" + createDate + "</createdate>");
523
             }
524
             if (updateDate != null)
525
             {
526
               document.append("<updatedate>" + updateDate + "</updatedate>");
527
             }
528
              // Store the document id and the root node id
529
              docListResult.put(docid, (String) document.toString());
530
              count++;
531
              index++;
532

    
533
        }//else
534
        // when doclist reached the offset number, send out doc list and empty
535
        // the hash table
536
        if (count == offset)
537
        {
538
          //reset count
539
          count = 0;
540
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
541
                              user, groups,dbconn, useXMLIndex);
542
          // reset docListResult
543
          docListResult = new Hashtable();
544

    
545
        }
546
       // Advance to the next record in the cursor
547
       tableHasRows = rs.next();
548
     }//while
549
     rs.close();
550
     pstmt.close();
551
     //if docListResult is not empty, it need to be sent.
552
     if (!docListResult.isEmpty())
553
     {
554
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
555
                              user, groups,dbconn, useXMLIndex);
556
     }
557
     double docListTime = System.currentTimeMillis() / 1000;
558
     MetaCatUtil.debugMessage("prepare docid list time: "
559
                    + (docListTime - queryExecuteTime), 30);
560
     MetaCatUtil.debugMessage("total docid is ===== "+index, 30);
561
     return resultsetBuffer;
562
    }//findReturnDoclist
563

    
564

    
565
    /*
566
     * Send completed search hashtable(part of reulst)to output stream
567
     * and buffer into a buffer stream
568
     */
569
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
570
                                           StringBuffer resultset,
571
                                           PrintWriter out, Hashtable partOfDoclist,
572
                                           String user, String[]groups,
573
                                       DBConnection dbconn, boolean useXMLIndex)
574
                                       throws Exception
575
   {
576

    
577
     int index =0;
578
     //add return field
579
     partOfDoclist = addRetrunfield(partOfDoclist, qspec, user, groups,
580
                                        dbconn, useXMLIndex );
581
     //add relationship part part docid list
582
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
583
     // send the completed search item to output and store it in a buffer
584
     String key = null;
585
     String element = null;
586
     Enumeration keys = partOfDoclist.keys();
587
     while (keys.hasMoreElements())
588
     {
589
           key = (String) keys.nextElement();
590
           element = (String)partOfDoclist.get(key);
591
           // A string with element
592
           String xmlElement = "  <document>" + element + "</document>";
593
           //send single element to output
594
           if (out != null)
595
           {
596
             out.println(xmlElement);
597
             index++;
598
           }
599
           else
600
           {
601
             index++;
602
           }
603
           resultset.append(xmlElement);
604
      }//while
605
      MetaCatUtil.debugMessage("total package number is ======= = "+ index, 20);
606
      return resultset;
607
   }
608

    
609

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

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

    
664
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
665
           MetaCatUtil.debugMessage( "Time for execute access extended query: "
666
                          + (extendedAccessQueryEnd - extendedQueryStart),30);
667

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

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

    
753
              // get attribures return
754
              docListResult = getAttributeValueForReturn(qspec,
755
                            docListResult, doclist.toString(), useXMLIndex);
756
       }//if doclist lenght is great than zero
757

    
758
     }//if has extended query
759

    
760
      return docListResult;
761
    }//addReturnfield
762

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

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

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

    
826
    return docListResult;
827
  }//addRelation
828

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

    
849

    
850
    /*
851
     * A method to search if Vector contains a particular key string
852
     */
853
    private boolean containsKey(Vector parentidList, String parentId)
854
    {
855

    
856
        Vector tempVector = null;
857

    
858
        for (int count = 0; count < parentidList.size(); count++) {
859
            tempVector = (Vector) parentidList.get(count);
860
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return false; }
861
        }
862
        return false;
863
    }
864

    
865
    /*
866
     * A method to put key and value in Vector
867
     */
868
    private void putInArray(Vector parentidList, String key,
869
            ReturnFieldValue value)
870
    {
871

    
872
        Vector tempVector = null;
873

    
874
        for (int count = 0; count < parentidList.size(); count++) {
875
            tempVector = (Vector) parentidList.get(count);
876

    
877
            if (key.compareTo((String) tempVector.get(0)) == 0) {
878
                tempVector.remove(1);
879
                tempVector.add(1, value);
880
                return;
881
            }
882
        }
883

    
884
        tempVector = new Vector();
885
        tempVector.add(0, key);
886
        tempVector.add(1, value);
887
        parentidList.add(tempVector);
888
        return;
889
    }
890

    
891
    /*
892
     * A method to get value in Vector given a key
893
     */
894
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
895
    {
896

    
897
        Vector tempVector = null;
898

    
899
        for (int count = 0; count < parentidList.size(); count++) {
900
            tempVector = (Vector) parentidList.get(count);
901

    
902
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
903
                    .get(1); }
904
        }
905
        return null;
906
    }
907

    
908
    /*
909
     * A method to get enumeration of all values in Vector
910
     */
911
    private Vector getElements(Vector parentidList)
912
    {
913
        Vector enum = new Vector();
914
        Vector tempVector = null;
915

    
916
        for (int count = 0; count < parentidList.size(); count++) {
917
            tempVector = (Vector) parentidList.get(count);
918

    
919
            enum.add(tempVector.get(1));
920
        }
921
        return enum;
922
    }
923

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

    
939
        //check the parameter
940
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
941

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

    
960
                    XML.append("<param name=\"");
961
                    XML.append(fieldname);
962
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
963
                    XML.append(attirbuteName);
964
                    XML.append("\">");
965
                    XML.append(fielddata);
966
                    XML.append("</param>");
967
                    tableHasRows = rs.next();
968

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

    
1000
    }
1001

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

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

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

    
1048
        if (params.containsKey("meta_file_id")) {
1049
            query.append("<meta_file_id>");
1050
            query.append(((String[]) params.get("meta_file_id"))[0]);
1051
            query.append("</meta_file_id>");
1052
        }
1053

    
1054
        if (params.containsKey("returndoctype")) {
1055
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1056
            for (int i = 0; i < returnDoctypes.length; i++) {
1057
                String doctype = (String) returnDoctypes[i];
1058

    
1059
                if (!doctype.equals("any") && !doctype.equals("ANY")
1060
                        && !doctype.equals("")) {
1061
                    query.append("<returndoctype>").append(doctype);
1062
                    query.append("</returndoctype>");
1063
                }
1064
            }
1065
        }
1066

    
1067
        if (params.containsKey("filterdoctype")) {
1068
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1069
            for (int i = 0; i < filterDoctypes.length; i++) {
1070
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1071
                query.append("</filterdoctype>");
1072
            }
1073
        }
1074

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

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

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

    
1099
        //allows the dynamic switching of boolean operators
1100
        if (params.containsKey("operator")) {
1101
            query.append("<querygroup operator=\""
1102
                    + ((String[]) params.get("operator"))[0] + "\">");
1103
        } else { //the default operator is UNION
1104
            query.append("<querygroup operator=\"UNION\">");
1105
        }
1106

    
1107
        if (params.containsKey("casesensitive")) {
1108
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1109
        } else {
1110
            casesensitive = "false";
1111
        }
1112

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

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

    
1136
        //this while loop finds the rest of the parameters
1137
        //and attempts to query for the field specified
1138
        //by the parameter.
1139
        elements = params.elements();
1140
        keys = params.keys();
1141
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1142
            nextkey = keys.nextElement();
1143
            nextelement = elements.nextElement();
1144

    
1145
            //make sure we aren't querying for any of these
1146
            //parameters since the are already in the query
1147
            //in one form or another.
1148
            Vector ignoredParams = new Vector();
1149
            ignoredParams.add("returndoctype");
1150
            ignoredParams.add("filterdoctype");
1151
            ignoredParams.add("action");
1152
            ignoredParams.add("qformat");
1153
            ignoredParams.add("anyfield");
1154
            ignoredParams.add("returnfield");
1155
            ignoredParams.add("owner");
1156
            ignoredParams.add("site");
1157
            ignoredParams.add("operator");
1158

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

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

    
1203
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1204
            xmlquery.append("<returndoctype>");
1205
            xmlquery.append(doctype).append("</returndoctype>");
1206
        }
1207

    
1208
        xmlquery.append("<querygroup operator=\"UNION\">");
1209
        //chad added - 8/14
1210
        //the if statement allows a query to gracefully handle a null
1211
        //query. Without this if a nullpointerException is thrown.
1212
        if (!value.equals("")) {
1213
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1214
            xmlquery.append("searchmode=\"contains\">");
1215
            xmlquery.append("<value>").append(value).append("</value>");
1216
            xmlquery.append("</queryterm>");
1217
        }
1218
        xmlquery.append("</querygroup>");
1219
        xmlquery.append("</pathquery>");
1220

    
1221
        return (xmlquery.toString());
1222
    }
1223

    
1224
    /**
1225
     * format a simple free-text value query as an XML document that conforms
1226
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1227
     * structured query engine
1228
     *
1229
     * @param value the text string to search for in the xml catalog
1230
     */
1231
    public static String createQuery(String value)
1232
    {
1233
        return createQuery(value, "any");
1234
    }
1235

    
1236
    /**
1237
     * Check for "READ" permission on @docid for @user and/or @group from DB
1238
     * connection
1239
     */
1240
    private boolean hasPermission(String user, String[] groups, String docid)
1241
            throws SQLException, Exception
1242
    {
1243
        // Check for READ permission on @docid for @user and/or @groups
1244
        PermissionController controller = new PermissionController(docid);
1245
        return controller.hasPermission(user, groups,
1246
                AccessControlInterface.READSTRING);
1247
    }
1248

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

    
1264
        // Check the parameter
1265
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1266

    
1267
        //the query stirng
1268
        String query = "SELECT subject, object from xml_relation where docId = ?";
1269
        try {
1270
            dbConn = DBConnectionPool
1271
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1272
            serialNumber = dbConn.getCheckOutSerialNumber();
1273
            pStmt = dbConn.prepareStatement(query);
1274
            //bind the value to query
1275
            pStmt.setString(1, dataPackageDocid);
1276

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

    
1292
                //don't put the duplicate docId into the vector
1293
                if (!docIdList.contains(docIdInSubjectField)) {
1294
                    docIdList.add(docIdInSubjectField);
1295
                }
1296

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

    
1325
    /**
1326
     * Get all docIds list for a data packadge
1327
     *
1328
     * @param dataPackageDocid, the string in docId field of xml_relation table
1329
     */
1330
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1331
    {
1332

    
1333
        Vector docIdList = new Vector();//return value
1334
        Vector tripleList = null;
1335
        String xml = null;
1336

    
1337
        // Check the parameter
1338
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1339

    
1340
        try {
1341
            //initial a documentImpl object
1342
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocid);
1343
            //transfer to documentImpl object to string
1344
            xml = packageDocument.toString();
1345

    
1346
            //create a tripcollection object
1347
            TripleCollection tripleForPackage = new TripleCollection(
1348
                    new StringReader(xml));
1349
            //get the vetor of triples
1350
            tripleList = tripleForPackage.getCollection();
1351

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

    
1371
        // return result
1372
        return docIdList;
1373
    }//getDocidListForPackageInXMLRevisions()
1374

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

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

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

    
1476
        }//try
1477
        catch (SQLException e) {
1478
            MetaCatUtil.debugMessage(
1479
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1480
                            + e.getMessage(), 30);
1481
            throw e;
1482
        }//catch
1483
        finally {
1484
            try {
1485
                pStmt.close();
1486
            }//try
1487
            catch (SQLException ee) {
1488
                MetaCatUtil.debugMessage(
1489
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1490
                                + ee.getMessage(), 30);
1491
            }//catch
1492
            finally {
1493
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1494
            }//finally
1495
        }//finally
1496
        return rev;
1497
    }//getCurrentRevFromXMLDoumentsTable
1498

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

    
1515
        byteString = docImpl.toString().getBytes();
1516
        //use docId as the zip entry's name
1517
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1518
                + docImpl.getDocID());
1519
        zEntry.setSize(byteString.length);
1520
        zipOut.putNextEntry(zEntry);
1521
        zipOut.write(byteString, 0, byteString.length);
1522
        zipOut.closeEntry();
1523

    
1524
    }//addDocToZipOutputStream()
1525

    
1526
    /**
1527
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1528
     * only inlcudes current version. If a DocumentImple object couldn't find
1529
     * for a docid, then the String of this docid was added to vetor rather
1530
     * than DocumentImple object.
1531
     *
1532
     * @param docIdList, a vetor hold a docid list for a data package. In
1533
     *            docid, there is not version number in it.
1534
     */
1535

    
1536
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1537
            throws McdbException, Exception
1538
    {
1539
        //Connection dbConn=null;
1540
        Vector documentImplList = new Vector();
1541
        int rev = 0;
1542

    
1543
        // Check the parameter
1544
        if (docIdList.isEmpty()) { return documentImplList; }//if
1545

    
1546
        //for every docid in vector
1547
        for (int i = 0; i < docIdList.size(); i++) {
1548
            try {
1549
                //get newest version for this docId
1550
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1551
                        .elementAt(i));
1552

    
1553
                // There is no record for this docId in xml_documents table
1554
                if (rev == -5) {
1555
                    // Rather than put DocumentImple object, put a String
1556
                    // Object(docid)
1557
                    // into the documentImplList
1558
                    documentImplList.add((String) docIdList.elementAt(i));
1559
                    // Skip other code
1560
                    continue;
1561
                }
1562

    
1563
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1564
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1565

    
1566
                //create new documentImpl object
1567
                DocumentImpl documentImplObject = new DocumentImpl(
1568
                        docidPlusVersion);
1569
                //add them to vector
1570
                documentImplList.add(documentImplObject);
1571
            }//try
1572
            catch (Exception e) {
1573
                MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1574
                        + e.getMessage(), 30);
1575
                // continue the for loop
1576
                continue;
1577
            }
1578
        }//for
1579
        return documentImplList;
1580
    }
1581

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

    
1598
        // Check the parameter
1599
        if (docIdList.isEmpty()) { return documentImplList; }//if
1600

    
1601
        //for every docid in vector
1602
        for (int i = 0; i < docIdList.size(); i++) {
1603

    
1604
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1605

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

    
1632
        }//for
1633
        return documentImplList;
1634
    }//getOldVersionAllDocumentImple
1635

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

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

    
1692
        //create a DBTransform ojbect
1693
        xmlToHtml = new DBTransform();
1694
        //head of html
1695
        htmlDoc.append("<html><head></head><body>");
1696
        for (int i = 0; i < docImplList.size(); i++) {
1697
            // If this String object, this means it is missed data file
1698
            if ((((docImplList.elementAt(i)).getClass()).toString())
1699
                    .equals("class java.lang.String")) {
1700

    
1701
                htmlDoc.append("<a href=\"");
1702
                String dataFileid = (String) docImplList.elementAt(i);
1703
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1704
                htmlDoc.append("Data File: ");
1705
                htmlDoc.append(dataFileid).append("</a><br>");
1706
                htmlDoc.append("<br><hr><br>");
1707

    
1708
            }//if
1709
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
1710
                    .compareTo("BIN") != 0) { //this is an xml file so we can
1711
                                              // transform it.
1712
                //transform each file individually then concatenate all of the
1713
                //transformations together.
1714

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

    
1749
    }//addHtmlSummaryToZipOutputStream
1750

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

    
1775
        String docId = null;
1776
        int version = -5;
1777
        // Docid without revision
1778
        docId = MetaCatUtil.getDocIdFromString(docIdString);
1779
        // revision number
1780
        version = MetaCatUtil.getVersionFromString(docIdString);
1781

    
1782
        //check if the reqused docId is a data package id
1783
        if (!isDataPackageId(docId)) {
1784

    
1785
            /*
1786
             * Exception e = new Exception("The request the doc id "
1787
             * +docIdString+ " is not a data package id");
1788
             */
1789

    
1790
            //CB 1/6/03: if the requested docid is not a datapackage, we just
1791
            // zip
1792
            //up the single document and return the zip file.
1793
            if (!hasPermissionToExportPackage(docId, user, groups)) {
1794

    
1795
                Exception e = new Exception("User " + user
1796
                        + " does not have permission"
1797
                        + " to export the data package " + docIdString);
1798
                throw e;
1799
            }
1800

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

    
1818
            zOut.finish(); //terminate the zip file
1819
            return zOut;
1820
        }
1821
        // Check the permission of user
1822
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
1823

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

    
1849
            }//if
1850
            else if (version > currentVersion || version < -1) {
1851
                throw new Exception("The user specified docid: " + docId + "."
1852
                        + version + " doesn't exist");
1853
            }//else if
1854
            else //for an old version
1855
            {
1856

    
1857
                rootName = docIdString
1858
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
1859
                //get the whole id list for data packadge
1860
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
1861

    
1862
                //get the whole documentImple object
1863
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
1864
            }//else
1865

    
1866
            // Make sure documentImplist is not empty
1867
            if (documentImplList.isEmpty()) { throw new Exception(
1868
                    "Couldn't find component for data package: " + packageId); }//if
1869

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

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

    
1929
                        }//if
1930
                        else {
1931
                            //it is data file
1932
                            addDataFileToZipOutputStream(docImpls, zOut,
1933
                                    rootName);
1934
                            htmlDocumentImplList.add(docImpls);
1935
                        }//else
1936
                    }//if
1937
                }//else
1938
            }//for
1939

    
1940
            //add html summary file
1941
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
1942
                    rootName);
1943
            zOut.finish(); //terminate the zip file
1944
            //dbConn.close();
1945
            return zOut;
1946
        }//else
1947
    }//getZippedPackage()
1948

    
1949
    private class ReturnFieldValue
1950
    {
1951

    
1952
        private String docid = null; //return field value for this docid
1953

    
1954
        private String fieldValue = null;
1955

    
1956
        private String xmlFieldValue = null; //return field value in xml
1957
                                             // format
1958

    
1959
        public void setDocid(String myDocid)
1960
        {
1961
            docid = myDocid;
1962
        }
1963

    
1964
        public String getDocid()
1965
        {
1966
            return docid;
1967
        }
1968

    
1969
        public void setFieldValue(String myValue)
1970
        {
1971
            fieldValue = myValue;
1972
        }
1973

    
1974
        public String getFieldValue()
1975
        {
1976
            return fieldValue;
1977
        }
1978

    
1979
        public void setXMLFieldValue(String xml)
1980
        {
1981
            xmlFieldValue = xml;
1982
        }
1983

    
1984
        public String getXMLFieldValue()
1985
        {
1986
            return xmlFieldValue;
1987
        }
1988

    
1989
    }
1990
}
(22-22/59)