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
 *
12
 *   '$Author: tao $'
13
 *     '$Date: 2007-05-10 17:59:26 -0700 (Thu, 10 May 2007) $'
14
 * '$Revision: 3271 $'
15
 *
16
 * This program is free software; you can redistribute it and/or modify
17
 * it under the terms of the GNU General Public License as published by
18
 * the Free Software Foundation; either version 2 of the License, or
19
 * (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU General Public License
27
 * along with this program; if not, write to the Free Software
28
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29
 */
30

    
31
package edu.ucsb.nceas.metacat;
32

    
33
import java.io.*;
34
import java.util.zip.*;
35
import java.sql.PreparedStatement;
36
import java.sql.ResultSet;
37
import java.sql.SQLException;
38
import java.util.*;
39

    
40
import javax.servlet.ServletOutputStream;
41
import javax.servlet.http.HttpServletResponse;
42
import javax.servlet.http.HttpSession;
43

    
44
import org.apache.log4j.Logger;
45

    
46
import org.w3c.dom.*;
47
import javax.xml.parsers.DocumentBuilderFactory;
48
import org.xml.sax.InputSource;
49
import org.w3c.dom.ls.*;
50

    
51
import edu.ucsb.nceas.morpho.datapackage.Triple;
52
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
53

    
54

    
55
/**
56
 * A Class that searches a relational DB for elements and attributes that have
57
 * free text matches a query string, or structured query matches to a path
58
 * specified node in the XML hierarchy. It returns a result set consisting of
59
 * the document ID for each document that satisfies the query
60
 */
61
public class DBQuery
62
{
63

    
64
    static final int ALL = 1;
65

    
66
    static final int WRITE = 2;
67

    
68
    static final int READ = 4;
69

    
70
    //private Connection conn = null;
71
    private String parserName = null;
72

    
73
    private MetaCatUtil util = new MetaCatUtil();
74

    
75
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
76

    
77
    /** true if the metacat spatial option is installed **/
78
    private final boolean METACAT_SPATIAL = true;
79

    
80
    /** useful if you just want to grab a list of docids **/
81
    Vector docidOverride = new Vector();
82

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

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

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

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

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

    
120
                double connTime = System.currentTimeMillis();
121

    
122
                // Execute the query
123
                DBQuery queryobj = new DBQuery();
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()
191
    {
192
        String parserName = MetaCatUtil.getOption("saxparser");
193
        this.parserName = parserName;
194
    }
195

    
196
    /**
197
     * 
198
     * Construct an instance of DBQuery Class
199
     * BUT accept a docid Vector that will supersede
200
     * the query.printSQL() method
201
     *
202
     * If a docid Vector is passed in,
203
     * the docids will be used to create a simple IN query 
204
     * without the multiple subselects of the printSQL() method
205
     *
206
     * Using this constructor, we just check for 
207
     * a docidOverride Vector in the findResultDoclist() method
208
     *
209
     * @param docids List of docids to display in the resultset
210
     */
211
    public DBQuery(Vector docids)
212
    {
213
        this.docidOverride = docids;
214
        String parserName = MetaCatUtil.getOption("saxparser");
215
        this.parserName = parserName;
216
    }
217

    
218
  /**
219
   * Method put the search result set into out printerwriter
220
   * @param resoponse the return response
221
   * @param out the output printer
222
   * @param params the paratermer hashtable
223
   * @param user the user name (it maybe different to the one in param)
224
   * @param groups the group array
225
   * @param sessionid  the sessionid
226
   */
227
  public void findDocuments(HttpServletResponse response,
228
                                       PrintWriter out, Hashtable params,
229
                                       String user, String[] groups,
230
                                       String sessionid)
231
  {
232
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
233
               .booleanValue();
234
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
235

    
236
  }
237

    
238

    
239
    /**
240
     * Method put the search result set into out printerwriter
241
     * @param resoponse the return response
242
     * @param out the output printer
243
     * @param params the paratermer hashtable
244
     * @param user the user name (it maybe different to the one in param)
245
     * @param groups the group array
246
     * @param sessionid  the sessionid
247
     */
248
    public void findDocuments(HttpServletResponse response,
249
                                         PrintWriter out, Hashtable params,
250
                                         String user, String[] groups,
251
                                         String sessionid, boolean useXMLIndex)
252
    {
253
      int pagesize = 0;
254
      int pagestart = 0;
255
      
256
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
257
      {
258
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
259
        String pagestartStr = ((String[])params.get("pagestart"))[0];
260
        if(pagesizeStr != null && pagestartStr != null)
261
        {
262
          pagesize = (new Integer(pagesizeStr)).intValue();
263
          pagestart = (new Integer(pagestartStr)).intValue();
264
        }
265
      }
266
      
267
      // get query and qformat
268
      String xmlquery = ((String[])params.get("query"))[0];
269

    
270
      logMetacat.info("SESSIONID: " + sessionid);
271
      logMetacat.info("xmlquery: " + xmlquery);
272
      String qformat = ((String[])params.get("qformat"))[0];
273
      logMetacat.info("qformat: " + qformat);
274
      // Get the XML query and covert it into a SQL statment
275
      QuerySpecification qspec = null;
276
      if ( xmlquery != null)
277
      {
278
         xmlquery = transformQuery(xmlquery);
279
         try
280
         {
281
           qspec = new QuerySpecification(xmlquery,
282
                                          parserName,
283
                                          MetaCatUtil.getOption("accNumSeparator"));
284
         }
285
         catch (Exception ee)
286
         {
287
           logMetacat.error("error generating QuerySpecification object"
288
                                    +" in DBQuery.findDocuments"
289
                                    + ee.getMessage());
290
         }
291
      }
292

    
293

    
294

    
295
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
296
      {
297
        //xml format
298
        response.setContentType("text/xml");
299
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex, 
300
          pagesize, pagestart, sessionid);
301
      }//if
302
      else
303
      {
304
        //knb format, in this case we will get whole result and sent it out
305
        response.setContentType("text/html");
306
        PrintWriter nonout = null;
307
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
308
                                                groups, useXMLIndex, pagesize, 
309
                                                pagestart, sessionid);
310
        
311
        //transfer the xml to html
312
        try
313
        {
314
         double startHTMLTransform = System.currentTimeMillis()/1000;
315
         DBTransform trans = new DBTransform();
316
         response.setContentType("text/html");
317

    
318
         // if the user is a moderator, then pass a param to the 
319
         // xsl specifying the fact
320
         if(MetaCatUtil.isModerator(user, groups)){
321
        	 params.put("isModerator", new String[] {"true"});
322
         }
323

    
324
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
325
                                 "-//W3C//HTML//EN", qformat, out, params,
326
                                 sessionid);
327
         double endHTMLTransform = System.currentTimeMillis()/1000;
328
                   logMetacat.warn("The time to transfrom resultset from xml to html format is "
329
                  		                             +(endHTMLTransform -startHTMLTransform));
330
                   MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Transfrom xml to html  "
331
                             +(endHTMLTransform -startHTMLTransform));
332
        }
333
        catch(Exception e)
334
        {
335
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
336
                                +e.getMessage());
337
         }
338

    
339
      }//else
340

    
341
  }
342
  
343
  /**
344
   * Transforms a hashtable of documents to an xml or html result and sent
345
   * the content to outputstream. Keep going untill hastable is empty. stop it.
346
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
347
   * to xmlquery String
348
   * @param xmlquery
349
   * @param qspec
350
   * @param out
351
   * @param user
352
   * @param groups
353
   * @param useXMLIndex
354
   * @param sessionid
355
   * @return
356
   */
357
    public StringBuffer createResultDocument(String xmlquery,
358
                                              QuerySpecification qspec,
359
                                              PrintWriter out,
360
                                              String user, String[] groups,
361
                                              boolean useXMLIndex)
362
    {
363
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"");
364
    }
365

    
366
  /*
367
   * Transforms a hashtable of documents to an xml or html result and sent
368
   * the content to outputstream. Keep going untill hastable is empty. stop it.
369
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
370
   * to xmlquery String
371
   */
372
  public StringBuffer createResultDocument(String xmlquery,
373
                                            QuerySpecification qspec,
374
                                            PrintWriter out,
375
                                            String user, String[] groups,
376
                                            boolean useXMLIndex, int pagesize,
377
                                            int pagestart, String sessionid)
378
  {
379
    DBConnection dbconn = null;
380
    int serialNumber = -1;
381
    StringBuffer resultset = new StringBuffer();
382

    
383
    //try to get the cached version first    
384
    Hashtable sessionHash = MetaCatServlet.getSessionHash();
385
    HttpSession sess = (HttpSession)sessionHash.get(sessionid);
386

    
387
    QuerySpecification cachedQuerySpec = null;
388
    if (sess != null)
389
    {
390
    	cachedQuerySpec = (QuerySpecification)sess.getAttribute("query");
391
    }
392
    
393
    resultset.append("<?xml version=\"1.0\"?>\n");
394
    resultset.append("<resultset>\n");
395
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
396
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
397
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
398
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
399

    
400
    resultset.append("  <query>" + xmlquery + "</query>");
401
    //send out a new query
402
    if (out != null)
403
    {
404
      out.println(resultset.toString());
405
    }
406
    if (qspec != null)
407
    {
408
      try
409
      {
410

    
411
        //checkout the dbconnection
412
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
413
        serialNumber = dbconn.getCheckOutSerialNumber();
414

    
415
        //print out the search result
416
        // search the doc list
417
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
418
                                      dbconn, useXMLIndex, pagesize, pagestart, 
419
                                      sessionid);
420
      } //try
421
      catch (IOException ioe)
422
      {
423
        logMetacat.error("IO error in DBQuery.findDocuments:");
424
        logMetacat.error(ioe.getMessage());
425

    
426
      }
427
      catch (SQLException e)
428
      {
429
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
430
                                 + e.getMessage());
431
      }
432
      catch (Exception ee)
433
      {
434
        logMetacat.error("Exception in DBQuery.findDocuments: "
435
                                 + ee.getMessage());
436
        ee.printStackTrace();
437
      }
438
      finally
439
      {
440
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
441
      } //finally
442
    }//if
443
    String closeRestultset = "</resultset>";
444
    resultset.append(closeRestultset);
445
    if (out != null)
446
    {
447
      out.println(closeRestultset);
448
    }
449

    
450
    //default to returning the whole resultset
451
    return resultset;
452
  }//createResultDocuments
453

    
454
    /*
455
     * Find the doc list which match the query
456
     */
457
    private StringBuffer findResultDoclist(QuerySpecification qspec,
458
                                      StringBuffer resultsetBuffer,
459
                                      PrintWriter out,
460
                                      String user, String[]groups,
461
                                      DBConnection dbconn, boolean useXMLIndex,
462
                                      int pagesize, int pagestart, String sessionid)
463
                                      throws Exception
