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: leinfelder $'
13
 *     '$Date: 2007-12-05 12:40:06 -0800 (Wed, 05 Dec 2007) $'
14
 * '$Revision: 3635 $'
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. Since the docids can be very long,
81
         it is a vector of vector  **/
82
    Vector docidOverride = new Vector();
83
    
84
    // a hash table serves as query reuslt cache. Key of hashtable
85
    // is a query string and value is result xml string
86
    private static Hashtable queryResultCache = new Hashtable();
87
    
88
    // Capacity of the query result cache
89
    private static final int QUERYRESULTCACHESIZE = Integer.parseInt(MetaCatUtil.getOption("queryresult_cache_size"));
90

    
91
    // Size of page for non paged query
92
    private static final int NONPAGESIZE = 99999999;
93
    /**
94
     * the main routine used to test the DBQuery utility.
95
     * <p>
96
     * Usage: java DBQuery <xmlfile>
97
     *
98
     * @param xmlfile the filename of the xml file containing the query
99
     */
100
    static public void main(String[] args)
101
    {
102

    
103
        if (args.length < 1) {
104
            System.err.println("Wrong number of arguments!!!");
105
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
106
            return;
107
        } else {
108
            try {
109

    
110
                int i = 0;
111
                boolean showRuntime = false;
112
                boolean useXMLIndex = false;
113
                if (args[i].equals("-t")) {
114
                    showRuntime = true;
115
                    i++;
116
                }
117
                if (args[i].equals("-index")) {
118
                    useXMLIndex = true;
119
                    i++;
120
                }
121
                String xmlfile = args[i];
122

    
123
                // Time the request if asked for
124
                double startTime = System.currentTimeMillis();
125

    
126
                // Open a connection to the database
127
                MetaCatUtil util = new MetaCatUtil();
128
                //Connection dbconn = util.openDBConnection();
129

    
130
                double connTime = System.currentTimeMillis();
131

    
132
                // Execute the query
133
                DBQuery queryobj = new DBQuery();
134
                FileReader xml = new FileReader(new File(xmlfile));
135
                Hashtable nodelist = null;
136
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
137

    
138
                // Print the reulting document listing
139
                StringBuffer result = new StringBuffer();
140
                String document = null;
141
                String docid = null;
142
                result.append("<?xml version=\"1.0\"?>\n");
143
                result.append("<resultset>\n");
144

    
145
                if (!showRuntime) {
146
                    Enumeration doclist = nodelist.keys();
147
                    while (doclist.hasMoreElements()) {
148
                        docid = (String) doclist.nextElement();
149
                        document = (String) nodelist.get(docid);
150
                        result.append("  <document>\n    " + document
151
                                + "\n  </document>\n");
152
                    }
153

    
154
                    result.append("</resultset>\n");
155
                }
156
                // Time the request if asked for
157
                double stopTime = System.currentTimeMillis();
158
                double dbOpenTime = (connTime - startTime) / 1000;
159
                double readTime = (stopTime - connTime) / 1000;
160
                double executionTime = (stopTime - startTime) / 1000;
161
                if (showRuntime) {
162
                    System.out.print("  " + executionTime);
163
                    System.out.print("  " + dbOpenTime);
164
                    System.out.print("  " + readTime);
165
                    System.out.print("  " + nodelist.size());
166
                    System.out.println();
167
                }
168
                //System.out.println(result);
169
                //write into a file "result.txt"
170
                if (!showRuntime) {
171
                    File f = new File("./result.txt");
172
                    FileWriter fw = new FileWriter(f);
173
                    BufferedWriter out = new BufferedWriter(fw);
174
                    out.write(result.toString());
175
                    out.flush();
176
                    out.close();
177
                    fw.close();
178
                }
179

    
180
            } catch (Exception e) {
181
                System.err.println("Error in DBQuery.main");
182
                System.err.println(e.getMessage());
183
                e.printStackTrace(System.err);
184
            }
185
        }
186
    }
187

    
188
    /**
189
     * construct an instance of the DBQuery class
190
     *
191
     * <p>
192
     * Generally, one would call the findDocuments() routine after creating an
193
     * instance to specify the search query
194
     * </p>
195
     *
196

    
197
     * @param parserName the fully qualified name of a Java class implementing
198
     *            the org.xml.sax.XMLReader interface
199
     */
200
    public DBQuery()
201
    {
202
        String parserName = MetaCatUtil.getOption("saxparser");
203
        this.parserName = parserName;
204
    }
205

    
206
    /**
207
     * 
208
     * Construct an instance of DBQuery Class
209
     * BUT accept a docid Vector that will supersede
210
     * the query.printSQL() method
211
     *
212
     * If a docid Vector is passed in,
213
     * the docids will be used to create a simple IN query 
214
     * without the multiple subselects of the printSQL() method
215
     *
216
     * Using this constructor, we just check for 
217
     * a docidOverride Vector in the findResultDoclist() method
218
     *
219
     * @param docids List of docids to display in the resultset
220
     */
221
    public DBQuery(Vector docids)
222
    {
223
    	// since the query will be too long to be handled, so we divided the 
224
    	// docids vector into couple vectors.
225
    	int size = (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
226
    	logMetacat.info("The size of select doicds is "+docids.size());
227
    	logMetacat.info("The application result size in metacat.properties is "+size);
228
    	Vector subset = new Vector();
229
    	if (docids != null && docids.size() > size)
230
    	{
231
    		int index = 0;
232
    		for (int i=0; i< docids.size(); i++)
233
    		{
234
    			
235
    			if (index < size)
236
    			{  	
237
    				subset.add(docids.elementAt(i));
238
    				index ++;
239
    			}
240
    			else
241
    			{
242
    				docidOverride.add(subset);
243
    				subset = new Vector();
244
    				subset.add(docids.elementAt(i));
245
    			    index = 1;
246
    			}
247
    		}
248
    		if (!subset.isEmpty())
249
    		{
250
    			docidOverride.add(subset);
251
    		}
252
    		
253
    	}
254
    	else
255
    	{
256
    		this.docidOverride.add(docids);
257
    	}
258
        
259
        String parserName = MetaCatUtil.getOption("saxparser");
260
        this.parserName = parserName;
261
    }
262

    
263
  /**
264
   * Method put the search result set into out printerwriter
265
   * @param resoponse the return response
266
   * @param out the output printer
267
   * @param params the paratermer hashtable
268
   * @param user the user name (it maybe different to the one in param)
269
   * @param groups the group array
270
   * @param sessionid  the sessionid
271
   */
272
  public void findDocuments(HttpServletResponse response,
273
                                       PrintWriter out, Hashtable params,
274
                                       String user, String[] groups,
275
                                       String sessionid)
276
  {
277
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
278
               .booleanValue();
279
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
280

    
281
  }
282

    
283

    
284
    /**
285
     * Method put the search result set into out printerwriter
286
     * @param resoponse the return response
287
     * @param out the output printer
288
     * @param params the paratermer hashtable
289
     * @param user the user name (it maybe different to the one in param)
290
     * @param groups the group array
291
     * @param sessionid  the sessionid
292
     */
293
    public void findDocuments(HttpServletResponse response,
294
                                         PrintWriter out, Hashtable params,
295
                                         String user, String[] groups,
296
                                         String sessionid, boolean useXMLIndex)
297
    {
298
      int pagesize = 0;
299
      int pagestart = 0;
300
      
301
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
302
      {
303
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
304
        String pagestartStr = ((String[])params.get("pagestart"))[0];
305
        if(pagesizeStr != null && pagestartStr != null)
306
        {
307
          pagesize = (new Integer(pagesizeStr)).intValue();
308
          pagestart = (new Integer(pagestartStr)).intValue();
309
        }
310
      }
311
      
312
      // get query and qformat
313
      String xmlquery = ((String[])params.get("query"))[0];
314

    
315
      logMetacat.info("SESSIONID: " + sessionid);
316
      logMetacat.info("xmlquery: " + xmlquery);
317
      String qformat = ((String[])params.get("qformat"))[0];
318
      logMetacat.info("qformat: " + qformat);
319
      // Get the XML query and covert it into a SQL statment
320
      QuerySpecification qspec = null;
321
      if ( xmlquery != null)
322
      {
323
         xmlquery = transformQuery(xmlquery);
324
         try
325
         {
326
           qspec = new QuerySpecification(xmlquery,
327
                                          parserName,
328
                                          MetaCatUtil.getOption("accNumSeparator"));
329
         }
330
         catch (Exception ee)
331
         {
332
           logMetacat.error("error generating QuerySpecification object"
333
                                    +" in DBQuery.findDocuments"
334
                                    + ee.getMessage());
335
         }
336
      }
337

    
338

    
339

    
340
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
341
      {
342
        //xml format
343
        response.setContentType("text/xml");
344
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex, 
345
          pagesize, pagestart, sessionid);
346
      }//if
347
      else
348
      {
349
        //knb format, in this case we will get whole result and sent it out
350
        response.setContentType("text/html");
351
        PrintWriter nonout = null;
352
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
353
                                                groups, useXMLIndex, pagesize, 
354
                                                pagestart, sessionid);
355
        
356
        //transfer the xml to html
357
        try
358
        {
359
         double startHTMLTransform = System.currentTimeMillis()/1000;
360
         DBTransform trans = new DBTransform();
361
         response.setContentType("text/html");
362

    
363
         // if the user is a moderator, then pass a param to the 
364
         // xsl specifying the fact
365
         if(MetaCatUtil.isModerator(user, groups)){
366
        	 params.put("isModerator", new String[] {"true"});
367
         }
368

    
369
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
370
                                 "-//W3C//HTML//EN", qformat, out, params,
371
                                 sessionid);
372
         double endHTMLTransform = System.currentTimeMillis()/1000;
373
          logMetacat.warn("The time to transfrom resultset from xml to html format is "
374
                  		                             +(endHTMLTransform -startHTMLTransform));
375
          MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Transfrom xml to html  "
376
                             +(endHTMLTransform -startHTMLTransform));
377
          MetaCatUtil.writeDebugToDelimiteredFile(" "+(endHTMLTransform -startHTMLTransform), false);
378
        }
379
        catch(Exception e)
380
        {
381
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
382
                                +e.getMessage());
383
         }
384

    
385
      }//else
386

    
387
  }
388
  
389
  /**
390
   * Transforms a hashtable of documents to an xml or html result and sent
391
   * the content to outputstream. Keep going untill hastable is empty. stop it.
392
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
393
   * to xmlquery String
394
   * @param xmlquery
395
   * @param qspec
396
   * @param out
397
   * @param user
398
   * @param groups
399
   * @param useXMLIndex
400
   * @param sessionid
401
   * @return
402
   */
403
    public StringBuffer createResultDocument(String xmlquery,
404
                                              QuerySpecification qspec,
405
                                              PrintWriter out,
406
                                              String user, String[] groups,
407
                                              boolean useXMLIndex)
408
    {
409
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"");
410
    }
411

    
412
  /*
413
   * Transforms a hashtable of documents to an xml or html result and sent
414
   * the content to outputstream. Keep going untill hastable is empty. stop it.
415
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
416
   * to xmlquery String
417
   */
418
  public StringBuffer createResultDocument(String xmlquery,
419
                                            QuerySpecification qspec,
420
                                            PrintWriter out,
421
                                            String user, String[] groups,
422
                                            boolean useXMLIndex, int pagesize,
423
                                            int pagestart, String sessionid)
424
  {
425
    DBConnection dbconn = null;
426
    int serialNumber = -1;
427
    StringBuffer resultset = new StringBuffer();
428

    
429
    //try to get the cached version first    
430
    Hashtable sessionHash = MetaCatServlet.getSessionHash();
431
    HttpSession sess = (HttpSession)sessionHash.get(sessionid);
432

    
433
    
434
    resultset.append("<?xml version=\"1.0\"?>\n");
435
    resultset.append("<resultset>\n");
436
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
437
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
438
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
439
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
440

    
441
    resultset.append("  <query>" + xmlquery + "</query>");
442
    //send out a new query
443
    if (out != null)
444
    {
445
      out.println(resultset.toString());
446
    }
447
    if (qspec != null)
448
    {
449
      try
450
      {
451

    
452
        //checkout the dbconnection
453
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
454
        serialNumber = dbconn.getCheckOutSerialNumber();
455

    
456
        //print out the search result
457
        // search the doc list
458
        Vector givenDocids = new Vector();
459
        StringBuffer resultContent = new StringBuffer();
460
        if (docidOverride == null || docidOverride.size() == 0)
461
        {
462
        	logMetacat.info("Not in map query");
463
        	resultContent = findResultDoclist(qspec, out, user, groups,
464
                    dbconn, useXMLIndex, pagesize, pagestart, 
465
                    sessionid, givenDocids);
466
        }
467
        else
468
        {
469
        	logMetacat.info("In map query");
470
        	// since docid can be too long to be handled. We divide it into several parts
471
        	for (int i= 0; i<docidOverride.size(); i++)
472
        	{
473
        	   logMetacat.info("in loop===== "+i);
474
        		givenDocids = (Vector)docidOverride.elementAt(i);
475
        		StringBuffer subset = findResultDoclist(qspec, out, user, groups,
476
                        dbconn, useXMLIndex, pagesize, pagestart, 
477
                        sessionid, givenDocids);
478
        		resultContent.append(subset);
479
        	}
480
        }
481
           
482
        resultset.append(resultContent);
483
      } //try
484
      catch (IOException ioe)
485
      {
486
        logMetacat.error("IO error in DBQuery.findDocuments:");
487
        logMetacat.error(ioe.getMessage());
488

    
489
      }
490
      catch (SQLException e)
491
      {
492
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
493
                                 + e.getMessage());
494
      }
495
      catch (Exception ee)
496
      {
497
        logMetacat.error("Exception in DBQuery.findDocuments: "
498
                                 + ee.getMessage());
499
        ee.printStackTrace();
500
      }
501
      finally
502
      {
503
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
504
      } //finally
505
    }//if
506
    String closeRestultset = "</resultset>";
507
    resultset.append(closeRestultset);
508
    if (out != null)
509
    {
510
      out.println(closeRestultset);
511
    }
512

    
513
    //default to returning the whole resultset
514
    return resultset;
515
  }//createResultDocuments
516

    
517
    /*
518
     * Find the doc list which match the query
519
     */
520
    private StringBuffer findResultDoclist(QuerySpecification qspec,
521
                                      PrintWriter out,
522
                                      String user, String[]groups,
523
                                      DBConnection dbconn, boolean useXMLIndex,
524
                                      int pagesize, int pagestart, String sessionid, Vector givenDocids)
525
                                      throws Exception
526
    {
527
      StringBuffer resultsetBuffer = new StringBuffer();
528
      String query = null;
529
      int count = 0;
530
      int index = 0;
531
      ResultDocumentSet docListResult = new ResultDocumentSet();
532
      PreparedStatement pstmt = null;
533
      String docid = null;
534
      String docname = null;
535
      String doctype = null;
536
      String createDate = null;
537
      String updateDate = null;
538
      StringBuffer document = null;
539
      boolean lastpage = false;
540
      int rev = 0;
541
      double startTime = 0;
542
      int offset = 1;
543
      double startSelectionTime = System.currentTimeMillis()/1000;
544
      ResultSet rs = null;
545
           
546
   
547
      // this is a hack for offset. in postgresql 7, if the returned docid list is too long,
548
      //the extend query which base on the docid will be too long to be run. So we 
549
      // have to cut them into different parts. Page query don't need it somehow.
550
      if (out == null)
551
      {
552
        // for html page, we put everything into one page
553
        offset =
554
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
555
      }
556
      else
557
      {
558
          offset =
559
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
560
      }
561

    
562
      /*
563
       * Check the docidOverride Vector
564
       * if defined, we bypass the qspec.printSQL() method
565
       * and contruct a simpler query based on a 
566
       * list of docids rather than a bunch of subselects
567
       */
568
      if ( givenDocids == null || givenDocids.size() == 0 ) {
569
          query = qspec.printSQL(useXMLIndex);
570
      } else {
571
          logMetacat.info("*** docid override " + givenDocids.size());
572
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
573
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
574
          for (int i = 0; i < givenDocids.size(); i++) {  
575
              queryBuffer.append("'");
576
              queryBuffer.append( (String)givenDocids.elementAt(i) );
577
              queryBuffer.append("',");
578
          }
579
          // empty string hack 
580
          queryBuffer.append( "'') " );
581
          query = queryBuffer.toString();
582
      } 
583
      String ownerQuery = getOwnerQuery(user);
584
      logMetacat.info("\n\n\n query: " + query);
585
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
586
      // if query is not the owner query, we need to check the permission
587
      // otherwise we don't need (owner has all permission by default)
588
      if (!query.equals(ownerQuery))
589
      {
590
        // set user name and group
591
        qspec.setUserName(user);
592
        qspec.setGroup(groups);
593
        // Get access query
594
        String accessQuery = qspec.getAccessQuery();
595
        if(!query.endsWith("WHERE")){
596
            query = query + accessQuery;
597
        } else {
598
            query = query + accessQuery.substring(4, accessQuery.length());
599
        }
600
        
601
      }
602
      logMetacat.warn("============ final selection query: " + query);
603
      String selectionAndExtendedQuery = null;
604
      // we only get cache for public
605
      if (user != null && user.equalsIgnoreCase("public") 
606
     		 && pagesize == 0 && MetaCatUtil.getOption("query_cache_on").equals("true"))
607
      {
608
    	  selectionAndExtendedQuery = query +qspec.getReturnDocList()+qspec.getReturnFieldList();
609
   	      String cachedResult = getResultXMLFromCache(selectionAndExtendedQuery);
610
   	      logMetacat.debug("The key of query cache is "+selectionAndExtendedQuery);
611
   	      //System.out.println("==========the string from cache is "+cachedResult);
612
   	      if (cachedResult != null)
613
   	      {
614
   	    	logMetacat.info("resutl from cache !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
615
   	    	 if (out != null)
616
   	         {
617
   	             out.println(cachedResult);
618
   	         }
619
   	    	 resultsetBuffer.append(cachedResult);
620
   	    	 return resultsetBuffer;
621
   	      }
622
      }
623
      
624
      startTime = System.currentTimeMillis() / 1000;
625
      pstmt = dbconn.prepareStatement(query);
626
      rs = pstmt.executeQuery();
627

    
628
      double queryExecuteTime = System.currentTimeMillis() / 1000;
629
      logMetacat.warn("Time to execute select docid query is "
630
                    + (queryExecuteTime - startTime));
631
      MetaCatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
632
              + (queryExecuteTime - startTime));
633
      MetaCatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
634

    
635
      boolean tableHasRows = rs.next();
636
      
637
      if(pagesize == 0)
638
      { //this makes sure we get all results if there is no paging
639
        pagesize = NONPAGESIZE;
640
        pagestart = NONPAGESIZE;
641
      } 
642
      
643
      int currentIndex = 0;
644
      while (tableHasRows)
645
      {
646
        logMetacat.info("############getting result: " + currentIndex);
647
        docid = rs.getString(1).trim();
648
        logMetacat.info("############processing: " + docid);
649
        docname = rs.getString(2);
650
        doctype = rs.getString(3);
651
        logMetacat.info("############processing: " + doctype);
652
        createDate = rs.getString(4);
653
        updateDate = rs.getString(5);
654
        rev = rs.getInt(6);
655
        
656
         Vector returndocVec = qspec.getReturnDocList();
657
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
658
        {
659
          logMetacat.info("NOT Back tracing now...");
660
           document = new StringBuffer();
661

    
662
           String completeDocid = docid
663
                            + MetaCatUtil.getOption("accNumSeparator");
664
           completeDocid += rev;
665
           document.append("<docid>").append(completeDocid).append("</docid>");
666
           if (docname != null)
667
           {
668
               document.append("<docname>" + docname + "</docname>");
669
           }
670
           if (doctype != null)
671
           {
672
              document.append("<doctype>" + doctype + "</doctype>");
673
           }
674
           if (createDate != null)
675
           {
676
               document.append("<createdate>" + createDate + "</createdate>");
677
           }
678
           if (updateDate != null)
679
           {
680
             document.append("<updatedate>" + updateDate + "</updatedate>");
681
           }
682
           // Store the document id and the root node id
683
           
684
           docListResult.addResultDocument(
685
             new ResultDocument(docid, (String) document.toString()));
686
           logMetacat.info("$$$$$$$real result: " + docid);
687
           currentIndex++;
688
           count++;
689
        }//else
690
        
691
        // when doclist reached the offset number, send out doc list and empty
692
        // the hash table
693
        if (count == offset && pagesize == NONPAGESIZE)
694
        { //if pagesize is not 0, do this later.
695
          //reset count
696
          //logMetacat.warn("############doing subset cache");
697
          count = 0;
698
          handleSubsetResult(qspec, resultsetBuffer, out, docListResult,
699
                              user, groups,dbconn, useXMLIndex);
700
          //reset docListResult
701
          docListResult = new ResultDocumentSet();
702
        }
703
       
704
       logMetacat.info("currentIndex: " + currentIndex);
705
       logMetacat.info("page comparator: " + (pagesize * pagestart) + pagesize);
706
       if(currentIndex >= ((pagesize * pagestart) + pagesize))
707
       {
708
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
709
         for(int i=pagesize*pagestart; i<docListResult.size(); i++)
710
         {
711
           pagedResultsHash.put(docListResult.get(i));
712
         }
713
         
714
         docListResult = pagedResultsHash;
715
         break;
716
       }
717
       // Advance to the next record in the cursor
718
       tableHasRows = rs.next();
719
       if(!tableHasRows)
720
       {
721
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
722
         //get the last page of information then break
723
         if(pagesize != NONPAGESIZE)
724
         {
725
           for(int i=pagesize*pagestart; i<docListResult.size(); i++)
726
           {
727
             pagedResultsHash.put(docListResult.get(i));
728
           }
729
           docListResult = pagedResultsHash;
730
         }
731
         
732
         lastpage = true;
733
         break;
734
       }
735
     }//while
736
     
737
     rs.close();
738
     pstmt.close();
739
     double docListTime = System.currentTimeMillis() / 1000;
740
     logMetacat.warn("======Total time to get docid list is: "
741
                          + (docListTime - startSelectionTime ));
742
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Total selection: "
743
             + (docListTime - startSelectionTime ));