464
    {
465
      String query = null;
466
      int count = 0;
467
      int index = 0;
468
      ResultDocumentSet docListResult = new ResultDocumentSet();
469
      PreparedStatement pstmt = null;
470
      String docid = null;
471
      String docname = null;
472
      String doctype = null;
473
      String createDate = null;
474
      String updateDate = null;
475
      StringBuffer document = null;
476
      boolean lastpage = false;
477
      int rev = 0;
478
      double startTime = 0;
479
      int offset = 1;
480
      double startSelectionTime = System.currentTimeMillis()/1000;
481
      ResultSet rs = null;
482
        
483
      offset = 1;
484
      // this is a hack for offset
485
      if (out == null)
486
      {
487
        // for html page, we put everything into one page
488
        offset =
489
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
490
      }
491
      else
492
      {
493
          offset =
494
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
495
      }
496

    
497
      /*
498
       * Check the docidOverride Vector
499
       * if defined, we bypass the qspec.printSQL() method
500
       * and contruct a simpler query based on a 
501
       * list of docids rather than a bunch of subselects
502
       */
503
      if ( this.docidOverride.size() == 0 ) {
504
          query = qspec.printSQL(useXMLIndex);
505
      } else {
506
          logMetacat.info("*** docid override " + this.docidOverride.size());
507
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
508
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
509
          for (int i = 0; i < docidOverride.size(); i++) {  
510
              queryBuffer.append("'");
511
              queryBuffer.append( (String)docidOverride.elementAt(i) );
512
              queryBuffer.append("',");
513
          }
514
          // empty string hack 
515
          queryBuffer.append( "'') " );
516
          query = queryBuffer.toString();
517
      } 
518
      String ownerQuery = getOwnerQuery(user);
519
      logMetacat.info("\n\n\n query: " + query);
520
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
521
      // if query is not the owner query, we need to check the permission
522
      // otherwise we don't need (owner has all permission by default)
523
      if (!query.equals(ownerQuery))
524
      {
525
        // set user name and group
526
        qspec.setUserName(user);
527
        qspec.setGroup(groups);
528
        // Get access query
529
        String accessQuery = qspec.getAccessQuery();
530
        if(!query.endsWith("WHERE")){
531
            query = query + accessQuery;
532
        } else {
533
            query = query + accessQuery.substring(4, accessQuery.length());
534
        }
535
        logMetacat.info("\n\n\n final query: " + query);
536
      }
537

    
538
      startTime = System.currentTimeMillis() / 1000;
539
      pstmt = dbconn.prepareStatement(query);
540
      rs = pstmt.executeQuery();
541

    
542
      double queryExecuteTime = System.currentTimeMillis() / 1000;
543
      logMetacat.warn("Time to execute select docid query is "
544
                    + (queryExecuteTime - startTime));
545
      MetaCatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
546
              + (queryExecuteTime - startTime));
547

    
548
      boolean tableHasRows = rs.next();
549
      
550
      if(pagesize == 0)
551
      { //this makes sure we get all results if there is no paging
552
        pagesize = 99999;
553
        pagestart = 99999;
554
      } 
555
      
556
      int currentIndex = 0;
557
      while (tableHasRows)
558
      {
559
        logMetacat.info("############getting result: " + currentIndex);
560
        docid = rs.getString(1).trim();
561
        logMetacat.info("############processing: " + docid);
562
        docname = rs.getString(2);
563
        doctype = rs.getString(3);
564
        logMetacat.info("############processing: " + doctype);
565
        createDate = rs.getString(4);
566
        updateDate = rs.getString(5);
567
        rev = rs.getInt(6);
568
        
569
        // if there are returndocs to match, backtracking can be performed
570
        // otherwise, just return the document that was hit
571
        Vector returndocVec = qspec.getReturnDocList();
572
        if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
573
             && !qspec.isPercentageSearch())
574
         {
575
           logMetacat.info("Back tracing now...");
576
           String sep = MetaCatUtil.getOption("accNumSeparator");
577
           StringBuffer btBuf = new StringBuffer();
578
           btBuf.append("select docid from xml_relation where ");
579

    
580
           //build the doctype list for the backtracking sql statement
581
           btBuf.append("packagetype in (");
582
           for (int i = 0; i < returndocVec.size(); i++)
583
           {
584
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
585
             if (i != (returndocVec.size() - 1))
586
             {
587
                btBuf.append(", ");
588
              }
589
            }
590
            btBuf.append(") ");
591
            btBuf.append("and (subject like '");
592
            btBuf.append(docid).append("'");
593
            btBuf.append("or object like '");
594
            btBuf.append(docid).append("')");
595

    
596
            PreparedStatement npstmt = dbconn.prepareStatement(btBuf.toString());
597
            //should incease usage count
598
            dbconn.increaseUsageCount(1);
599
            npstmt.execute();
600
            ResultSet btrs = npstmt.getResultSet();
601
            boolean hasBtRows = btrs.next();
602
            //Hashtable list = new Hashtable();
603
            while (hasBtRows)
604
            {
605
               //there was a backtrackable document found
606
               DocumentImpl xmldoc = null;
607
               String packageDocid = btrs.getString(1);
608
               logMetacat.info("Getting document for docid: "
609
                                         + packageDocid);
610
                try
611
                {
612
                    //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not
613
                    // needed here
614
                    // xmldoc = new DocumentImpl(dbconn, packageDocid);
615
                    //  thus use the following to get the doc info only
616
                    //  xmldoc = new DocumentImpl(dbconn);
617
                    String accNumber = packageDocid + MetaCatUtil.getOption("accNumSeparator") +
618
                    DBUtil.getLatestRevisionInDocumentTable(packageDocid);
619
                    xmldoc = new DocumentImpl(accNumber, false);
620
                    if (xmldoc == null)
621
                    {
622
                       logMetacat.info("Document was null for: "
623
                                                + packageDocid);
624
                    }
625
                }
626
                catch (Exception e)
627
                {
628
                    System.out.println("Error getting document in "
629
                                       + "DBQuery.findDocuments: "
630
                                       + e.getMessage());
631
                }
632

    
633
                String docid_org = xmldoc.getDocID();
634
                if (docid_org == null)
635
                {
636
                   logMetacat.info("Docid_org was null.");
637
                   hasBtRows = btrs.next();
638
                   continue;
639
                }
640
                docid = docid_org.trim();
641
                /*if (list.containsKey(docid))
642
                {
643
                        	logMetacat.info("DocumentResultSet already has docid "+docid+" and skip it");
644
                            hasBtRows = btrs.next();
645
                            continue;
646
                 }*/
647
                docname = xmldoc.getDocname();
648
                doctype = xmldoc.getDoctype();
649
                createDate = xmldoc.getCreateDate();
650
                updateDate = xmldoc.getUpdateDate();
651
                rev = xmldoc.getRev();
652
                document = new StringBuffer();
653

    
654
                String completeDocid = docid
655
                                + MetaCatUtil.getOption("accNumSeparator");
656
                completeDocid += rev;
657
                document.append("<docid>").append(completeDocid);
658
                document.append("</docid>");
659
                if (docname != null)
660
                {
661
                  document.append("<docname>" + docname + "</docname>");
662
                }
663
                if (doctype != null)
664
                {
665
                  document.append("<doctype>" + doctype + "</doctype>");
666
                }
667
                if (createDate != null)
668
                {
669
                 document.append("<createdate>" + createDate + "</createdate>");
670
                }
671
                if (updateDate != null)
672
                {
673
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
674
                }
675
                // Store the document id and the root node id
676
                docListResult.addResultDocument(
677
                  new ResultDocument(docid, (String) document.toString()));
678
                currentIndex++;
679
                //list.put(docid, docid);
680
                logMetacat.info("$$$$$$$real result: " + docid);
681
                count++;
682

    
683
                // Get the next package document linked to our hit
684
                hasBtRows = btrs.next();
685
              }//while
686
              npstmt.close();
687
              btrs.close();
688
        }
689
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
690
        {
691
          logMetacat.info("NOT Back tracing now...");
692
           document = new StringBuffer();
693

    
694
           String completeDocid = docid
695
                            + MetaCatUtil.getOption("accNumSeparator");
696
           completeDocid += rev;
697
           document.append("<docid>").append(completeDocid).append("</docid>");
698
           if (docname != null)
699
           {
700
               document.append("<docname>" + docname + "</docname>");
701
           }
702
           if (doctype != null)
703
           {
704
              document.append("<doctype>" + doctype + "</doctype>");
705
           }
706
           if (createDate != null)
707
           {
708
               document.append("<createdate>" + createDate + "</createdate>");
709
           }
710
           if (updateDate != null)
711
           {
712
             document.append("<updatedate>" + updateDate + "</updatedate>");
713
           }
714
           // Store the document id and the root node id
715
           
716
           docListResult.addResultDocument(
717
             new ResultDocument(docid, (String) document.toString()));
718
           logMetacat.info("$$$$$$$real result: " + docid);
719
           currentIndex++;
720
           count++;
721
        }//else
722
        
723
        // when doclist reached the offset number, send out doc list and empty
724
        // the hash table
725
        if (count == offset && pagesize == 0)
726
        { //if pagesize is not 0, do this later.
727
          //reset count
728
          //logMetacat.warn("############doing subset cache");
729
          count = 0;
730
          handleSubsetResult(qspec, resultsetBuffer, out, docListResult,
731
                              user, groups,dbconn, useXMLIndex);
732
          //reset docListResult
733
          docListResult = new ResultDocumentSet();
734
        }
735
       
736
       logMetacat.info("currentIndex: " + currentIndex);
737
       logMetacat.info("page comparator: " + (pagesize * pagestart) + pagesize);
738
       if(currentIndex >= ((pagesize * pagestart) + pagesize))
739
       {
740
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
741
         for(int i=pagesize*pagestart; i<docListResult.size(); i++)
742
         {
743
           pagedResultsHash.put(docListResult.get(i));
744
         }
745
         
746
         docListResult = pagedResultsHash;
747
         break;
748
       }
749
       // Advance to the next record in the cursor
750
       tableHasRows = rs.next();
751
       if(!tableHasRows)
752
       {
753
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
754
         //get the last page of information then break
755
         if(pagesize != 99999)
756
         {
757
           for(int i=pagesize*pagestart; i<docListResult.size(); i++)
758
           {
759
             pagedResultsHash.put(docListResult.get(i));
760
           }
761
           docListResult = pagedResultsHash;
762
         }
763
         
764
         lastpage = true;
765
         break;
766
       }
767
     }//while
768
     
769
     rs.close();
770
     pstmt.close();
771
     double docListTime = System.currentTimeMillis() / 1000;
772
     logMetacat.warn("======Total time to get docid list is: "
773
                          + (docListTime - startSelectionTime ));
774
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Total selection: "
775
             + (docListTime - startSelectionTime ));
776
     //if docListResult is not empty, it need to be sent.
777
     if (docListResult.size() != 0)
778
     {
779
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
780
                              user, groups,dbconn, useXMLIndex);
781
     }
782

    
783
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
784
     if (out != null)
785
     {
786
         out.println("\n<lastpage>" + lastpage + "</lastpage>\n");
787
     }
788
          
789
     return resultsetBuffer;
790
    }//findReturnDoclist
791

    
792

    
793
    /*
794
     * Send completed search hashtable(part of reulst)to output stream
795
     * and buffer into a buffer stream
796
     */
797
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
798
                                           StringBuffer resultset,
799
                                           PrintWriter out, ResultDocumentSet partOfDoclist,
800
                                           String user, String[]groups,
801
                                       DBConnection dbconn, boolean useXMLIndex)
802
                                       throws Exception
803
   {
804
     double startReturnField = System.currentTimeMillis()/1000;
805
     // check if there is a record in xml_returnfield
806
     // and get the returnfield_id and usage count
807
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
808
     boolean enterRecords = false;
809

    
810
     // get value of xml_returnfield_count
811
     int count = (new Integer(MetaCatUtil
812
                            .getOption("xml_returnfield_count")))
813
                            .intValue();
814

    
815
     // set enterRecords to true if usage_count is more than the offset
816
     // specified in metacat.properties
817
     if(usage_count > count){
818
         enterRecords = true;
819
     }
820

    
821
     if(returnfield_id < 0){
822
         logMetacat.warn("Error in getting returnfield id from"
823
                                  + "xml_returnfield table");
824
         enterRecords = false;
825
     }
826

    
827
     // get the hashtable containing the docids that already in the
828
     // xml_queryresult table
829
     logMetacat.info("size of partOfDoclist before"
830
                             + " docidsInQueryresultTable(): "
831
                             + partOfDoclist.size());
832
     double startGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
833
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
834
                                                        partOfDoclist, dbconn);
835

    
836
     // remove the keys in queryresultDocList from partOfDoclist
837
     Enumeration _keys = queryresultDocList.keys();
838
     while (_keys.hasMoreElements()){
839
         partOfDoclist.remove((String)_keys.nextElement());
840
     }
841
     double endGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
842
     logMetacat.warn("Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
843
          		               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
844
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
845
               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
846
     // backup the keys-elements in partOfDoclist to check later
847
     // if the doc entry is indexed yet
848
     Hashtable partOfDoclistBackup = new Hashtable();
849
     Iterator itt = partOfDoclist.getDocids();
850
     while (itt.hasNext()){
851
       Object key = itt.next();
852
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
853
     }
854

    
855
     logMetacat.info("size of partOfDoclist after"
856
                             + " docidsInQueryresultTable(): "
857
                             + partOfDoclist.size());
858

    
859
     //add return fields for the documents in partOfDoclist
860
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
861
                                        dbconn, useXMLIndex);
862
     double endExtendedQuery = System.currentTimeMillis()/1000;
863
     logMetacat.warn("Get fields from index and node table (Part2 in return fields) "
864
        		                                          + (endExtendedQuery - endGetReturnValueFromQueryresultable));
865
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
866
             + (endExtendedQuery - endGetReturnValueFromQueryresultable));
867
     //add relationship part part docid list for the documents in partOfDocList
868
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
869

    
870
     double startStoreReturnField = System.currentTimeMillis()/1000;
871
     Iterator keys = partOfDoclist.getDocids();
872
     String key = null;
873
     String element = null;
874
     String query = null;
875
     int offset = (new Integer(MetaCatUtil
876
                               .getOption("queryresult_string_length")))
877
                               .intValue();
878
     while (keys.hasNext())
879
     {
880
         key = (String) keys.next();
881
         element = (String)partOfDoclist.get(key);
882

    
883
	 // check if the enterRecords is true, elements is not null, element's
884
         // length is less than the limit of table column and if the document
885
         // has been indexed already
886
         if(enterRecords && element != null
887
		&& element.length() < offset
888
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
889
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
890
                 + "queryresult_string) VALUES (?, ?, ?)";
891

    
892
             PreparedStatement pstmt = null;
893
             pstmt = dbconn.prepareStatement(query);
894
             pstmt.setInt(1, returnfield_id);
895
             pstmt.setString(2, key);
896
             pstmt.setString(3, element);
897

    
898
             dbconn.increaseUsageCount(1);
899
             pstmt.execute();
900
             pstmt.close();
901
         }
902
        
903
         // A string with element
904
         String xmlElement = "  <document>" + element + "</document>";
905

    
906
         //send single element to output
907
         if (out != null)
908
         {
909
             out.println(xmlElement);
910
         }
911
         resultset.append(xmlElement);
912
     }//while
913
     
914
     double endStoreReturnField = System.currentTimeMillis()/1000;
915
     logMetacat.warn("Time to store new return fields into xml_queryresult table (Part4 in return fields) "
916
                   + (endStoreReturnField -startStoreReturnField));
917
     MetaCatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
918
             + (endStoreReturnField -startStoreReturnField));
919
     
920
     Enumeration keysE = queryresultDocList.keys();
921
     while (keysE.hasMoreElements())
922
     {
923
         key = (String) keysE.nextElement();
924
         element = (String)queryresultDocList.get(key);
925
         // A string with element
926
         String xmlElement = "  <document>" + element + "</document>";
927
         //send single element to output
928
         if (out != null)
929
         {
930
             out.println(xmlElement);
931
         }
932
         resultset.append(xmlElement);
933
     }//while
934
     double returnFieldTime = System.currentTimeMillis() / 1000;
935
     logMetacat.warn("======Total time to get return fields is: "
936
                           + (returnFieldTime - startReturnField));
937
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------"+
938
    		 "Total to get return fields  "
939
                                   + (returnFieldTime - startReturnField));
940
     return resultset;
941
 }
942

    
943
   /**
944
    * Get the docids already in xml_queryresult table and corresponding
945
    * queryresultstring as a hashtable
946
    */
947
   private Hashtable docidsInQueryresultTable(int returnfield_id,
948
                                              ResultDocumentSet partOfDoclist,
949
                                              DBConnection dbconn){
950

    
951
         Hashtable returnValue = new Hashtable();
952
         PreparedStatement pstmt = null;
953
         ResultSet rs = null;
954

    
955
         // get partOfDoclist as string for the query
956
         Iterator keylist = partOfDoclist.getDocids();
957
         StringBuffer doclist = new StringBuffer();
958
         while (keylist.hasNext())
959
         {
960
             doclist.append("'");
961
             doclist.append((String) keylist.next());
962
             doclist.append("',");
963
         }//while
964

    
965

    
966
         if (doclist.length() > 0)
967
         {
968
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
969

    
970
             // the query to find out docids from xml_queryresult
971
             String query = "select docid, queryresult_string from "
972
                          + "xml_queryresult where returnfield_id = " +
973
                          returnfield_id +" and docid in ("+ doclist + ")";
974
             logMetacat.info("Query to get docids from xml_queryresult:"
975
                                      + query);
976

    
977
             try {
978
                 // prepare and execute the query
979
                 pstmt = dbconn.prepareStatement(query);
980
                 dbconn.increaseUsageCount(1);
981
                 pstmt.execute();
982
                 rs = pstmt.getResultSet();
983
                 boolean tableHasRows = rs.next();
984
                 while (tableHasRows) {
985
                     // store the returned results in the returnValue hashtable
986
                     String key = rs.getString(1);
987
                     String element = rs.getString(2);
988

    
989
                     if(element != null){
990
                         returnValue.put(key, element);
991
                     } else {
992
                         logMetacat.info("Null elment found ("
993
                         + "DBQuery.docidsInQueryresultTable)");
994
                     }
995
                     tableHasRows = rs.next();
996
                 }
997
                 rs.close();
998
                 pstmt.close();
999
             } catch (Exception e){
1000
                 logMetacat.error("Error getting docids from "
1001
                                          + "queryresult in "
1002
                                          + "DBQuery.docidsInQueryresultTable: "
1003
                                          + e.getMessage());
1004
              }
1005
         }
1006
         return returnValue;
1007
     }
1008

    
1009

    
1010
   /**
1011
    * Method to get id from xml_returnfield table
1012
    * for a given query specification
1013
    */
1014
   private int returnfield_id;
1015
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1016
                                           DBConnection dbconn){
1017
       int id = -1;
1018
       int count = 1;
1019
       PreparedStatement pstmt = null;
1020
       ResultSet rs = null;
1021
       String returnfield = qspec.getSortedReturnFieldString();
1022

    
1023
       // query for finding the id from xml_returnfield
1024
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1025
            + "WHERE returnfield_string LIKE ?";
1026
       logMetacat.info("ReturnField Query:" + query);
1027

    
1028
       try {
1029
           // prepare and run the query
1030
           pstmt = dbconn.prepareStatement(query);
1031
           pstmt.setString(1,returnfield);
1032
           dbconn.increaseUsageCount(1);
1033
           pstmt.execute();
1034
           rs = pstmt.getResultSet();
1035
           boolean tableHasRows = rs.next();
1036

    
1037
           // if record found then increase the usage count
1038
           // else insert a new record and get the id of the new record
1039
           if(tableHasRows){
1040
               // get the id
1041
               id = rs.getInt(1);
1042
               count = rs.getInt(2) + 1;
1043
               rs.close();
1044
               pstmt.close();
1045

    
1046
               // increase the usage count
1047
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1048
                   + "' WHERE returnfield_id ='"+ id +"'";
1049
               logMetacat.info("ReturnField Table Update:"+ query);
1050

    
1051
               pstmt = dbconn.prepareStatement(query);
1052
               dbconn.increaseUsageCount(1);
1053
               pstmt.execute();
1054
               pstmt.close();
1055

    
1056
           } else {
1057
               rs.close();
1058
               pstmt.close();
1059

    
1060
               // insert a new record
1061
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1062
                   + "VALUES (?, '1')";
1063
               logMetacat.info("ReturnField Table Insert:"+ query);
1064
               pstmt = dbconn.prepareStatement(query);
1065
               pstmt.setString(1, returnfield);
1066
               dbconn.increaseUsageCount(1);
1067
               pstmt.execute();
1068
               pstmt.close();
1069

    
1070
               // get the id of the new record
1071
               query = "SELECT returnfield_id FROM xml_returnfield "
1072
                   + "WHERE returnfield_string LIKE ?";
1073
               logMetacat.info("ReturnField query after Insert:" + query);
1074
               pstmt = dbconn.prepareStatement(query);
1075
               pstmt.setString(1, returnfield);
1076

    
1077
               dbconn.increaseUsageCount(1);
1078
               pstmt.execute();
1079
               rs = pstmt.getResultSet();
1080
               if(rs.next()){
1081
                   id = rs.getInt(1);
1082
               } else {
1083
                   id = -1;
1084
               }
1085
               rs.close();
1086
               pstmt.close();
1087
           }
1088

    
1089
       } catch (Exception e){
1090
           logMetacat.error("Error getting id from xml_returnfield in "
1091
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1092
                                     + e.getMessage());
1093
           id = -1;
1094
       }
1095

    
1096
       returnfield_id = id;
1097
       return count;
1098
   }