744
     MetaCatUtil.writeDebugToDelimiteredFile(" "+ (docListTime - startSelectionTime ), false);
745
     //if docListResult is not empty, it need to be sent.
746
     if (docListResult.size() != 0)
747
     {
748
      
749
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
750
                              user, groups,dbconn, useXMLIndex);
751
     }
752

    
753
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
754
     if (out != null)
755
     {
756
         out.println("\n<lastpage>" + lastpage + "</lastpage>\n");
757
     }
758
     
759
     // now we only cached none-paged query and user is public
760
     if (user != null && user.equalsIgnoreCase("public") 
761
    		 && pagesize == NONPAGESIZE && MetaCatUtil.getOption("query_cache_on").equals("true"))
762
     {
763
       //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
764
  	   storeQueryResultIntoCache(selectionAndExtendedQuery, resultsetBuffer.toString());
765
     }
766
          
767
     return resultsetBuffer;
768
    }//findReturnDoclist
769

    
770

    
771
    /*
772
     * Send completed search hashtable(part of reulst)to output stream
773
     * and buffer into a buffer stream
774
     */
775
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
776
                                           StringBuffer resultset,
777
                                           PrintWriter out, ResultDocumentSet partOfDoclist,
778
                                           String user, String[]groups,
779
                                       DBConnection dbconn, boolean useXMLIndex)
780
                                       throws Exception
781
   {
782
     double startReturnField = System.currentTimeMillis()/1000;
783
     // check if there is a record in xml_returnfield
784
     // and get the returnfield_id and usage count
785
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
786
     boolean enterRecords = false;
787

    
788
     // get value of xml_returnfield_count
789
     int count = (new Integer(MetaCatUtil
790
                            .getOption("xml_returnfield_count")))
791
                            .intValue();
792

    
793
     // set enterRecords to true if usage_count is more than the offset
794
     // specified in metacat.properties
795
     if(usage_count > count){
796
         enterRecords = true;
797
     }
798

    
799
     if(returnfield_id < 0){
800
         logMetacat.warn("Error in getting returnfield id from"
801
                                  + "xml_returnfield table");
802
         enterRecords = false;
803
     }
804

    
805
     // get the hashtable containing the docids that already in the
806
     // xml_queryresult table
807
     logMetacat.info("size of partOfDoclist before"
808
                             + " docidsInQueryresultTable(): "
809
                             + partOfDoclist.size());
810
     double startGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
811
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
812
                                                        partOfDoclist, dbconn);
813

    
814
     // remove the keys in queryresultDocList from partOfDoclist
815
     Enumeration _keys = queryresultDocList.keys();
816
     while (_keys.hasMoreElements()){
817
         partOfDoclist.remove((String)_keys.nextElement());
818
     }
819
     double endGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
820
     logMetacat.warn("Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
821
          		               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
822
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
823
               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
824
     MetaCatUtil.writeDebugToDelimiteredFile(" " +
825
             (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable),false);
826
     // backup the keys-elements in partOfDoclist to check later
827
     // if the doc entry is indexed yet
828
     Hashtable partOfDoclistBackup = new Hashtable();
829
     Iterator itt = partOfDoclist.getDocids();
830
     while (itt.hasNext()){
831
       Object key = itt.next();
832
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
833
     }
834

    
835
     logMetacat.info("size of partOfDoclist after"
836
                             + " docidsInQueryresultTable(): "
837
                             + partOfDoclist.size());
838

    
839
     //add return fields for the documents in partOfDoclist
840
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
841
                                        dbconn, useXMLIndex);
842
     double endExtendedQuery = System.currentTimeMillis()/1000;
843
     logMetacat.warn("Get fields from index and node table (Part2 in return fields) "
844
        		                                          + (endExtendedQuery - endGetReturnValueFromQueryresultable));
845
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
846
             + (endExtendedQuery - endGetReturnValueFromQueryresultable));
847
     MetaCatUtil.writeDebugToDelimiteredFile(" "
848
             + (endExtendedQuery - endGetReturnValueFromQueryresultable), false);
849
     //add relationship part part docid list for the documents in partOfDocList
850
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
851

    
852
     double startStoreReturnField = System.currentTimeMillis()/1000;
853
     Iterator keys = partOfDoclist.getDocids();
854
     String key = null;
855
     String element = null;
856
     String query = null;
857
     int offset = (new Integer(MetaCatUtil
858
                               .getOption("queryresult_string_length")))
859
                               .intValue();
860
     while (keys.hasNext())
861
     {
862
         key = (String) keys.next();
863
         element = (String)partOfDoclist.get(key);
864
         
865
	 // check if the enterRecords is true, elements is not null, element's
866
         // length is less than the limit of table column and if the document
867
         // has been indexed already
868
         if(enterRecords && element != null
869
		&& element.length() < offset
870
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
871
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
872
                 + "queryresult_string) VALUES (?, ?, ?)";
873

    
874
             PreparedStatement pstmt = null;
875
             pstmt = dbconn.prepareStatement(query);
876
             pstmt.setInt(1, returnfield_id);
877
             pstmt.setString(2, key);
878
             pstmt.setString(3, element);
879
            
880
             dbconn.increaseUsageCount(1);
881
             try
882
             {
883
            	 pstmt.execute();
884
             }
885
             catch(Exception e)
886
             {
887
            	 logMetacat.warn("couldn't insert the element to xml_queryresult table "+e.getLocalizedMessage());
888
             }
889
             finally
890
             {
891
                pstmt.close();
892
             }
893
         }
894
        
895
         // A string with element
896
         String xmlElement = "  <document>" + element + "</document>";
897

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

    
938
   /**
939
    * Get the docids already in xml_queryresult table and corresponding
940
    * queryresultstring as a hashtable
941
    */
942
   private Hashtable docidsInQueryresultTable(int returnfield_id,
943
                                              ResultDocumentSet partOfDoclist,
944
                                              DBConnection dbconn){
945

    
946
         Hashtable returnValue = new Hashtable();
947
         PreparedStatement pstmt = null;
948
         ResultSet rs = null;
949

    
950
         // get partOfDoclist as string for the query
951
         Iterator keylist = partOfDoclist.getDocids();
952
         StringBuffer doclist = new StringBuffer();
953
         while (keylist.hasNext())
954
         {
955
             doclist.append("'");
956
             doclist.append((String) keylist.next());
957
             doclist.append("',");
958
         }//while
959

    
960

    
961
         if (doclist.length() > 0)
962
         {
963
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
964

    
965
             // the query to find out docids from xml_queryresult
966
             String query = "select docid, queryresult_string from "
967
                          + "xml_queryresult where returnfield_id = " +
968
                          returnfield_id +" and docid in ("+ doclist + ")";
969
             logMetacat.info("Query to get docids from xml_queryresult:"
970
                                      + query);
971

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

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

    
1004

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

    
1018
       // query for finding the id from xml_returnfield
1019
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1020
            + "WHERE returnfield_string LIKE ?";
1021
       logMetacat.info("ReturnField Query:" + query);
1022

    
1023
       try {
1024
           // prepare and run the query
1025
           pstmt = dbconn.prepareStatement(query);
1026
           pstmt.setString(1,returnfield);
1027
           dbconn.increaseUsageCount(1);
1028
           pstmt.execute();
1029
           rs = pstmt.getResultSet();
1030
           boolean tableHasRows = rs.next();
1031

    
1032
           // if record found then increase the usage count
1033
           // else insert a new record and get the id of the new record
1034
           if(tableHasRows){
1035
               // get the id
1036
               id = rs.getInt(1);
1037
               count = rs.getInt(2) + 1;
1038
               rs.close();
1039
               pstmt.close();
1040

    
1041
               // increase the usage count
1042
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1043
                   + "' WHERE returnfield_id ='"+ id +"'";
1044
               logMetacat.info("ReturnField Table Update:"+ query);
1045

    
1046
               pstmt = dbconn.prepareStatement(query);
1047
               dbconn.increaseUsageCount(1);
1048
               pstmt.execute();
1049
               pstmt.close();
1050

    
1051
           } else {
1052
               rs.close();
1053
               pstmt.close();
1054

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

    
1065
               // get the id of the new record
1066
               query = "SELECT returnfield_id FROM xml_returnfield "
1067
                   + "WHERE returnfield_string LIKE ?";
1068
               logMetacat.info("ReturnField query after Insert:" + query);
1069
               pstmt = dbconn.prepareStatement(query);
1070
               pstmt.setString(1, returnfield);
1071

    
1072
               dbconn.increaseUsageCount(1);
1073
               pstmt.execute();
1074
               rs = pstmt.getResultSet();
1075
               if(rs.next()){
1076
                   id = rs.getInt(1);
1077
               } else {
1078
                   id = -1;
1079
               }
1080
               rs.close();
1081
               pstmt.close();
1082
           }
1083

    
1084
       } catch (Exception e){
1085
           logMetacat.error("Error getting id from xml_returnfield in "
1086
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1087
                                     + e.getMessage());
1088
           id = -1;
1089
       }
1090

    
1091
       returnfield_id = id;
1092
       return count;
1093
   }
1094

    
1095

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

    
1113
      if (qspec.containsExtendedSQL())
1114
      {
1115
        qspec.setUserName(user);
1116
        qspec.setGroup(groups);
1117
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1118
        Vector results = new Vector();
1119
        Iterator keylist = docListResult.getDocids();
1120
        StringBuffer doclist = new StringBuffer();
1121
        Vector parentidList = new Vector();
1122
        Hashtable returnFieldValue = new Hashtable();
1123
        while (keylist.hasNext())
1124
        {
1125
          doclist.append("'");
1126
          doclist.append((String) keylist.next());
1127
          doclist.append("',");
1128
        }
1129
        if (doclist.length() > 0)
1130
        {
1131
          Hashtable controlPairs = new Hashtable();
1132
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1133
          boolean tableHasRows = false;
1134
        
1135

    
1136
           String extendedQuery =
1137
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex);
1138
           logMetacat.info("Extended query: " + extendedQuery);
1139

    
1140
           if(extendedQuery != null){
1141
        	   double extendedQueryStart = System.currentTimeMillis() / 1000;
1142
               pstmt = dbconn.prepareStatement(extendedQuery);
1143
               //increase dbconnection usage count
1144
               dbconn.increaseUsageCount(1);
1145
               pstmt.execute();
1146
               rs = pstmt.getResultSet();
1147
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
1148
               logMetacat.warn(
1149
                   "Time to execute extended query: "
1150
                   + (extendedQueryEnd - extendedQueryStart));
1151
               MetaCatUtil.writeDebugToFile(
1152
                       "Execute extended query "
1153
                       + (extendedQueryEnd - extendedQueryStart));
1154
               MetaCatUtil.writeDebugToDelimiteredFile(" "+ (extendedQueryEnd - extendedQueryStart), false);
1155
               tableHasRows = rs.next();
1156
               while (tableHasRows) {
1157
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1158
                   docid = rs.getString(1).trim();
1159
                   fieldname = rs.getString(2);
1160
                   fielddata = rs.getString(3);
1161
                   fielddata = MetaCatUtil.normalize(fielddata);
1162
                   String parentId = rs.getString(4);
1163
                   fieldtype = rs.getString(5);
1164
                   StringBuffer value = new StringBuffer();
1165

    
1166
                   //handle case when usexmlindex is true differently
1167
                   //at one point merging the nodedata (for large text elements) was 
1168
                   //deemed unnecessary - but now it is needed.  but not for attribute nodes
1169
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1170
                	   //merge node data only for non-ATTRIBUTEs
1171
                	   if (fieldtype != null && !fieldtype.equals("ATTRIBUTE")) {
1172
	                	   //try merging the data
1173
	                	   ReturnFieldValue existingRFV =
1174
	                		   getArrayValue(parentidList, parentId);
1175
	                	   if (existingRFV != null) {
1176
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1177
	                	   }
1178
                	   }
1179
                       value.append("<param name=\"");
1180
                       value.append(fieldname);
1181
                       value.append("\">");
1182
                       value.append(fielddata);
1183
                       value.append("</param>");
1184
                       //set returnvalue
1185
                       returnValue.setDocid(docid);
1186
                       returnValue.setFieldValue(fielddata);
1187
                       returnValue.setFieldType(fieldtype);
1188
                       returnValue.setXMLFieldValue(value.toString());
1189
                       // Store it in hastable
1190
                       putInArray(parentidList, parentId, returnValue);
1191
                   }
1192
                   else {
1193
                       // need to merge nodedata if they have same parent id and
1194
                       // node type is text
1195
                       fielddata = (String) ( (ReturnFieldValue)
1196
                                             getArrayValue(
1197
                           parentidList, parentId)).getFieldValue()
1198
                           + fielddata;
1199
                       value.append("<param name=\"");
1200
                       value.append(fieldname);
1201
                       value.append("\">");
1202
                       value.append(fielddata);
1203
                       value.append("</param>");
1204
                       returnValue.setDocid(docid);
1205
                       returnValue.setFieldValue(fielddata);
1206
                       returnValue.setFieldType(fieldtype);
1207
                       returnValue.setXMLFieldValue(value.toString());
1208
                       // remove the old return value from paretnidList
1209
                       parentidList.remove(parentId);
1210
                       // store the new return value in parentidlit
1211
                       putInArray(parentidList, parentId, returnValue);
1212
                   }
1213
                   tableHasRows = rs.next();
1214
               } //while
1215
               rs.close();
1216
               pstmt.close();
1217

    
1218
               // put the merger node data info into doclistReult
1219
               Enumeration xmlFieldValue = (getElements(parentidList)).
1220
                   elements();
1221
               while (xmlFieldValue.hasMoreElements()) {
1222
                   ReturnFieldValue object =
1223
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1224
                   docid = object.getDocid();
1225
                   if (docListResult.containsDocid(docid)) {
1226
                       String removedelement = (String) docListResult.
1227
                           remove(docid);
1228
                       docListResult.
1229
                           addResultDocument(new ResultDocument(docid,
1230
                               removedelement + object.getXMLFieldValue()));
1231
                   }
1232
                   else {
1233
                       docListResult.addResultDocument(
1234
                         new ResultDocument(docid, object.getXMLFieldValue()));
1235
                   }
1236
               } //while
1237
               double docListResultEnd = System.currentTimeMillis() / 1000;
1238
               logMetacat.warn(
1239
                   "Time to prepare ResultDocumentSet after"
1240
                   + " execute extended query: "
1241
                   + (docListResultEnd - extendedQueryEnd));
1242
           }
1243

    
1244
         
1245
           
1246
           
1247
       }//if doclist lenght is great than zero
1248

    
1249
     }//if has extended query
1250

    
1251
      return docListResult;
1252
    }//addReturnfield
1253

    
1254
    /*
1255
    * A method to add relationship to return doclist hash table
1256
    */
1257
   private ResultDocumentSet addRelationship(ResultDocumentSet docListResult,
1258
                                     QuerySpecification qspec,
1259
                                     DBConnection dbconn, boolean useXMLIndex )
1260
                                     throws Exception
1261
  {
1262
    PreparedStatement pstmt = null;
1263
    ResultSet rs = null;
1264
    StringBuffer document = null;
1265
    double startRelation = System.currentTimeMillis() / 1000;
1266
    Iterator docidkeys = docListResult.getDocids();
1267
    while (docidkeys.hasNext())
1268
    {
1269
      //String connstring =
1270
      // "metacat://"+util.getOption("server")+"?docid=";
1271
      String connstring = "%docid=";
1272
      String docidkey;
1273
      synchronized(docListResult)
1274
      {
1275
        docidkey = (String) docidkeys.next();
1276
      }
1277
      pstmt = dbconn.prepareStatement(QuerySpecification
1278
                      .printRelationSQL(docidkey));
1279
      pstmt.execute();
1280
      rs = pstmt.getResultSet();
1281
      boolean tableHasRows = rs.next();
1282
      while (tableHasRows)
1283
      {
1284
        String sub = rs.getString(1);
1285
        String rel = rs.getString(2);
1286
        String obj = rs.getString(3);
1287
        String subDT = rs.getString(4);
1288
        String objDT = rs.getString(5);
1289

    
1290
        document = new StringBuffer();
1291
        document.append("<triple>");
1292
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1293
        document.append("</subject>");
1294
        if (subDT != null)
1295
        {
1296
          document.append("<subjectdoctype>").append(subDT);
1297
          document.append("</subjectdoctype>");
1298
        }
1299
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1300
        document.append("</relationship>");
1301
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1302
        document.append("</object>");
1303
        if (objDT != null)
1304
        {
1305
          document.append("<objectdoctype>").append(objDT);
1306
          document.append("</objectdoctype>");
1307
        }
1308
        document.append("</triple>");
1309

    
1310
        String removedelement = (String) docListResult.get(docidkey);
1311
        docListResult.set(docidkey, removedelement+ document.toString());
1312
        tableHasRows = rs.next();
1313
      }//while
1314
      rs.close();
1315
      pstmt.close();
1316
      
1317
    }//while
1318
    double endRelation = System.currentTimeMillis() / 1000;
1319
    logMetacat.warn("Time to add relationship to return fields (part 3 in return fields): "
1320
                             + (endRelation - startRelation));
1321
    MetaCatUtil.writeDebugToFile("-----------------------------------------Add relationship to return field(part3 in return fields): "
1322
            + (endRelation - startRelation));
1323
    MetaCatUtil.writeDebugToDelimiteredFile(" "+ (endRelation - startRelation), false);
1324

    
1325
    return docListResult;
1326
  }//addRelation