1099

    
1100

    
1101
    /*
1102
     * A method to add return field to return doclist hash table
1103
     */
1104
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1105
                                      QuerySpecification qspec,
1106
                                      String user, String[]groups,
1107
                                      DBConnection dbconn, boolean useXMLIndex )
1108
                                      throws Exception
1109
    {
1110
      PreparedStatement pstmt = null;
1111
      ResultSet rs = null;
1112
      String docid = null;
1113
      String fieldname = null;
1114
      String fielddata = null;
1115
      String relation = null;
1116

    
1117
      if (qspec.containsExtendedSQL())
1118
      {
1119
        qspec.setUserName(user);
1120
        qspec.setGroup(groups);
1121
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1122
        Vector results = new Vector();
1123
        Iterator keylist = docListResult.getDocids();
1124
        StringBuffer doclist = new StringBuffer();
1125
        Vector parentidList = new Vector();
1126
        Hashtable returnFieldValue = new Hashtable();
1127
        while (keylist.hasNext())
1128
        {
1129
          doclist.append("'");
1130
          doclist.append((String) keylist.next());
1131
          doclist.append("',");
1132
        }
1133
        if (doclist.length() > 0)
1134
        {
1135
          Hashtable controlPairs = new Hashtable();
1136
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1137
          boolean tableHasRows = false;
1138
          // check if user has permission to see the return field data
1139
          /*String accessControlSQL =
1140
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
1141
          pstmt = dbconn.prepareStatement(accessControlSQL);
1142
          //increase dbconnection usage count
1143
          dbconn.increaseUsageCount(1);
1144
          pstmt.execute();
1145
          rs = pstmt.getResultSet();
1146
          tableHasRows = rs.next();
1147
          while (tableHasRows)
1148
          {
1149
            long startNodeId = rs.getLong(1);
1150
            long endNodeId = rs.getLong(2);
1151
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
1152
            tableHasRows = rs.next();
1153
          }*/
1154

    
1155
           /*double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
1156
           logMetacat.info( "Time for execute access extended query: "
1157
                          + (extendedAccessQueryEnd - extendedQueryStart));*/
1158

    
1159
           String extendedQuery =
1160
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex);
1161
           logMetacat.info("Extended query: " + extendedQuery);
1162

    
1163
           if(extendedQuery != null){
1164
        	   double extendedQueryStart = System.currentTimeMillis() / 1000;
1165
               pstmt = dbconn.prepareStatement(extendedQuery);
1166
               //increase dbconnection usage count
1167
               dbconn.increaseUsageCount(1);
1168
               pstmt.execute();
1169
               rs = pstmt.getResultSet();
1170
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
1171
               logMetacat.warn(
1172
                   "Time to execute extended query: "
1173
                   + (extendedQueryEnd - extendedQueryStart));
1174
               MetaCatUtil.writeDebugToFile(
1175
                       "Execute extended query "
1176
                       + (extendedQueryEnd - extendedQueryStart));
1177
               tableHasRows = rs.next();
1178
               while (tableHasRows) {
1179
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1180
                   docid = rs.getString(1).trim();
1181
                   fieldname = rs.getString(2);
1182
                   fielddata = rs.getString(3);
1183
                   fielddata = MetaCatUtil.normalize(fielddata);
1184
                   String parentId = rs.getString(4);
1185
                   StringBuffer value = new StringBuffer();
1186

    
1187
                   // if xml_index is used, there would be just one record per nodeid
1188
                   // as xml_index just keeps one entry for each path
1189
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1190
                       // don't need to merger nodedata
1191
                       value.append("<param name=\"");
1192
                       value.append(fieldname);
1193
                       value.append("\">");
1194
                       value.append(fielddata);
1195
                       value.append("</param>");
1196
                       //set returnvalue
1197
                       returnValue.setDocid(docid);
1198
                       returnValue.setFieldValue(fielddata);
1199
                       returnValue.setXMLFieldValue(value.toString());
1200
                       // Store it in hastable
1201
                       putInArray(parentidList, parentId, returnValue);
1202
                   }
1203
                   else {
1204
                       // need to merge nodedata if they have same parent id and
1205
                       // node type is text
1206
                       fielddata = (String) ( (ReturnFieldValue)
1207
                                             getArrayValue(
1208
                           parentidList, parentId)).getFieldValue()
1209
                           + fielddata;
1210
                       value.append("<param name=\"");
1211
                       value.append(fieldname);
1212
                       value.append("\">");
1213
                       value.append(fielddata);
1214
                       value.append("</param>");
1215
                       returnValue.setDocid(docid);
1216
                       returnValue.setFieldValue(fielddata);
1217
                       returnValue.setXMLFieldValue(value.toString());
1218
                       // remove the old return value from paretnidList
1219
                       parentidList.remove(parentId);
1220
                       // store the new return value in parentidlit
1221
                       putInArray(parentidList, parentId, returnValue);
1222
                   }
1223
                   tableHasRows = rs.next();
1224
               } //while
1225
               rs.close();
1226
               pstmt.close();
1227

    
1228
               // put the merger node data info into doclistReult
1229
               Enumeration xmlFieldValue = (getElements(parentidList)).
1230
                   elements();
1231
               while (xmlFieldValue.hasMoreElements()) {
1232
                   ReturnFieldValue object =
1233
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1234
                   docid = object.getDocid();
1235
                   if (docListResult.containsDocid(docid)) {
1236
                       String removedelement = (String) docListResult.
1237
                           remove(docid);
1238
                       docListResult.
1239
                           addResultDocument(new ResultDocument(docid,
1240
                               removedelement + object.getXMLFieldValue()));
1241
                   }
1242
                   else {
1243
                       docListResult.addResultDocument(
1244
                         new ResultDocument(docid, object.getXMLFieldValue()));
1245
                   }
1246
               } //while
1247
               double docListResultEnd = System.currentTimeMillis() / 1000;
1248
               logMetacat.warn(
1249
                   "Time to prepare ResultDocumentSet after"
1250
                   + " execute extended query: "
1251
                   + (docListResultEnd - extendedQueryEnd));
1252
           }
1253

    
1254
           // get attribures return
1255
           double startGetAttribute = System.currentTimeMillis()/1000;
1256
           docListResult = getAttributeValueForReturn(qspec,
1257
                           docListResult, doclist.toString(), useXMLIndex);
1258
           double endGetAttribute = System.currentTimeMillis()/1000;
1259
           logMetacat.warn(
1260
                   "Time to get attribute return value after"
1261
                   + " execute extended query: "
1262
                   + (endGetAttribute - startGetAttribute));
1263
           MetaCatUtil.writeDebugToFile(
1264
                   "Get attribute return field "
1265
                   + (endGetAttribute - startGetAttribute));
1266
           
1267
           
1268
       }//if doclist lenght is great than zero
1269

    
1270
     }//if has extended query
1271

    
1272
      return docListResult;
1273
    }//addReturnfield
1274

    
1275
    /*
1276
    * A method to add relationship to return doclist hash table
1277
    */
1278
   private ResultDocumentSet addRelationship(ResultDocumentSet docListResult,
1279
                                     QuerySpecification qspec,
1280
                                     DBConnection dbconn, boolean useXMLIndex )
1281
                                     throws Exception
1282
  {
1283
    PreparedStatement pstmt = null;
1284
    ResultSet rs = null;
1285
    StringBuffer document = null;
1286
    double startRelation = System.currentTimeMillis() / 1000;
1287
    Iterator docidkeys = docListResult.getDocids();
1288
    while (docidkeys.hasNext())
1289
    {
1290
      //String connstring =
1291
      // "metacat://"+util.getOption("server")+"?docid=";
1292
      String connstring = "%docid=";
1293
      String docidkey;
1294
      synchronized(docListResult)
1295
      {
1296
        docidkey = (String) docidkeys.next();
1297
      }
1298
      pstmt = dbconn.prepareStatement(QuerySpecification
1299
                      .printRelationSQL(docidkey));
1300
      pstmt.execute();
1301
      rs = pstmt.getResultSet();
1302
      boolean tableHasRows = rs.next();
1303
      while (tableHasRows)
1304
      {
1305
        String sub = rs.getString(1);
1306
        String rel = rs.getString(2);
1307
        String obj = rs.getString(3);
1308
        String subDT = rs.getString(4);
1309
        String objDT = rs.getString(5);
1310

    
1311
        document = new StringBuffer();
1312
        document.append("<triple>");
1313
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1314
        document.append("</subject>");
1315
        if (subDT != null)
1316
        {
1317
          document.append("<subjectdoctype>").append(subDT);
1318
          document.append("</subjectdoctype>");
1319
        }
1320
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1321
        document.append("</relationship>");
1322
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1323
        document.append("</object>");
1324
        if (objDT != null)
1325
        {
1326
          document.append("<objectdoctype>").append(objDT);
1327
          document.append("</objectdoctype>");
1328
        }
1329
        document.append("</triple>");
1330

    
1331
        String removedelement = (String) docListResult.get(docidkey);
1332
        docListResult.set(docidkey, removedelement+ document.toString());
1333
        tableHasRows = rs.next();
1334
      }//while
1335
      rs.close();
1336
      pstmt.close();
1337
      
1338
    }//while
1339
    double endRelation = System.currentTimeMillis() / 1000;
1340
    logMetacat.warn("Time to add relationship to return fields (part 3 in return fields): "
1341
                             + (endRelation - startRelation));
1342
    MetaCatUtil.writeDebugToFile("-----------------------------------------Add relationship to return field(part3 in return fields): "
1343
            + (endRelation - startRelation));
1344

    
1345
    return docListResult;
1346
  }//addRelation
1347

    
1348
  /**
1349
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1350
   * string as a param instead of a hashtable.
1351
   *
1352
   * @param xmlquery a string representing a query.
1353
   */
1354
   private  String transformQuery(String xmlquery)
1355
   {
1356
     xmlquery = xmlquery.trim();
1357
     int index = xmlquery.indexOf("?>");
1358
     if (index != -1)
1359
     {
1360
       return xmlquery.substring(index + 2, xmlquery.length());
1361
     }
1362
     else
1363
     {
1364
       return xmlquery;
1365
     }
1366
   }
1367

    
1368

    
1369
    /*
1370
     * A method to search if Vector contains a particular key string
1371
     */
1372
    private boolean containsKey(Vector parentidList, String parentId)
1373
    {
1374

    
1375
        Vector tempVector = null;
1376

    
1377
        for (int count = 0; count < parentidList.size(); count++) {
1378
            tempVector = (Vector) parentidList.get(count);
1379
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1380
        }
1381
        return false;
1382
    }