1327

    
1328
  /**
1329
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1330
   * string as a param instead of a hashtable.
1331
   *
1332
   * @param xmlquery a string representing a query.
1333
   */
1334
   private  String transformQuery(String xmlquery)
1335
   {
1336
     xmlquery = xmlquery.trim();
1337
     int index = xmlquery.indexOf("?>");
1338
     if (index != -1)
1339
     {
1340
       return xmlquery.substring(index + 2, xmlquery.length());
1341
     }
1342
     else
1343
     {
1344
       return xmlquery;
1345
     }
1346
   }
1347
   
1348
   /*
1349
    * Method to store query string and result xml string into query result
1350
    * cache. If the size alreay reache the limitation, the cache will be
1351
    * cleared first, then store them.
1352
    */
1353
   private void storeQueryResultIntoCache(String query, String resultXML)
1354
   {
1355
	   synchronized (queryResultCache)
1356
	   {
1357
		   if (queryResultCache.size() >= QUERYRESULTCACHESIZE)
1358
		   {
1359
			   queryResultCache.clear();
1360
		   }
1361
		   queryResultCache.put(query, resultXML);
1362
		   
1363
	   }
1364
   }
1365
   
1366
   /*
1367
    * Method to get result xml string from query result cache. 
1368
    * Note: the returned string can be null.
1369
    */
1370
   private String getResultXMLFromCache(String query)
1371
   {
1372
	   String resultSet = null;
1373
	   synchronized (queryResultCache)
1374
	   {
1375
          try
1376
          {
1377
        	 logMetacat.info("Get query from cache ===");
1378
		     resultSet = (String)queryResultCache.get(query);
1379
		   
1380
          }
1381
          catch (Exception e)
1382
          {
1383
        	  resultSet = null;
1384
          }
1385
		   
1386
	   }
1387
	   return resultSet;
1388
   }
1389
   
1390
   /**
1391
    * Method to clear the query result cache.
1392
    */
1393
   public static void clearQueryResultCache()
1394
   {
1395
	   synchronized (queryResultCache)
1396
	   {
1397
		   queryResultCache.clear();
1398
	   }
1399
   }
1400

    
1401

    
1402
    /*
1403
     * A method to search if Vector contains a particular key string
1404
     */
1405
    private boolean containsKey(Vector parentidList, String parentId)
1406
    {
1407

    
1408
        Vector tempVector = null;
1409

    
1410
        for (int count = 0; count < parentidList.size(); count++) {
1411
            tempVector = (Vector) parentidList.get(count);
1412
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1413
        }
1414
        return false;
1415
    }
1416
    
1417
    /*
1418
     * A method to put key and value in Vector
1419
     */
1420
    private void putInArray(Vector parentidList, String key,
1421
            ReturnFieldValue value)
1422
    {
1423

    
1424
        Vector tempVector = null;
1425
        //only filter if the field type is NOT an attribute (say, for text)
1426
        String fieldType = value.getFieldType();
1427
        if (fieldType != null && !fieldType.equals("ATTRIBUTE")) {
1428
        
1429
	        for (int count = 0; count < parentidList.size(); count++) {
1430
	            tempVector = (Vector) parentidList.get(count);
1431
	
1432
	            if (key.compareTo((String) tempVector.get(0)) == 0) {
1433
	                tempVector.remove(1);
1434
	                tempVector.add(1, value);
1435
	                return;
1436
	            }
1437
	        }
1438
        }
1439

    
1440
        tempVector = new Vector();
1441
        tempVector.add(0, key);
1442
        tempVector.add(1, value);
1443
        parentidList.add(tempVector);
1444
        return;
1445
    }
1446

    
1447
    /*
1448
     * A method to get value in Vector given a key
1449
     */
1450
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1451
    {
1452

    
1453
        Vector tempVector = null;
1454

    
1455
        for (int count = 0; count < parentidList.size(); count++) {
1456
            tempVector = (Vector) parentidList.get(count);
1457

    
1458
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1459
                    .get(1); }
1460
        }
1461
        return null;
1462
    }
1463

    
1464
    /*
1465
     * A method to get enumeration of all values in Vector
1466
     */
1467
    private Vector getElements(Vector parentidList)
1468
    {
1469
        Vector enumVector = new Vector();
1470
        Vector tempVector = null;
1471

    
1472
        for (int count = 0; count < parentidList.size(); count++) {
1473
            tempVector = (Vector) parentidList.get(count);
1474

    
1475
            enumVector.add(tempVector.get(1));
1476
        }
1477
        return enumVector;
1478
    }
1479

    
1480
  
1481

    
1482
    /*
1483
     * A method to create a query to get owner's docid list
1484
     */
1485
    private String getOwnerQuery(String owner)
1486
    {
1487
        if (owner != null) {
1488
            owner = owner.toLowerCase();
1489
        }
1490
        StringBuffer self = new StringBuffer();
1491

    
1492
        self.append("SELECT docid,docname,doctype,");
1493
        self.append("date_created, date_updated, rev ");
1494
        self.append("FROM xml_documents WHERE docid IN (");
1495
        self.append("(");
1496
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1497
        self.append("nodedata LIKE '%%%' ");
1498
        self.append(") \n");
1499
        self.append(") ");
1500
        self.append(" AND (");
1501
        self.append(" lower(user_owner) = '" + owner + "'");
1502
        self.append(") ");
1503
        return self.toString();
1504
    }
1505

    
1506
    /**
1507
     * format a structured query as an XML document that conforms to the
1508
     * pathquery.dtd and is appropriate for submission to the DBQuery
1509
     * structured query engine
1510
     *
1511
     * @param params The list of parameters that should be included in the
1512
     *            query
1513
     */
1514
    public static String createSQuery(Hashtable params)
1515
    {
1516
        StringBuffer query = new StringBuffer();
1517
        Enumeration elements;
1518
        Enumeration keys;
1519
        String filterDoctype = null;
1520
        String casesensitive = null;
1521
        String searchmode = null;
1522
        Object nextkey;
1523
        Object nextelement;
1524
        //add the xml headers
1525
        query.append("<?xml version=\"1.0\"?>\n");
1526
        query.append("<pathquery version=\"1.2\">\n");
1527

    
1528

    
1529

    
1530
        if (params.containsKey("meta_file_id")) {
1531
            query.append("<meta_file_id>");
1532
            query.append(((String[]) params.get("meta_file_id"))[0]);
1533
            query.append("</meta_file_id>");
1534
        }
1535

    
1536
        if (params.containsKey("returndoctype")) {
1537
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1538
            for (int i = 0; i < returnDoctypes.length; i++) {
1539
                String doctype = (String) returnDoctypes[i];
1540

    
1541
                if (!doctype.equals("any") && !doctype.equals("ANY")
1542
                        && !doctype.equals("")) {
1543
                    query.append("<returndoctype>").append(doctype);
1544
                    query.append("</returndoctype>");
1545
                }
1546
            }
1547
        }
1548

    
1549
        if (params.containsKey("filterdoctype")) {
1550
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1551
            for (int i = 0; i < filterDoctypes.length; i++) {
1552
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1553
                query.append("</filterdoctype>");
1554
            }
1555
        }
1556

    
1557
        if (params.containsKey("returnfield")) {
1558
            String[] returnfield = ((String[]) params.get("returnfield"));
1559
            for (int i = 0; i < returnfield.length; i++) {
1560
                query.append("<returnfield>").append(returnfield[i]);
1561
                query.append("</returnfield>");
1562
            }
1563
        }
1564

    
1565
        if (params.containsKey("owner")) {
1566
            String[] owner = ((String[]) params.get("owner"));
1567
            for (int i = 0; i < owner.length; i++) {
1568
                query.append("<owner>").append(owner[i]);
1569
                query.append("</owner>");
1570
            }
1571
        }
1572

    
1573
        if (params.containsKey("site")) {
1574
            String[] site = ((String[]) params.get("site"));
1575
            for (int i = 0; i < site.length; i++) {
1576
                query.append("<site>").append(site[i]);
1577
                query.append("</site>");
1578
            }
1579
        }
1580

    
1581
        //allows the dynamic switching of boolean operators
1582
        if (params.containsKey("operator")) {
1583
            query.append("<querygroup operator=\""
1584
                    + ((String[]) params.get("operator"))[0] + "\">");
1585
        } else { //the default operator is UNION
1586
            query.append("<querygroup operator=\"UNION\">");
1587
        }
1588

    
1589
        if (params.containsKey("casesensitive")) {
1590
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1591
        } else {
1592
            casesensitive = "false";
1593
        }
1594

    
1595
        if (params.containsKey("searchmode")) {
1596
            searchmode = ((String[]) params.get("searchmode"))[0];
1597
        } else {
1598
            searchmode = "contains";
1599
        }
1600

    
1601
        //anyfield is a special case because it does a
1602
        //free text search. It does not have a <pathexpr>
1603
        //tag. This allows for a free text search within the structured
1604
        //query. This is useful if the INTERSECT operator is used.
1605
        if (params.containsKey("anyfield")) {
1606
            String[] anyfield = ((String[]) params.get("anyfield"));
1607
            //allow for more than one value for anyfield
1608
            for (int i = 0; i < anyfield.length; i++) {
1609
                if (!anyfield[i].equals("")) {
1610
                    query.append("<queryterm casesensitive=\"" + casesensitive
1611
                            + "\" " + "searchmode=\"" + searchmode
1612
                            + "\"><value>" + anyfield[i]
1613
                            + "</value></queryterm>");
1614
                }
1615
            }
1616
        }
1617

    
1618
        //this while loop finds the rest of the parameters
1619
        //and attempts to query for the field specified
1620
        //by the parameter.
1621
        elements = params.elements();
1622
        keys = params.keys();
1623
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1624
            nextkey = keys.nextElement();
1625
            nextelement = elements.nextElement();
1626

    
1627
            //make sure we aren't querying for any of these
1628
            //parameters since the are already in the query
1629
            //in one form or another.
1630
            Vector ignoredParams = new Vector();
1631
            ignoredParams.add("returndoctype");
1632
            ignoredParams.add("filterdoctype");
1633
            ignoredParams.add("action");
1634
            ignoredParams.add("qformat");
1635
            ignoredParams.add("anyfield");
1636
            ignoredParams.add("returnfield");
1637
            ignoredParams.add("owner");
1638
            ignoredParams.add("site");
1639
            ignoredParams.add("operator");
1640
            ignoredParams.add("sessionid");
1641
            ignoredParams.add("pagesize");
1642
            ignoredParams.add("pagestart");
1643

    
1644
            // Also ignore parameters listed in the properties file
1645
            // so that they can be passed through to stylesheets
1646
            String paramsToIgnore = MetaCatUtil
1647
                    .getOption("query.ignored.params");
1648
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1649
            while (st.hasMoreTokens()) {
1650
                ignoredParams.add(st.nextToken());
1651
            }
1652
            if (!ignoredParams.contains(nextkey.toString())) {
1653
                //allow for more than value per field name
1654
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1655
                    if (!((String[]) nextelement)[i].equals("")) {
1656
                        query.append("<queryterm casesensitive=\""
1657
                                + casesensitive + "\" " + "searchmode=\""
1658
                                + searchmode + "\">" + "<value>" +
1659
                                //add the query value
1660
                                ((String[]) nextelement)[i]
1661
                                + "</value><pathexpr>" +
1662
                                //add the path to query by
1663
                                nextkey.toString() + "</pathexpr></queryterm>");
1664
                    }
1665
                }
1666
            }