1383

    
1384
    /*
1385
     * A method to put key and value in Vector
1386
     */
1387
    private void putInArray(Vector parentidList, String key,
1388
            ReturnFieldValue value)
1389
    {
1390

    
1391
        Vector tempVector = null;
1392

    
1393
        for (int count = 0; count < parentidList.size(); count++) {
1394
            tempVector = (Vector) parentidList.get(count);
1395

    
1396
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1397
                tempVector.remove(1);
1398
                tempVector.add(1, value);
1399
                return;
1400
            }
1401
        }
1402

    
1403
        tempVector = new Vector();
1404
        tempVector.add(0, key);
1405
        tempVector.add(1, value);
1406
        parentidList.add(tempVector);
1407
        return;
1408
    }
1409

    
1410
    /*
1411
     * A method to get value in Vector given a key
1412
     */
1413
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1414
    {
1415

    
1416
        Vector tempVector = null;
1417

    
1418
        for (int count = 0; count < parentidList.size(); count++) {
1419
            tempVector = (Vector) parentidList.get(count);
1420

    
1421
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1422
                    .get(1); }
1423
        }
1424
        return null;
1425
    }
1426

    
1427
    /*
1428
     * A method to get enumeration of all values in Vector
1429
     */
1430
    private Vector getElements(Vector parentidList)
1431
    {
1432
        Vector enumVector = new Vector();
1433
        Vector tempVector = null;
1434

    
1435
        for (int count = 0; count < parentidList.size(); count++) {
1436
            tempVector = (Vector) parentidList.get(count);
1437

    
1438
            enumVector.add(tempVector.get(1));
1439
        }
1440
        return enumVector;
1441
    }
1442

    
1443
    /*
1444
     * A method to return search result after running a query which return
1445
     * field have attribue
1446
     */
1447
    private ResultDocumentSet getAttributeValueForReturn(QuerySpecification squery,
1448
            ResultDocumentSet docInformationList, String docList, boolean useXMLIndex)
1449
    {
1450
        StringBuffer XML = null;
1451
        String sql = null;
1452
        DBConnection dbconn = null;
1453
        PreparedStatement pstmt = null;
1454
        ResultSet rs = null;
1455
        int serialNumber = -1;
1456
        boolean tableHasRows = false;
1457

    
1458
        //check the parameter
1459
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1460

    
1461
        // if has attribute as return field
1462
        if (squery.containsAttributeReturnField()) {
1463
            sql = squery.printAttributeQuery(docList, useXMLIndex);
1464
            try {
1465
                dbconn = DBConnectionPool
1466
                        .getDBConnection("DBQuery.getAttributeValue");
1467
                serialNumber = dbconn.getCheckOutSerialNumber();
1468
                pstmt = dbconn.prepareStatement(sql);
1469
                pstmt.execute();
1470
                rs = pstmt.getResultSet();
1471
                tableHasRows = rs.next();
1472
                while (tableHasRows) {
1473
                    String docid = rs.getString(1).trim();
1474
                    String fieldname = rs.getString(2);
1475
                    String fielddata = rs.getString(3);
1476
                    String attirbuteName = rs.getString(4);
1477
                    XML = new StringBuffer();
1478

    
1479
                    XML.append("<param name=\"");
1480
                    XML.append(fieldname);
1481
                    XML.append("/");
1482
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1483
                    XML.append(attirbuteName);
1484
                    XML.append("\">");
1485
                    XML.append(fielddata);
1486
                    XML.append("</param>");
1487
                    tableHasRows = rs.next();
1488

    
1489
                    if (docInformationList.containsDocid(docid)) {
1490
                        String removedelement = (String) docInformationList
1491
                                .remove(docid);
1492
                        docInformationList.put(docid, removedelement
1493
                                + XML.toString());
1494
                    } else {
1495
                        docInformationList.put(docid, XML.toString());
1496
                    }
1497
                }//while
1498
                rs.close();
1499
                pstmt.close();
1500
            } catch (Exception se) {
1501
                logMetacat.error(
1502
                        "Error in DBQuery.getAttributeValue1: "
1503
                                + se.getMessage());
1504
            } finally {
1505
                try {
1506
                    pstmt.close();
1507
                }//try
1508
                catch (SQLException sqlE) {
1509
                    logMetacat.error(
1510
                            "Error in DBQuery.getAttributeValue2: "
1511
                                    + sqlE.getMessage());
1512
                }//catch
1513
                finally {
1514
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
1515
                }//finally
1516
            }//finally
1517
        }//if
1518
        return docInformationList;
1519

    
1520
    }
1521

    
1522
    /*
1523
     * A method to create a query to get owner's docid list
1524
     */
1525
    private String getOwnerQuery(String owner)
1526
    {
1527
        if (owner != null) {
1528
            owner = owner.toLowerCase();
1529
        }
1530
        StringBuffer self = new StringBuffer();
1531

    
1532
        self.append("SELECT docid,docname,doctype,");
1533
        self.append("date_created, date_updated, rev ");
1534
        self.append("FROM xml_documents WHERE docid IN (");
1535
        self.append("(");
1536
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1537
        self.append("nodedata LIKE '%%%' ");
1538
        self.append(") \n");
1539
        self.append(") ");
1540
        self.append(" AND (");
1541
        self.append(" lower(user_owner) = '" + owner + "'");
1542
        self.append(") ");
1543
        return self.toString();
1544
    }
1545

    
1546
    /**
1547
     * format a structured query as an XML document that conforms to the
1548
     * pathquery.dtd and is appropriate for submission to the DBQuery
1549
     * structured query engine
1550
     *
1551
     * @param params The list of parameters that should be included in the
1552
     *            query
1553
     */
1554
    public static String createSQuery(Hashtable params)
1555
    {
1556
        StringBuffer query = new StringBuffer();
1557
        Enumeration elements;
1558
        Enumeration keys;
1559
        String filterDoctype = null;
1560
        String casesensitive = null;
1561
        String searchmode = null;
1562
        Object nextkey;
1563
        Object nextelement;
1564
        //add the xml headers
1565
        query.append("<?xml version=\"1.0\"?>\n");
1566
        query.append("<pathquery version=\"1.2\">\n");
1567

    
1568

    
1569

    
1570
        if (params.containsKey("meta_file_id")) {
1571
            query.append("<meta_file_id>");
1572
            query.append(((String[]) params.get("meta_file_id"))[0]);
1573
            query.append("</meta_file_id>");
1574
        }
1575

    
1576
        if (params.containsKey("returndoctype")) {
1577
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1578
            for (int i = 0; i < returnDoctypes.length; i++) {
1579
                String doctype = (String) returnDoctypes[i];
1580

    
1581
                if (!doctype.equals("any") && !doctype.equals("ANY")
1582
                        && !doctype.equals("")) {
1583
                    query.append("<returndoctype>").append(doctype);
1584
                    query.append("</returndoctype>");
1585
                }
1586
            }
1587
        }
1588

    
1589
        if (params.containsKey("filterdoctype")) {
1590
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1591
            for (int i = 0; i < filterDoctypes.length; i++) {
1592
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1593
                query.append("</filterdoctype>");
1594
            }
1595
        }
1596

    
1597
        if (params.containsKey("returnfield")) {
1598
            String[] returnfield = ((String[]) params.get("returnfield"));
1599
            for (int i = 0; i < returnfield.length; i++) {
1600
                query.append("<returnfield>").append(returnfield[i]);
1601
                query.append("</returnfield>");
1602
            }
1603
        }
1604

    
1605
        if (params.containsKey("owner")) {
1606
            String[] owner = ((String[]) params.get("owner"));
1607
            for (int i = 0; i < owner.length; i++) {
1608
                query.append("<owner>").append(owner[i]);
1609
                query.append("</owner>");
1610
            }
1611
        }
1612

    
1613
        if (params.containsKey("site")) {
1614
            String[] site = ((String[]) params.get("site"));
1615
            for (int i = 0; i < site.length; i++) {
1616
                query.append("<site>").append(site[i]);
1617
                query.append("</site>");
1618
            }
1619
        }
1620

    
1621
        //allows the dynamic switching of boolean operators
1622
        if (params.containsKey("operator")) {
1623
            query.append("<querygroup operator=\""
1624
                    + ((String[]) params.get("operator"))[0] + "\">");
1625
        } else { //the default operator is UNION
1626
            query.append("<querygroup operator=\"UNION\">");
1627
        }
1628

    
1629
        if (params.containsKey("casesensitive")) {
1630
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1631
        } else {
1632
            casesensitive = "false";
1633
        }
1634

    
1635
        if (params.containsKey("searchmode")) {
1636
            searchmode = ((String[]) params.get("searchmode"))[0];
1637
        } else {
1638
            searchmode = "contains";
1639
        }
1640

    
1641
        //anyfield is a special case because it does a
1642
        //free text search. It does not have a <pathexpr>
1643
        //tag. This allows for a free text search within the structured
1644
        //query. This is useful if the INTERSECT operator is used.
1645
        if (params.containsKey("anyfield")) {
1646
            String[] anyfield = ((String[]) params.get("anyfield"));
1647
            //allow for more than one value for anyfield
1648
            for (int i = 0; i < anyfield.length; i++) {
1649
                if (!anyfield[i].equals("")) {
1650
                    query.append("<queryterm casesensitive=\"" + casesensitive
1651
                            + "\" " + "searchmode=\"" + searchmode
1652
                            + "\"><value>" + anyfield[i]
1653
                            + "</value></queryterm>");
1654
                }
1655
            }
1656
        }
1657

    
1658
        //this while loop finds the rest of the parameters
1659
        //and attempts to query for the field specified
1660
        //by the parameter.
1661
        elements = params.elements();
1662
        keys = params.keys();
1663
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1664
            nextkey = keys.nextElement();
1665
            nextelement = elements.nextElement();
1666

    
1667
            //make sure we aren't querying for any of these
1668
            //parameters since the are already in the query
1669
            //in one form or another.
1670
            Vector ignoredParams = new Vector();
1671
            ignoredParams.add("returndoctype");
1672
            ignoredParams.add("filterdoctype");
1673
            ignoredParams.add("action");
1674
            ignoredParams.add("qformat");
1675
            ignoredParams.add("anyfield");
1676
            ignoredParams.add("returnfield");
1677
            ignoredParams.add("owner");
1678
            ignoredParams.add("site");
1679
            ignoredParams.add("operator");
1680
            ignoredParams.add("sessionid");
1681
            ignoredParams.add("pagesize");
1682
            ignoredParams.add("pagestart");
1683

    
1684
            // Also ignore parameters listed in the properties file
1685
            // so that they can be passed through to stylesheets
1686
            String paramsToIgnore = MetaCatUtil
1687
                    .getOption("query.ignored.params");
1688
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1689
            while (st.hasMoreTokens()) {
1690
                ignoredParams.add(st.nextToken());
1691
            }
1692
            if (!ignoredParams.contains(nextkey.toString())) {
1693
                //allow for more than value per field name
1694
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1695
                    if (!((String[]) nextelement)[i].equals("")) {
1696
                        query.append("<queryterm casesensitive=\""
1697
                                + casesensitive + "\" " + "searchmode=\""
1698
                                + searchmode + "\">" + "<value>" +
1699
                                //add the query value
1700
                                ((String[]) nextelement)[i]
1701
                                + "</value><pathexpr>" +
1702
                                //add the path to query by
1703
                                nextkey.toString() + "</pathexpr></queryterm>");
1704
                    }
1705
                }
1706
            }
1707
        }
1708
        query.append("</querygroup></pathquery>");
1709
        //append on the end of the xml and return the result as a string
1710
        return query.toString();
1711
    }
1712

    
1713
    /**
1714
     * format a simple free-text value query as an XML document that conforms
1715
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1716
     * structured query engine
1717
     *
1718
     * @param value the text string to search for in the xml catalog
1719
     * @param doctype the type of documents to include in the result set -- use
1720
     *            "any" or "ANY" for unfiltered result sets
1721
     */
1722
    public static String createQuery(String value, String doctype)
1723
    {
1724
        StringBuffer xmlquery = new StringBuffer();
1725
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1726
        xmlquery.append("<pathquery version=\"1.0\">");
1727

    
1728
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1729
            xmlquery.append("<returndoctype>");
1730
            xmlquery.append(doctype).append("</returndoctype>");
1731
        }
1732

    
1733
        xmlquery.append("<querygroup operator=\"UNION\">");
1734
        //chad added - 8/14
1735
        //the if statement allows a query to gracefully handle a null
1736
        //query. Without this if a nullpointerException is thrown.
1737
        if (!value.equals("")) {
1738
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1739
            xmlquery.append("searchmode=\"contains\">");
1740
            xmlquery.append("<value>").append(value).append("</value>");
1741
            xmlquery.append("</queryterm>");
1742
        }
1743
        xmlquery.append("</querygroup>");
1744
        xmlquery.append("</pathquery>");
1745

    
1746
        return (xmlquery.toString());
1747
    }
1748

    
1749
    /**
1750
     * format a simple free-text value query as an XML document that conforms
1751
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1752
     * structured query engine
1753
     *
1754
     * @param value the text string to search for in the xml catalog
1755
     */
1756
    public static String createQuery(String value)
1757
    {
1758
        return createQuery(value, "any");
1759
    }
1760

    
1761
    /**
1762
     * Check for "READ" permission on @docid for @user and/or @group from DB
1763
     * connection
1764
     */
1765
    private boolean hasPermission(String user, String[] groups, String docid)
1766
            throws SQLException, Exception
1767
    {
1768
        // Check for READ permission on @docid for @user and/or @groups
1769
        PermissionController controller = new PermissionController(docid);
1770
        return controller.hasPermission(user, groups,
1771
                AccessControlInterface.READSTRING);
1772
    }
1773

    
1774
    /**
1775
     * Get all docIds list for a data packadge
1776
     *
1777
     * @param dataPackageDocid, the string in docId field of xml_relation table
1778
     */
1779
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1780
    {
1781
        DBConnection dbConn = null;
1782
        int serialNumber = -1;
1783
        Vector docIdList = new Vector();//return value
1784
        PreparedStatement pStmt = null;
1785
        ResultSet rs = null;
1786
        String docIdInSubjectField = null;
1787
        String docIdInObjectField = null;
1788

    
1789
        // Check the parameter
1790
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1791

    
1792
        //the query stirng
1793
        String query = "SELECT subject, object from xml_relation where docId = ?";
1794
        try {
1795
            dbConn = DBConnectionPool
1796
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1797
            serialNumber = dbConn.getCheckOutSerialNumber();
1798
            pStmt = dbConn.prepareStatement(query);
1799
            //bind the value to query
1800
            pStmt.setString(1, dataPackageDocid);
1801

    
1802
            //excute the query
1803
            pStmt.execute();
1804
            //get the result set
1805
            rs = pStmt.getResultSet();
1806
            //process the result
1807
            while (rs.next()) {
1808
                //In order to get the whole docIds in a data packadge,
1809
                //we need to put the docIds of subject and object field in
1810
                // xml_relation
1811
                //into the return vector
1812
                docIdInSubjectField = rs.getString(1);//the result docId in
1813
                                                      // subject field
1814
                docIdInObjectField = rs.getString(2);//the result docId in
1815
                                                     // object field
1816

    
1817
                //don't put the duplicate docId into the vector
1818
                if (!docIdList.contains(docIdInSubjectField)) {
1819
                    docIdList.add(docIdInSubjectField);
1820
                }
1821

    
1822
                //don't put the duplicate docId into the vector
1823
                if (!docIdList.contains(docIdInObjectField)) {
1824
                    docIdList.add(docIdInObjectField);
1825
                }
1826
            }//while
1827
            //close the pStmt
1828
            pStmt.close();
1829
        }//try
1830
        catch (SQLException e) {
1831
            logMetacat.error("Error in getDocidListForDataPackage: "
1832
                    + e.getMessage());
1833
        }//catch
1834
        finally {
1835
            try {
1836
                pStmt.close();
1837
            }//try
1838
            catch (SQLException ee) {
1839
                logMetacat.error(
1840
                        "Error in getDocidListForDataPackage: "
1841
                                + ee.getMessage());
1842
            }//catch
1843
            finally {
1844
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1845
            }//fianlly
1846
        }//finally
1847
        return docIdList;
1848
    }//getCurrentDocidListForDataPackadge()
1849

    
1850
    /**
1851
     * Get all docIds list for a data packadge
1852
     *
1853
     * @param dataPackageDocid, the string in docId field of xml_relation table
1854
     */
1855
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1856
    {
1857

    
1858
        Vector docIdList = new Vector();//return value
1859
        Vector tripleList = null;
1860
        String xml = null;
1861

    
1862
        // Check the parameter
1863
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1864

    
1865
        try {
1866
            //initial a documentImpl object
1867
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1868
            //transfer to documentImpl object to string
1869
            xml = packageDocument.toString();
1870

    
1871
            //create a tripcollection object
1872
            TripleCollection tripleForPackage = new TripleCollection(
1873
                    new StringReader(xml));
1874
            //get the vetor of triples
1875
            tripleList = tripleForPackage.getCollection();
1876

    
1877
            for (int i = 0; i < tripleList.size(); i++) {
1878
                //put subject docid into docIdlist without duplicate
1879
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1880
                        .getSubject())) {
1881
                    //put subject docid into docIdlist
1882
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1883
                }
1884
                //put object docid into docIdlist without duplicate
1885
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1886
                        .getObject())) {
1887
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1888
                }
1889
            }//for
1890
        }//try
1891
        catch (Exception e) {
1892
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1893
                    + e.getMessage());
1894
        }//catch
1895

    
1896
        // return result
1897
        return docIdList;
1898
    }//getDocidListForPackageInXMLRevisions()
1899

    
1900
    /**
1901
     * Check if the docId is a data packadge id. If the id is a data packadage
1902
     * id, it should be store in the docId fields in xml_relation table. So we
1903
     * can use a query to get the entries which the docId equals the given
1904
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1905
     * it is.
1906
     *
1907
     * @param docId, the id need to be checked
1908
     */
1909
    private boolean isDataPackageId(String docId)
1910
    {
1911
        boolean result = false;
1912
        PreparedStatement pStmt = null;
1913
        ResultSet rs = null;
1914
        String query = "SELECT docId from xml_relation where docId = ?";
1915
        DBConnection dbConn = null;
1916
        int serialNumber = -1;
1917
        try {
1918
            dbConn = DBConnectionPool
1919
                    .getDBConnection("DBQuery.isDataPackageId");
1920
            serialNumber = dbConn.getCheckOutSerialNumber();
1921
            pStmt = dbConn.prepareStatement(query);
1922
            //bind the value to query
1923
            pStmt.setString(1, docId);
1924
            //execute the query
1925
            pStmt.execute();
1926
            rs = pStmt.getResultSet();
1927
            //process the result
1928
            if (rs.next()) //There are some records for the id in docId fields
1929
            {
1930
                result = true;//It is a data packadge id
1931
            }
1932
            pStmt.close();
1933
        }//try
1934
        catch (SQLException e) {
1935
            logMetacat.error("Error in isDataPackageId: "
1936
                    + e.getMessage());
1937
        } finally {
1938
            try {
1939
                pStmt.close();
1940
            }//try
1941
            catch (SQLException ee) {
1942
                logMetacat.error("Error in isDataPackageId: "
1943
                        + ee.getMessage());
1944
            }//catch
1945
            finally {
1946
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1947
            }//finally
1948
        }//finally
1949
        return result;
1950
    }//isDataPackageId()
1951

    
1952
    /**
1953
     * Check if the user has the permission to export data package
1954
     *
1955
     * @param conn, the connection
1956
     * @param docId, the id need to be checked
1957
     * @param user, the name of user
1958
     * @param groups, the user's group
1959
     */
1960
    private boolean hasPermissionToExportPackage(String docId, String user,
1961
            String[] groups) throws Exception
1962
    {
1963
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1964
        return DocumentImpl.hasReadPermission(user, groups, docId);
1965
    }
1966

    
1967
    /**
1968
     * Get the current Rev for a docid in xml_documents table
1969
     *
1970
     * @param docId, the id need to get version numb If the return value is -5,
1971
     *            means no value in rev field for this docid
1972
     */
1973
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1974
            throws SQLException
1975
    {
1976
        int rev = -5;
1977
        PreparedStatement pStmt = null;
1978
        ResultSet rs = null;
1979
        String query = "SELECT rev from xml_documents where docId = ?";
1980
        DBConnection dbConn = null;
1981
        int serialNumber = -1;
1982
        try {
1983
            dbConn = DBConnectionPool
1984
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1985
            serialNumber = dbConn.getCheckOutSerialNumber();
1986
            pStmt = dbConn.prepareStatement(query);
1987
            //bind the value to query
1988
            pStmt.setString(1, docId);
1989
            //execute the query
1990
            pStmt.execute();
1991
            rs = pStmt.getResultSet();
1992
            //process the result
1993
            if (rs.next()) //There are some records for rev
1994
            {
1995
                rev = rs.getInt(1);
1996
                ;//It is the version for given docid
1997
            } else {
1998
                rev = -5;
1999
            }
2000

    
2001
        }//try
2002
        catch (SQLException e) {
2003
            logMetacat.error(
2004
                    "Error in getCurrentRevFromXMLDoumentsTable: "
2005
                            + e.getMessage());
2006
            throw e;
2007
        }//catch
2008
        finally {
2009
            try {
2010
                pStmt.close();
2011
            }//try
2012
            catch (SQLException ee) {
2013
                logMetacat.error(
2014
                        "Error in getCurrentRevFromXMLDoumentsTable: "
2015
                                + ee.getMessage());
2016
            }//catch
2017
            finally {
2018
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2019
            }//finally
2020
        }//finally
2021
        return rev;
2022
    }//getCurrentRevFromXMLDoumentsTable