1667
        }
1668
        query.append("</querygroup></pathquery>");
1669
        //append on the end of the xml and return the result as a string
1670
        return query.toString();
1671
    }
1672

    
1673
    /**
1674
     * format a simple free-text value query as an XML document that conforms
1675
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1676
     * structured query engine
1677
     *
1678
     * @param value the text string to search for in the xml catalog
1679
     * @param doctype the type of documents to include in the result set -- use
1680
     *            "any" or "ANY" for unfiltered result sets
1681
     */
1682
    public static String createQuery(String value, String doctype)
1683
    {
1684
        StringBuffer xmlquery = new StringBuffer();
1685
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1686
        xmlquery.append("<pathquery version=\"1.0\">");
1687

    
1688
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1689
            xmlquery.append("<returndoctype>");
1690
            xmlquery.append(doctype).append("</returndoctype>");
1691
        }
1692

    
1693
        xmlquery.append("<querygroup operator=\"UNION\">");
1694
        //chad added - 8/14
1695
        //the if statement allows a query to gracefully handle a null
1696
        //query. Without this if a nullpointerException is thrown.
1697
        if (!value.equals("")) {
1698
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1699
            xmlquery.append("searchmode=\"contains\">");
1700
            xmlquery.append("<value>").append(value).append("</value>");
1701
            xmlquery.append("</queryterm>");
1702
        }
1703
        xmlquery.append("</querygroup>");
1704
        xmlquery.append("</pathquery>");
1705

    
1706
        return (xmlquery.toString());
1707
    }
1708

    
1709
    /**
1710
     * format a simple free-text value query as an XML document that conforms
1711
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1712
     * structured query engine
1713
     *
1714
     * @param value the text string to search for in the xml catalog
1715
     */
1716
    public static String createQuery(String value)
1717
    {
1718
        return createQuery(value, "any");
1719
    }
1720

    
1721
    /**
1722
     * Check for "READ" permission on @docid for @user and/or @group from DB
1723
     * connection
1724
     */
1725
    private boolean hasPermission(String user, String[] groups, String docid)
1726
            throws SQLException, Exception
1727
    {
1728
        // Check for READ permission on @docid for @user and/or @groups
1729
        PermissionController controller = new PermissionController(docid);
1730
        return controller.hasPermission(user, groups,
1731
                AccessControlInterface.READSTRING);
1732
    }
1733

    
1734
    /**
1735
     * Get all docIds list for a data packadge
1736
     *
1737
     * @param dataPackageDocid, the string in docId field of xml_relation table
1738
     */
1739
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1740
    {
1741
        DBConnection dbConn = null;
1742
        int serialNumber = -1;
1743
        Vector docIdList = new Vector();//return value
1744
        PreparedStatement pStmt = null;
1745
        ResultSet rs = null;
1746
        String docIdInSubjectField = null;
1747
        String docIdInObjectField = null;
1748

    
1749
        // Check the parameter
1750
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1751

    
1752
        //the query stirng
1753
        String query = "SELECT subject, object from xml_relation where docId = ?";
1754
        try {
1755
            dbConn = DBConnectionPool
1756
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1757
            serialNumber = dbConn.getCheckOutSerialNumber();
1758
            pStmt = dbConn.prepareStatement(query);
1759
            //bind the value to query
1760
            pStmt.setString(1, dataPackageDocid);
1761

    
1762
            //excute the query
1763
            pStmt.execute();
1764
            //get the result set
1765
            rs = pStmt.getResultSet();
1766
            //process the result
1767
            while (rs.next()) {
1768
                //In order to get the whole docIds in a data packadge,
1769
                //we need to put the docIds of subject and object field in
1770
                // xml_relation
1771
                //into the return vector
1772
                docIdInSubjectField = rs.getString(1);//the result docId in
1773
                                                      // subject field
1774
                docIdInObjectField = rs.getString(2);//the result docId in
1775
                                                     // object field
1776

    
1777
                //don't put the duplicate docId into the vector
1778
                if (!docIdList.contains(docIdInSubjectField)) {
1779
                    docIdList.add(docIdInSubjectField);
1780
                }
1781

    
1782
                //don't put the duplicate docId into the vector
1783
                if (!docIdList.contains(docIdInObjectField)) {
1784
                    docIdList.add(docIdInObjectField);
1785
                }
1786
            }//while
1787
            //close the pStmt
1788
            pStmt.close();
1789
        }//try
1790
        catch (SQLException e) {
1791
            logMetacat.error("Error in getDocidListForDataPackage: "
1792
                    + e.getMessage());
1793
        }//catch
1794
        finally {
1795
            try {
1796
                pStmt.close();
1797
            }//try
1798
            catch (SQLException ee) {
1799
                logMetacat.error(
1800
                        "Error in getDocidListForDataPackage: "
1801
                                + ee.getMessage());
1802
            }//catch
1803
            finally {
1804
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1805
            }//fianlly
1806
        }//finally
1807
        return docIdList;
1808
    }//getCurrentDocidListForDataPackadge()
1809

    
1810
    /**
1811
     * Get all docIds list for a data packadge
1812
     *
1813
     * @param dataPackageDocid, the string in docId field of xml_relation table
1814
     */
1815
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1816
    {
1817

    
1818
        Vector docIdList = new Vector();//return value
1819
        Vector tripleList = null;
1820
        String xml = null;
1821

    
1822
        // Check the parameter
1823
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1824

    
1825
        try {
1826
            //initial a documentImpl object
1827
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1828
            //transfer to documentImpl object to string
1829
            xml = packageDocument.toString();
1830

    
1831
            //create a tripcollection object
1832
            TripleCollection tripleForPackage = new TripleCollection(
1833
                    new StringReader(xml));
1834
            //get the vetor of triples
1835
            tripleList = tripleForPackage.getCollection();
1836

    
1837
            for (int i = 0; i < tripleList.size(); i++) {
1838
                //put subject docid into docIdlist without duplicate
1839
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1840
                        .getSubject())) {
1841
                    //put subject docid into docIdlist
1842
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1843
                }
1844
                //put object docid into docIdlist without duplicate
1845
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1846
                        .getObject())) {
1847
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1848
                }
1849
            }//for
1850
        }//try
1851
        catch (Exception e) {
1852
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1853
                    + e.getMessage());
1854
        }//catch
1855

    
1856
        // return result
1857
        return docIdList;
1858
    }//getDocidListForPackageInXMLRevisions()
1859

    
1860
    /**
1861
     * Check if the docId is a data packadge id. If the id is a data packadage
1862
     * id, it should be store in the docId fields in xml_relation table. So we
1863
     * can use a query to get the entries which the docId equals the given
1864
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1865
     * it is.
1866
     *
1867
     * @param docId, the id need to be checked
1868
     */
1869
    private boolean isDataPackageId(String docId)
1870
    {
1871
        boolean result = false;
1872
        PreparedStatement pStmt = null;
1873
        ResultSet rs = null;
1874
        String query = "SELECT docId from xml_relation where docId = ?";
1875
        DBConnection dbConn = null;
1876
        int serialNumber = -1;
1877
        try {
1878
            dbConn = DBConnectionPool
1879
                    .getDBConnection("DBQuery.isDataPackageId");
1880
            serialNumber = dbConn.getCheckOutSerialNumber();
1881
            pStmt = dbConn.prepareStatement(query);
1882
            //bind the value to query
1883
            pStmt.setString(1, docId);
1884
            //execute the query
1885
            pStmt.execute();
1886
            rs = pStmt.getResultSet();
1887
            //process the result
1888
            if (rs.next()) //There are some records for the id in docId fields
1889
            {
1890
                result = true;//It is a data packadge id
1891
            }
1892
            pStmt.close();
1893
        }//try
1894
        catch (SQLException e) {
1895
            logMetacat.error("Error in isDataPackageId: "
1896
                    + e.getMessage());
1897
        } finally {
1898
            try {
1899
                pStmt.close();
1900
            }//try
1901
            catch (SQLException ee) {
1902
                logMetacat.error("Error in isDataPackageId: "
1903
                        + ee.getMessage());
1904
            }//catch
1905
            finally {
1906
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1907
            }//finally
1908
        }//finally
1909
        return result;
1910
    }//isDataPackageId()
1911

    
1912
    /**
1913
     * Check if the user has the permission to export data package
1914
     *
1915
     * @param conn, the connection
1916
     * @param docId, the id need to be checked
1917
     * @param user, the name of user
1918
     * @param groups, the user's group
1919
     */
1920
    private boolean hasPermissionToExportPackage(String docId, String user,
1921
            String[] groups) throws Exception
1922
    {
1923
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1924
        return DocumentImpl.hasReadPermission(user, groups, docId);
1925
    }
1926

    
1927
    /**
1928
     * Get the current Rev for a docid in xml_documents table
1929
     *
1930
     * @param docId, the id need to get version numb If the return value is -5,
1931
     *            means no value in rev field for this docid
1932
     */
1933
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1934
            throws SQLException
1935
    {
1936
        int rev = -5;
1937
        PreparedStatement pStmt = null;
1938
        ResultSet rs = null;
1939
        String query = "SELECT rev from xml_documents where docId = ?";
1940
        DBConnection dbConn = null;
1941
        int serialNumber = -1;
1942
        try {
1943
            dbConn = DBConnectionPool
1944
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1945
            serialNumber = dbConn.getCheckOutSerialNumber();
1946
            pStmt = dbConn.prepareStatement(query);
1947
            //bind the value to query
1948
            pStmt.setString(1, docId);
1949
            //execute the query
1950
            pStmt.execute();
1951
            rs = pStmt.getResultSet();
1952
            //process the result
1953
            if (rs.next()) //There are some records for rev
1954
            {
1955
                rev = rs.getInt(1);
1956
                ;//It is the version for given docid
1957
            } else {
1958
                rev = -5;
1959
            }
1960

    
1961
        }//try
1962
        catch (SQLException e) {
1963
            logMetacat.error(
1964
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1965
                            + e.getMessage());
1966
            throw e;
1967
        }//catch
1968
        finally {
1969
            try {
1970
                pStmt.close();
1971
            }//try
1972
            catch (SQLException ee) {
1973
                logMetacat.error(
1974
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1975
                                + ee.getMessage());
1976
            }//catch
1977
            finally {
1978
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1979
            }//finally
1980
        }//finally
1981
        return rev;
1982
    }//getCurrentRevFromXMLDoumentsTable
1983

    
1984
    /**
1985
     * put a doc into a zip output stream
1986
     *
1987
     * @param docImpl, docmentImpl object which will be sent to zip output
1988
     *            stream
1989
     * @param zipOut, zip output stream which the docImpl will be put
1990
     * @param packageZipEntry, the zip entry name for whole package
1991
     */
1992
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1993
            ZipOutputStream zipOut, String packageZipEntry)
1994
            throws ClassNotFoundException, IOException, SQLException,
1995
            McdbException, Exception
1996
    {
1997
        byte[] byteString = null;
1998
        ZipEntry zEntry = null;
1999

    
2000
        byteString = docImpl.toString().getBytes();
2001
        //use docId as the zip entry's name
2002
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
2003
                + docImpl.getDocID());
2004
        zEntry.setSize(byteString.length);
2005
        zipOut.putNextEntry(zEntry);
2006
        zipOut.write(byteString, 0, byteString.length);
2007
        zipOut.closeEntry();
2008

    
2009
    }//addDocToZipOutputStream()
2010

    
2011
    /**
2012
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
2013
     * only inlcudes current version. If a DocumentImple object couldn't find
2014
     * for a docid, then the String of this docid was added to vetor rather
2015
     * than DocumentImple object.
2016
     *
2017
     * @param docIdList, a vetor hold a docid list for a data package. In
2018
     *            docid, there is not version number in it.
2019
     */
2020

    
2021
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2022
            throws McdbException, Exception
2023
    {
2024
        //Connection dbConn=null;
2025
        Vector documentImplList = new Vector();
2026
        int rev = 0;
2027

    
2028
        // Check the parameter
2029
        if (docIdList.isEmpty()) { return documentImplList; }//if
2030

    
2031
        //for every docid in vector
2032
        for (int i = 0; i < docIdList.size(); i++) {
2033
            try {
2034
                //get newest version for this docId
2035
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2036
                        .elementAt(i));
2037

    
2038
                // There is no record for this docId in xml_documents table
2039
                if (rev == -5) {
2040
                    // Rather than put DocumentImple object, put a String
2041
                    // Object(docid)
2042
                    // into the documentImplList
2043
                    documentImplList.add((String) docIdList.elementAt(i));
2044
                    // Skip other code
2045
                    continue;
2046
                }
2047

    
2048
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2049
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
2050

    
2051
                //create new documentImpl object
2052
                DocumentImpl documentImplObject = new DocumentImpl(
2053
                        docidPlusVersion);
2054
                //add them to vector
2055
                documentImplList.add(documentImplObject);
2056
            }//try
2057
            catch (Exception e) {
2058
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
2059
                        + e.getMessage());
2060
                // continue the for loop
2061
                continue;
2062
            }
2063
        }//for
2064
        return documentImplList;
2065
    }
2066

    
2067
    /**
2068
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2069
     * object couldn't find for a docid, then the String of this docid was
2070
     * added to vetor rather than DocumentImple object.
2071
     *
2072
     * @param docIdList, a vetor hold a docid list for a data package. In
2073
     *            docid, t here is version number in it.
2074
     */
2075
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2076
    {
2077
        //Connection dbConn=null;
2078
        Vector documentImplList = new Vector();
2079
        String siteCode = null;
2080
        String uniqueId = null;
2081
        int rev = 0;
2082

    
2083
        // Check the parameter
2084
        if (docIdList.isEmpty()) { return documentImplList; }//if
2085

    
2086
        //for every docid in vector
2087
        for (int i = 0; i < docIdList.size(); i++) {
2088

    
2089
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2090

    
2091
            try {
2092
                //create new documentImpl object
2093
                DocumentImpl documentImplObject = new DocumentImpl(
2094
                        docidPlusVersion);
2095
                //add them to vector
2096
                documentImplList.add(documentImplObject);
2097
            }//try
2098
            catch (McdbDocNotFoundException notFoundE) {
2099
                logMetacat.error(
2100
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2101
                                + notFoundE.getMessage());
2102
                // Rather than add a DocumentImple object into vetor, a String
2103
                // object
2104
                // - the doicd was added to the vector
2105
                documentImplList.add(docidPlusVersion);
2106
                // Continue the for loop
2107
                continue;
2108
            }//catch
2109
            catch (Exception e) {
2110
                logMetacat.error(
2111
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2112
                                + e.getMessage());
2113
                // Continue the for loop
2114
                continue;
2115
            }//catch
2116

    
2117
        }//for
2118
        return documentImplList;
2119
    }//getOldVersionAllDocumentImple
2120

    
2121
    /**
2122
     * put a data file into a zip output stream
2123
     *
2124
     * @param docImpl, docmentImpl object which will be sent to zip output
2125
     *            stream
2126
     * @param zipOut, the zip output stream which the docImpl will be put
2127
     * @param packageZipEntry, the zip entry name for whole package
2128
     */
2129
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2130
            ZipOutputStream zipOut, String packageZipEntry)
2131
            throws ClassNotFoundException, IOException, SQLException,
2132
            McdbException, Exception
2133
    {
2134
        byte[] byteString = null;
2135
        ZipEntry zEntry = null;
2136
        // this is data file; add file to zip
2137
        String filePath = MetaCatUtil.getOption("datafilepath");
2138
        if (!filePath.endsWith("/")) {
2139
            filePath += "/";
2140
        }
2141
        String fileName = filePath + docImpl.getDocID();
2142
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2143
        zipOut.putNextEntry(zEntry);
2144
        FileInputStream fin = null;
2145
        try {
2146
            fin = new FileInputStream(fileName);
2147
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2148
            int b = fin.read(buf);
2149
            while (b != -1) {
2150
                zipOut.write(buf, 0, b);
2151
                b = fin.read(buf);
2152
            }//while
2153
            zipOut.closeEntry();
2154
        }//try
2155
        catch (IOException ioe) {
2156
            logMetacat.error("There is an exception: "
2157
                    + ioe.getMessage());
2158
        }//catch
2159
    }//addDataFileToZipOutputStream()
2160

    
2161
    /**
2162
     * create a html summary for data package and put it into zip output stream
2163
     *
2164
     * @param docImplList, the documentImpl ojbects in data package
2165
     * @param zipOut, the zip output stream which the html should be put
2166
     * @param packageZipEntry, the zip entry name for whole package
2167
     */