2023

    
2024
    /**
2025
     * put a doc into a zip output stream
2026
     *
2027
     * @param docImpl, docmentImpl object which will be sent to zip output
2028
     *            stream
2029
     * @param zipOut, zip output stream which the docImpl will be put
2030
     * @param packageZipEntry, the zip entry name for whole package
2031
     */
2032
    private void addDocToZipOutputStream(DocumentImpl docImpl,
2033
            ZipOutputStream zipOut, String packageZipEntry)
2034
            throws ClassNotFoundException, IOException, SQLException,
2035
            McdbException, Exception
2036
    {
2037
        byte[] byteString = null;
2038
        ZipEntry zEntry = null;
2039

    
2040
        byteString = docImpl.toString().getBytes();
2041
        //use docId as the zip entry's name
2042
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
2043
                + docImpl.getDocID());
2044
        zEntry.setSize(byteString.length);
2045
        zipOut.putNextEntry(zEntry);
2046
        zipOut.write(byteString, 0, byteString.length);
2047
        zipOut.closeEntry();
2048

    
2049
    }//addDocToZipOutputStream()
2050

    
2051
    /**
2052
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
2053
     * only inlcudes current version. If a DocumentImple object couldn't find
2054
     * for a docid, then the String of this docid was added to vetor rather
2055
     * than DocumentImple object.
2056
     *
2057
     * @param docIdList, a vetor hold a docid list for a data package. In
2058
     *            docid, there is not version number in it.
2059
     */
2060

    
2061
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2062
            throws McdbException, Exception
2063
    {
2064
        //Connection dbConn=null;
2065
        Vector documentImplList = new Vector();
2066
        int rev = 0;
2067

    
2068
        // Check the parameter
2069
        if (docIdList.isEmpty()) { return documentImplList; }//if
2070

    
2071
        //for every docid in vector
2072
        for (int i = 0; i < docIdList.size(); i++) {
2073
            try {
2074
                //get newest version for this docId
2075
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2076
                        .elementAt(i));
2077

    
2078
                // There is no record for this docId in xml_documents table
2079
                if (rev == -5) {
2080
                    // Rather than put DocumentImple object, put a String
2081
                    // Object(docid)
2082
                    // into the documentImplList
2083
                    documentImplList.add((String) docIdList.elementAt(i));
2084
                    // Skip other code
2085
                    continue;
2086
                }
2087

    
2088
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2089
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
2090

    
2091
                //create new documentImpl object
2092
                DocumentImpl documentImplObject = new DocumentImpl(
2093
                        docidPlusVersion);
2094
                //add them to vector
2095
                documentImplList.add(documentImplObject);
2096
            }//try
2097
            catch (Exception e) {
2098
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
2099
                        + e.getMessage());
2100
                // continue the for loop
2101
                continue;
2102
            }
2103
        }//for
2104
        return documentImplList;
2105
    }
2106

    
2107
    /**
2108
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2109
     * object couldn't find for a docid, then the String of this docid was
2110
     * added to vetor rather than DocumentImple object.
2111
     *
2112
     * @param docIdList, a vetor hold a docid list for a data package. In
2113
     *            docid, t here is version number in it.
2114
     */
2115
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2116
    {
2117
        //Connection dbConn=null;
2118
        Vector documentImplList = new Vector();
2119
        String siteCode = null;
2120
        String uniqueId = null;
2121
        int rev = 0;
2122

    
2123
        // Check the parameter
2124
        if (docIdList.isEmpty()) { return documentImplList; }//if
2125

    
2126
        //for every docid in vector
2127
        for (int i = 0; i < docIdList.size(); i++) {
2128

    
2129
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2130

    
2131
            try {
2132
                //create new documentImpl object
2133
                DocumentImpl documentImplObject = new DocumentImpl(
2134
                        docidPlusVersion);
2135
                //add them to vector
2136
                documentImplList.add(documentImplObject);
2137
            }//try
2138
            catch (McdbDocNotFoundException notFoundE) {
2139
                logMetacat.error(
2140
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2141
                                + notFoundE.getMessage());
2142
                // Rather than add a DocumentImple object into vetor, a String
2143
                // object
2144
                // - the doicd was added to the vector
2145
                documentImplList.add(docidPlusVersion);
2146
                // Continue the for loop
2147
                continue;
2148
            }//catch
2149
            catch (Exception e) {
2150
                logMetacat.error(
2151
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2152
                                + e.getMessage());
2153
                // Continue the for loop
2154
                continue;
2155
            }//catch
2156

    
2157
        }//for
2158
        return documentImplList;
2159
    }//getOldVersionAllDocumentImple
2160

    
2161
    /**
2162
     * put a data file into a zip output stream
2163
     *
2164
     * @param docImpl, docmentImpl object which will be sent to zip output
2165
     *            stream
2166
     * @param zipOut, the zip output stream which the docImpl will be put
2167
     * @param packageZipEntry, the zip entry name for whole package
2168
     */
2169
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2170
            ZipOutputStream zipOut, String packageZipEntry)
2171
            throws ClassNotFoundException, IOException, SQLException,
2172
            McdbException, Exception
2173
    {
2174
        byte[] byteString = null;
2175
        ZipEntry zEntry = null;
2176
        // this is data file; add file to zip
2177
        String filePath = MetaCatUtil.getOption("datafilepath");
2178
        if (!filePath.endsWith("/")) {
2179
            filePath += "/";
2180
        }
2181
        String fileName = filePath + docImpl.getDocID();
2182
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2183
        zipOut.putNextEntry(zEntry);
2184
        FileInputStream fin = null;
2185
        try {
2186
            fin = new FileInputStream(fileName);
2187
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2188
            int b = fin.read(buf);
2189
            while (b != -1) {
2190
                zipOut.write(buf, 0, b);
2191
                b = fin.read(buf);
2192
            }//while
2193
            zipOut.closeEntry();
2194
        }//try
2195
        catch (IOException ioe) {
2196
            logMetacat.error("There is an exception: "
2197
                    + ioe.getMessage());
2198
        }//catch
2199
    }//addDataFileToZipOutputStream()
2200

    
2201
    /**
2202
     * create a html summary for data package and put it into zip output stream
2203
     *
2204
     * @param docImplList, the documentImpl ojbects in data package
2205
     * @param zipOut, the zip output stream which the html should be put
2206
     * @param packageZipEntry, the zip entry name for whole package
2207
     */
2208
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2209
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2210
    {
2211
        StringBuffer htmlDoc = new StringBuffer();
2212
        ZipEntry zEntry = null;
2213
        byte[] byteString = null;
2214
        InputStream source;
2215
        DBTransform xmlToHtml;
2216

    
2217
        //create a DBTransform ojbect
2218
        xmlToHtml = new DBTransform();
2219
        //head of html
2220
        htmlDoc.append("<html><head></head><body>");
2221
        for (int i = 0; i < docImplList.size(); i++) {
2222
            // If this String object, this means it is missed data file
2223
            if ((((docImplList.elementAt(i)).getClass()).toString())
2224
                    .equals("class java.lang.String")) {
2225

    
2226
                htmlDoc.append("<a href=\"");
2227
                String dataFileid = (String) docImplList.elementAt(i);
2228
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2229
                htmlDoc.append("Data File: ");
2230
                htmlDoc.append(dataFileid).append("</a><br>");
2231
                htmlDoc.append("<br><hr><br>");
2232

    
2233
            }//if
2234
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2235
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2236
                                              // transform it.
2237
                //transform each file individually then concatenate all of the
2238
                //transformations together.
2239

    
2240
                //for metadata xml title
2241
                htmlDoc.append("<h2>");
2242
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2243
                        .getDocID());
2244
                //htmlDoc.append(".");
2245
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2246
                htmlDoc.append("</h2>");
2247
                //do the actual transform
2248
                StringWriter docString = new StringWriter();
2249
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2250
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2251
                        "-//W3C//HTML//EN", "html", docString);
2252
                htmlDoc.append(docString.toString());
2253
                htmlDoc.append("<br><br><hr><br><br>");
2254
            }//if
2255
            else { //this is a data file so we should link to it in the html
2256
                htmlDoc.append("<a href=\"");
2257
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2258
                        .getDocID();
2259
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2260
                htmlDoc.append("Data File: ");
2261
                htmlDoc.append(dataFileid).append("</a><br>");
2262
                htmlDoc.append("<br><hr><br>");
2263
            }//else
2264
        }//for
2265
        htmlDoc.append("</body></html>");
2266
        byteString = htmlDoc.toString().getBytes();
2267
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2268
        zEntry.setSize(byteString.length);
2269
        zipOut.putNextEntry(zEntry);
2270
        zipOut.write(byteString, 0, byteString.length);
2271
        zipOut.closeEntry();
2272
        //dbConn.close();
2273

    
2274
    }//addHtmlSummaryToZipOutputStream
2275

    
2276
    /**
2277
     * put a data packadge into a zip output stream
2278
     *
2279
     * @param docId, which the user want to put into zip output stream,it has version
2280
     * @param out, a servletoutput stream which the zip output stream will be
2281
     *            put
2282
     * @param user, the username of the user
2283
     * @param groups, the group of the user
2284
     */
2285
    public ZipOutputStream getZippedPackage(String docIdString,
2286
            ServletOutputStream out, String user, String[] groups,
2287
            String passWord) throws ClassNotFoundException, IOException,
2288
            SQLException, McdbException, NumberFormatException, Exception
2289
    {
2290
        ZipOutputStream zOut = null;
2291
        String elementDocid = null;
2292
        DocumentImpl docImpls = null;
2293
        //Connection dbConn = null;
2294
        Vector docIdList = new Vector();
2295
        Vector documentImplList = new Vector();
2296
        Vector htmlDocumentImplList = new Vector();
2297
        String packageId = null;
2298
        String rootName = "package";//the package zip entry name
2299

    
2300
        String docId = null;
2301
        int version = -5;
2302
        // Docid without revision
2303
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2304
        // revision number
2305
        version = MetaCatUtil.getVersionFromString(docIdString);
2306

    
2307
        //check if the reqused docId is a data package id
2308
        if (!isDataPackageId(docId)) {
2309

    
2310
            /*
2311
             * Exception e = new Exception("The request the doc id "
2312
             * +docIdString+ " is not a data package id");
2313
             */
2314

    
2315
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2316
            // zip
2317
            //up the single document and return the zip file.
2318
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2319

    
2320
                Exception e = new Exception("User " + user
2321
                        + " does not have permission"
2322
                        + " to export the data package " + docIdString);
2323
                throw e;
2324
            }
2325

    
2326
            docImpls = new DocumentImpl(docIdString);
2327
            //checking if the user has the permission to read the documents
2328
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2329
                    .getDocID())) {
2330
                zOut = new ZipOutputStream(out);
2331
                //if the docImpls is metadata
2332
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2333
                    //add metadata into zip output stream
2334
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2335
                }//if