2168
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2169
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2170
    {
2171
        StringBuffer htmlDoc = new StringBuffer();
2172
        ZipEntry zEntry = null;
2173
        byte[] byteString = null;
2174
        InputStream source;
2175
        DBTransform xmlToHtml;
2176

    
2177
        //create a DBTransform ojbect
2178
        xmlToHtml = new DBTransform();
2179
        //head of html
2180
        htmlDoc.append("<html><head></head><body>");
2181
        for (int i = 0; i < docImplList.size(); i++) {
2182
            // If this String object, this means it is missed data file
2183
            if ((((docImplList.elementAt(i)).getClass()).toString())
2184
                    .equals("class java.lang.String")) {
2185

    
2186
                htmlDoc.append("<a href=\"");
2187
                String dataFileid = (String) docImplList.elementAt(i);
2188
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2189
                htmlDoc.append("Data File: ");
2190
                htmlDoc.append(dataFileid).append("</a><br>");
2191
                htmlDoc.append("<br><hr><br>");
2192

    
2193
            }//if
2194
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2195
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2196
                                              // transform it.
2197
                //transform each file individually then concatenate all of the
2198
                //transformations together.
2199

    
2200
                //for metadata xml title
2201
                htmlDoc.append("<h2>");
2202
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2203
                        .getDocID());
2204
                //htmlDoc.append(".");
2205
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2206
                htmlDoc.append("</h2>");
2207
                //do the actual transform
2208
                StringWriter docString = new StringWriter();
2209
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2210
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2211
                        "-//W3C//HTML//EN", "html", docString);
2212
                htmlDoc.append(docString.toString());
2213
                htmlDoc.append("<br><br><hr><br><br>");
2214
            }//if
2215
            else { //this is a data file so we should link to it in the html
2216
                htmlDoc.append("<a href=\"");
2217
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2218
                        .getDocID();
2219
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2220
                htmlDoc.append("Data File: ");
2221
                htmlDoc.append(dataFileid).append("</a><br>");
2222
                htmlDoc.append("<br><hr><br>");
2223
            }//else
2224
        }//for
2225
        htmlDoc.append("</body></html>");
2226
        byteString = htmlDoc.toString().getBytes();
2227
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2228
        zEntry.setSize(byteString.length);
2229
        zipOut.putNextEntry(zEntry);
2230
        zipOut.write(byteString, 0, byteString.length);
2231
        zipOut.closeEntry();
2232
        //dbConn.close();
2233

    
2234
    }//addHtmlSummaryToZipOutputStream
2235

    
2236
    /**
2237
     * put a data packadge into a zip output stream
2238
     *
2239
     * @param docId, which the user want to put into zip output stream,it has version
2240
     * @param out, a servletoutput stream which the zip output stream will be
2241
     *            put
2242
     * @param user, the username of the user
2243
     * @param groups, the group of the user
2244
     */
2245
    public ZipOutputStream getZippedPackage(String docIdString,
2246
            ServletOutputStream out, String user, String[] groups,
2247
            String passWord) throws ClassNotFoundException, IOException,
2248
            SQLException, McdbException, NumberFormatException, Exception
2249
    {
2250
        ZipOutputStream zOut = null;
2251
        String elementDocid = null;
2252
        DocumentImpl docImpls = null;
2253
        //Connection dbConn = null;
2254
        Vector docIdList = new Vector();
2255
        Vector documentImplList = new Vector();
2256
        Vector htmlDocumentImplList = new Vector();
2257
        String packageId = null;
2258
        String rootName = "package";//the package zip entry name
2259

    
2260
        String docId = null;
2261
        int version = -5;
2262
        // Docid without revision
2263
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2264
        // revision number
2265
        version = MetaCatUtil.getVersionFromString(docIdString);
2266

    
2267
        //check if the reqused docId is a data package id
2268
        if (!isDataPackageId(docId)) {
2269

    
2270
            /*
2271
             * Exception e = new Exception("The request the doc id "
2272
             * +docIdString+ " is not a data package id");
2273
             */
2274

    
2275
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2276
            // zip
2277
            //up the single document and return the zip file.
2278
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2279

    
2280
                Exception e = new Exception("User " + user
2281
                        + " does not have permission"
2282
                        + " to export the data package " + docIdString);
2283
                throw e;
2284
            }
2285

    
2286
            docImpls = new DocumentImpl(docIdString);
2287
            //checking if the user has the permission to read the documents
2288
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2289
                    .getDocID())) {
2290
                zOut = new ZipOutputStream(out);
2291
                //if the docImpls is metadata
2292
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2293
                    //add metadata into zip output stream
2294
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2295
                }//if
2296
                else {
2297
                    //it is data file
2298
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2299
                    htmlDocumentImplList.add(docImpls);
2300
                }//else
2301
            }//if
2302

    
2303
            zOut.finish(); //terminate the zip file
2304
            return zOut;
2305
        }
2306
        // Check the permission of user
2307
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2308

    
2309
            Exception e = new Exception("User " + user
2310
                    + " does not have permission"
2311
                    + " to export the data package " + docIdString);
2312
            throw e;
2313
        } else //it is a packadge id
2314
        {
2315
            //store the package id
2316
            packageId = docId;
2317
            //get current version in database
2318
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2319
            //If it is for current version (-1 means user didn't specify
2320
            // revision)
2321
            if ((version == -1) || version == currentVersion) {
2322
                //get current version number
2323
                version = currentVersion;
2324
                //get package zip entry name
2325
                //it should be docId.revsion.package
2326
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2327
                        + version + MetaCatUtil.getOption("accNumSeparator")
2328
                        + "package";
2329
                //get the whole id list for data packadge
2330
                docIdList = getCurrentDocidListForDataPackage(packageId);
2331
                //get the whole documentImple object
2332
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2333

    
2334
            }//if
2335
            else if (version > currentVersion || version < -1) {
2336
                throw new Exception("The user specified docid: " + docId + "."
2337
                        + version + " doesn't exist");
2338
            }//else if
2339
            else //for an old version
2340
            {
2341

    
2342
                rootName = docIdString
2343
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2344
                //get the whole id list for data packadge
2345
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2346

    
2347
                //get the whole documentImple object
2348
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2349
            }//else
2350

    
2351
            // Make sure documentImplist is not empty
2352
            if (documentImplList.isEmpty()) { throw new Exception(
2353
                    "Couldn't find component for data package: " + packageId); }//if
2354

    
2355
            zOut = new ZipOutputStream(out);
2356
            //put every element into zip output stream
2357
            for (int i = 0; i < documentImplList.size(); i++) {
2358
                // if the object in the vetor is String, this means we couldn't
2359
                // find
2360
                // the document locally, we need find it remote
2361
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2362
                        .equals("class java.lang.String")) {
2363
                    // Get String object from vetor
2364
                    String documentId = (String) documentImplList.elementAt(i);
2365
                    logMetacat.info("docid: " + documentId);
2366
                    // Get doicd without revision
2367
                    String docidWithoutRevision = MetaCatUtil
2368
                            .getDocIdFromString(documentId);
2369
                    logMetacat.info("docidWithoutRevsion: "
2370
                            + docidWithoutRevision);
2371
                    // Get revision
2372
                    String revision = MetaCatUtil
2373
                            .getRevisionStringFromString(documentId);
2374
                    logMetacat.info("revsion from docIdentifier: "
2375
                            + revision);
2376
                    // Zip entry string
2377
                    String zipEntryPath = rootName + "/data/";
2378
                    // Create a RemoteDocument object
2379
                    RemoteDocument remoteDoc = new RemoteDocument(
2380
                            docidWithoutRevision, revision, user, passWord,
2381
                            zipEntryPath);
2382
                    // Here we only read data file from remote metacat
2383
                    String docType = remoteDoc.getDocType();
2384
                    if (docType != null) {
2385
                        if (docType.equals("BIN")) {
2386
                            // Put remote document to zip output
2387
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2388
                            // Add String object to htmlDocumentImplList
2389
                            String elementInHtmlList = remoteDoc
2390
                                    .getDocIdWithoutRevsion()
2391
                                    + MetaCatUtil.getOption("accNumSeparator")
2392
                                    + remoteDoc.getRevision();
2393
                            htmlDocumentImplList.add(elementInHtmlList);
2394
                        }//if
2395
                    }//if
2396

    
2397
                }//if
2398
                else {
2399
                    //create a docmentImpls object (represent xml doc) base on
2400
                    // the docId
2401
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2402
                    //checking if the user has the permission to read the
2403
                    // documents
2404
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2405
                            .getDocID())) {
2406
                        //if the docImpls is metadata
2407
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2408
                            //add metadata into zip output stream
2409
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2410
                            //add the documentImpl into the vetor which will
2411
                            // be used in html
2412
                            htmlDocumentImplList.add(docImpls);
2413

    
2414
                        }//if
2415
                        else {
2416
                            //it is data file
2417
                            addDataFileToZipOutputStream(docImpls, zOut,
2418
                                    rootName);
2419
                            htmlDocumentImplList.add(docImpls);
2420
                        }//else
2421
                    }//if
2422
                }//else
2423
            }//for
2424

    
2425
            //add html summary file
2426
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2427
                    rootName);
2428
            zOut.finish(); //terminate the zip file
2429
            //dbConn.close();
2430
            return zOut;
2431
        }//else
2432
    }//getZippedPackage()
2433

    
2434
    private class ReturnFieldValue
2435
    {
2436

    
2437
        private String docid = null; //return field value for this docid
2438

    
2439
        private String fieldValue = null;
2440

    
2441
        private String xmlFieldValue = null; //return field value in xml
2442
                                             // format
2443
        private String fieldType = null; //ATTRIBUTE, TEXT...
2444

    
2445
        public void setDocid(String myDocid)
2446
        {
2447
            docid = myDocid;
2448
        }
2449

    
2450
        public String getDocid()
2451
        {
2452
            return docid;
2453
        }
2454

    
2455
        public void setFieldValue(String myValue)
2456
        {
2457
            fieldValue = myValue;
2458
        }
2459

    
2460
        public String getFieldValue()
2461
        {
2462
            return fieldValue;
2463
        }
2464

    
2465
        public void setXMLFieldValue(String xml)
2466
        {
2467
            xmlFieldValue = xml;
2468
        }
2469

    
2470
        public String getXMLFieldValue()
2471
        {
2472
            return xmlFieldValue;
2473
        }
2474
        
2475
        public void setFieldType(String myType)
2476
        {
2477
            fieldType = myType;
2478
        }
2479

    
2480
        public String getFieldType()
2481
        {
2482
            return fieldType;
2483
        }
2484

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