2336
                else {
2337
                    //it is data file
2338
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2339
                    htmlDocumentImplList.add(docImpls);
2340
                }//else
2341
            }//if
2342

    
2343
            zOut.finish(); //terminate the zip file
2344
            return zOut;
2345
        }
2346
        // Check the permission of user
2347
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2348

    
2349
            Exception e = new Exception("User " + user
2350
                    + " does not have permission"
2351
                    + " to export the data package " + docIdString);
2352
            throw e;
2353
        } else //it is a packadge id
2354
        {
2355
            //store the package id
2356
            packageId = docId;
2357
            //get current version in database
2358
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2359
            //If it is for current version (-1 means user didn't specify
2360
            // revision)
2361
            if ((version == -1) || version == currentVersion) {
2362
                //get current version number
2363
                version = currentVersion;
2364
                //get package zip entry name
2365
                //it should be docId.revsion.package
2366
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2367
                        + version + MetaCatUtil.getOption("accNumSeparator")
2368
                        + "package";
2369
                //get the whole id list for data packadge
2370
                docIdList = getCurrentDocidListForDataPackage(packageId);
2371
                //get the whole documentImple object
2372
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2373

    
2374
            }//if
2375
            else if (version > currentVersion || version < -1) {
2376
                throw new Exception("The user specified docid: " + docId + "."
2377
                        + version + " doesn't exist");
2378
            }//else if
2379
            else //for an old version
2380
            {
2381

    
2382
                rootName = docIdString
2383
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2384
                //get the whole id list for data packadge
2385
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2386

    
2387
                //get the whole documentImple object
2388
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2389
            }//else
2390

    
2391
            // Make sure documentImplist is not empty
2392
            if (documentImplList.isEmpty()) { throw new Exception(
2393
                    "Couldn't find component for data package: " + packageId); }//if
2394

    
2395
            zOut = new ZipOutputStream(out);
2396
            //put every element into zip output stream
2397
            for (int i = 0; i < documentImplList.size(); i++) {
2398
                // if the object in the vetor is String, this means we couldn't
2399
                // find
2400
                // the document locally, we need find it remote
2401
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2402
                        .equals("class java.lang.String")) {
2403
                    // Get String object from vetor
2404
                    String documentId = (String) documentImplList.elementAt(i);
2405
                    logMetacat.info("docid: " + documentId);
2406
                    // Get doicd without revision
2407
                    String docidWithoutRevision = MetaCatUtil
2408
                            .getDocIdFromString(documentId);
2409
                    logMetacat.info("docidWithoutRevsion: "
2410
                            + docidWithoutRevision);
2411
                    // Get revision
2412
                    String revision = MetaCatUtil
2413
                            .getRevisionStringFromString(documentId);
2414
                    logMetacat.info("revsion from docIdentifier: "
2415
                            + revision);
2416
                    // Zip entry string
2417
                    String zipEntryPath = rootName + "/data/";
2418
                    // Create a RemoteDocument object
2419
                    RemoteDocument remoteDoc = new RemoteDocument(
2420
                            docidWithoutRevision, revision, user, passWord,
2421
                            zipEntryPath);
2422
                    // Here we only read data file from remote metacat
2423
                    String docType = remoteDoc.getDocType();
2424
                    if (docType != null) {
2425
                        if (docType.equals("BIN")) {
2426
                            // Put remote document to zip output
2427
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2428
                            // Add String object to htmlDocumentImplList
2429
                            String elementInHtmlList = remoteDoc
2430
                                    .getDocIdWithoutRevsion()
2431
                                    + MetaCatUtil.getOption("accNumSeparator")
2432
                                    + remoteDoc.getRevision();
2433
                            htmlDocumentImplList.add(elementInHtmlList);
2434
                        }//if
2435
                    }//if
2436

    
2437
                }//if
2438
                else {
2439
                    //create a docmentImpls object (represent xml doc) base on
2440
                    // the docId
2441
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2442
                    //checking if the user has the permission to read the
2443
                    // documents
2444
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2445
                            .getDocID())) {
2446
                        //if the docImpls is metadata
2447
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2448
                            //add metadata into zip output stream
2449
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2450
                            //add the documentImpl into the vetor which will
2451
                            // be used in html
2452
                            htmlDocumentImplList.add(docImpls);
2453

    
2454
                        }//if
2455
                        else {
2456
                            //it is data file
2457
                            addDataFileToZipOutputStream(docImpls, zOut,
2458
                                    rootName);
2459
                            htmlDocumentImplList.add(docImpls);
2460
                        }//else
2461
                    }//if
2462
                }//else
2463
            }//for
2464

    
2465
            //add html summary file
2466
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2467
                    rootName);
2468
            zOut.finish(); //terminate the zip file
2469
            //dbConn.close();
2470
            return zOut;
2471
        }//else
2472
    }//getZippedPackage()
2473

    
2474
    private class ReturnFieldValue
2475
    {
2476

    
2477
        private String docid = null; //return field value for this docid
2478

    
2479
        private String fieldValue = null;
2480

    
2481
        private String xmlFieldValue = null; //return field value in xml
2482
                                             // format
2483

    
2484
        public void setDocid(String myDocid)
2485
        {
2486
            docid = myDocid;
2487
        }
2488

    
2489
        public String getDocid()
2490
        {
2491
            return docid;
2492
        }
2493

    
2494
        public void setFieldValue(String myValue)
2495
        {
2496
            fieldValue = myValue;
2497
        }
2498

    
2499
        public String getFieldValue()
2500
        {
2501
            return fieldValue;
2502
        }
2503

    
2504
        public void setXMLFieldValue(String xml)
2505
        {
2506
            xmlFieldValue = xml;
2507
        }
2508

    
2509
        public String getXMLFieldValue()
2510
        {
2511
            return xmlFieldValue;
2512
        }
2513

    
2514
    }
2515
    
2516
    /**
2517
     * a class to store one result document consisting of a docid and a document
2518
     */
2519
    private class ResultDocument
2520
    {
2521
      public String docid;
2522
      public String document;
2523
      
2524
      public ResultDocument(String docid, String document)
2525
      {
2526
        this.docid = docid;
2527
        this.document = document;
2528
      }
2529
    }
2530
    
2531
    /**
2532
     * a private class to handle a set of resultDocuments
2533
     */
2534
    private class ResultDocumentSet
2535
    {
2536
      private Vector docids;
2537
      private Vector documents;
2538
      
2539
      public ResultDocumentSet()
2540
      {
2541
        docids = new Vector();
2542
        documents = new Vector();
2543
      }
2544
      
2545
      /**
2546
       * adds a result document to the set
2547
       */
2548
      public void addResultDocument(ResultDocument rd)
2549
      {
2550
        if(rd.docid == null)
2551
          return;
2552
        if(rd.document == null)
2553
          rd.document = "";
2554
        if (!containsDocid(rd.docid))
2555
        {
2556
           docids.addElement(rd.docid);
2557
           documents.addElement(rd.document);
2558
        }
2559
      }
2560
      
2561
      /**
2562
       * gets an iterator of docids
2563
       */
2564
      public Iterator getDocids()
2565
      {
2566
        return docids.iterator();
2567
      }
2568
      
2569
      /**
2570
       * gets an iterator of documents
2571
       */
2572
      public Iterator getDocuments()
2573
      {
2574
        return documents.iterator();
2575
      }
2576
      
2577
      /**
2578
       * returns the size of the set
2579
       */
2580
      public int size()
2581
      {
2582
        return docids.size();
2583
      }
2584
      
2585
      /**
2586
       * tests to see if this set contains the given docid
2587
       */
2588
      public boolean containsDocid(String docid)
2589
      {
2590
        for(int i=0; i<docids.size(); i++)
2591
        {
2592
          String docid0 = (String)docids.elementAt(i);
2593
          if(docid0.trim().equals(docid.trim()))
2594
          {
2595
            return true;
2596
          }
2597
        }
2598
        return false;
2599
      }
2600
      
2601
      /**
2602
       * removes the element with the given docid
2603
       */
2604
      public String remove(String docid)
2605
      {
2606
        for(int i=0; i<docids.size(); i++)
2607
        {
2608
          String docid0 = (String)docids.elementAt(i);
2609
          if(docid0.trim().equals(docid.trim()))
2610
          {
2611
            String returnDoc = (String)documents.elementAt(i);
2612
            documents.remove(i);
2613
            docids.remove(i);
2614
            return returnDoc;
2615
          }
2616
        }
2617
        return null;
2618
      }
2619
      
2620
      /**
2621
       * add a result document
2622
       */
2623
      public void put(ResultDocument rd)
2624
      {
2625
        addResultDocument(rd);
2626
      }
2627
      
2628
      /**
2629
       * add a result document by components
2630
       */
2631
      public void put(String docid, String document)
2632
      {
2633
        addResultDocument(new ResultDocument(docid, document));
2634
      }
2635
      
2636
      /**
2637
       * get the document part of the result document by docid
2638
       */
2639
      public Object get(String docid)
2640
      {
2641
        for(int i=0; i<docids.size(); i++)
2642
        {
2643
          String docid0 = (String)docids.elementAt(i);
2644
          if(docid0.trim().equals(docid.trim()))
2645
          {
2646
            return documents.elementAt(i);
2647
          }
2648
        }
2649
        return null;
2650
      }
2651
      
2652
      /**
2653
       * get the document part of the result document by an object
2654
       */
2655
      public Object get(Object o)
2656
      {
2657
        return get((String)o);
2658
      }
2659
      
2660
      /**
2661
       * get an entire result document by index number
2662
       */
2663
      public ResultDocument get(int index)
2664
      {
2665
        return new ResultDocument((String)docids.elementAt(index), 
2666
          (String)documents.elementAt(index));
2667
      }
2668
      
2669
      /**
2670
       * return a string representation of this object
2671
       */
2672
      public String toString()
2673
      {
2674
        String s = "";
2675
        for(int i=0; i<docids.size(); i++)
2676
        {
2677
          s += (String)docids.elementAt(i) + "\n";
2678
        }
2679
        return s;
2680
      }
2681
      /*
2682
       * Set a new document value for a given docid
2683
       */
2684
      public void set(String docid, String document)
2685
      {
2686
    	   for(int i=0; i<docids.size(); i++)
2687
           {
2688
             String docid0 = (String)docids.elementAt(i);
2689
             if(docid0.trim().equals(docid.trim()))
2690
             {
2691
                 documents.set(i, document);
2692
             }
2693
           }
2694
           
2695
      }
2696
    }
2697
}
(21-21/66)