Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *
12
 *   '$Author: tao $'
13
 *     '$Date: 2007-08-31 16:43:26 -0700 (Fri, 31 Aug 2007) $'
14
 * '$Revision: 3392 $'
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 fielddata = null;
1110
      String relation = null;
1111

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

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

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

    
1164
                   // if xml_index is used, there would be just one record per nodeid
1165
                   // as xml_index just keeps one entry for each path
1166
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1167
                       // don't need to merger nodedata
1168
                       value.append("<param name=\"");
1169
                       value.append(fieldname);
1170
                       value.append("\">");
1171
                       value.append(fielddata);
1172
                       value.append("</param>");
1173
                       //set returnvalue
1174
                       returnValue.setDocid(docid);
1175
                       returnValue.setFieldValue(fielddata);
1176
                       returnValue.setXMLFieldValue(value.toString());
1177
                       // Store it in hastable
1178
                       putInArray(parentidList, parentId, returnValue);
1179
                   }
1180
                   else {
1181
                       // need to merge nodedata if they have same parent id and
1182
                       // node type is text
1183
                       fielddata = (String) ( (ReturnFieldValue)
1184
                                             getArrayValue(
1185
                           parentidList, parentId)).getFieldValue()
1186
                           + fielddata;
1187
                       value.append("<param name=\"");
1188
                       value.append(fieldname);
1189
                       value.append("\">");
1190
                       value.append(fielddata);
1191
                       value.append("</param>");
1192
                       returnValue.setDocid(docid);
1193
                       returnValue.setFieldValue(fielddata);
1194
                       returnValue.setXMLFieldValue(value.toString());
1195
                       // remove the old return value from paretnidList
1196
                       parentidList.remove(parentId);
1197
                       // store the new return value in parentidlit
1198
                       putInArray(parentidList, parentId, returnValue);
1199
                   }
1200
                   tableHasRows = rs.next();
1201
               } //while
1202
               rs.close();
1203
               pstmt.close();
1204

    
1205
               // put the merger node data info into doclistReult
1206
               Enumeration xmlFieldValue = (getElements(parentidList)).
1207
                   elements();
1208
               while (xmlFieldValue.hasMoreElements()) {
1209
                   ReturnFieldValue object =
1210
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1211
                   docid = object.getDocid();
1212
                   if (docListResult.containsDocid(docid)) {
1213
                       String removedelement = (String) docListResult.
1214
                           remove(docid);
1215
                       docListResult.
1216
                           addResultDocument(new ResultDocument(docid,
1217
                               removedelement + object.getXMLFieldValue()));
1218
                   }
1219
                   else {
1220
                       docListResult.addResultDocument(
1221
                         new ResultDocument(docid, object.getXMLFieldValue()));
1222
                   }
1223
               } //while
1224
               double docListResultEnd = System.currentTimeMillis() / 1000;
1225
               logMetacat.warn(
1226
                   "Time to prepare ResultDocumentSet after"
1227
                   + " execute extended query: "
1228
                   + (docListResultEnd - extendedQueryEnd));
1229
           }
1230

    
1231
         
1232
           
1233
           
1234
       }//if doclist lenght is great than zero
1235

    
1236
     }//if has extended query
1237

    
1238
      return docListResult;
1239
    }//addReturnfield
1240

    
1241
    /*
1242
    * A method to add relationship to return doclist hash table
1243
    */
1244
   private ResultDocumentSet addRelationship(ResultDocumentSet docListResult,
1245
                                     QuerySpecification qspec,
1246
                                     DBConnection dbconn, boolean useXMLIndex )
1247
                                     throws Exception
1248
  {
1249
    PreparedStatement pstmt = null;
1250
    ResultSet rs = null;
1251
    StringBuffer document = null;
1252
    double startRelation = System.currentTimeMillis() / 1000;
1253
    Iterator docidkeys = docListResult.getDocids();
1254
    while (docidkeys.hasNext())
1255
    {
1256
      //String connstring =
1257
      // "metacat://"+util.getOption("server")+"?docid=";
1258
      String connstring = "%docid=";
1259
      String docidkey;
1260
      synchronized(docListResult)
1261
      {
1262
        docidkey = (String) docidkeys.next();
1263
      }
1264
      pstmt = dbconn.prepareStatement(QuerySpecification
1265
                      .printRelationSQL(docidkey));
1266
      pstmt.execute();
1267
      rs = pstmt.getResultSet();
1268
      boolean tableHasRows = rs.next();
1269
      while (tableHasRows)
1270
      {
1271
        String sub = rs.getString(1);
1272
        String rel = rs.getString(2);
1273
        String obj = rs.getString(3);
1274
        String subDT = rs.getString(4);
1275
        String objDT = rs.getString(5);
1276

    
1277
        document = new StringBuffer();
1278
        document.append("<triple>");
1279
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1280
        document.append("</subject>");
1281
        if (subDT != null)
1282
        {
1283
          document.append("<subjectdoctype>").append(subDT);
1284
          document.append("</subjectdoctype>");
1285
        }
1286
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1287
        document.append("</relationship>");
1288
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1289
        document.append("</object>");
1290
        if (objDT != null)
1291
        {
1292
          document.append("<objectdoctype>").append(objDT);
1293
          document.append("</objectdoctype>");
1294
        }
1295
        document.append("</triple>");
1296

    
1297
        String removedelement = (String) docListResult.get(docidkey);
1298
        docListResult.set(docidkey, removedelement+ document.toString());
1299
        tableHasRows = rs.next();
1300
      }//while
1301
      rs.close();
1302
      pstmt.close();
1303
      
1304
    }//while
1305
    double endRelation = System.currentTimeMillis() / 1000;
1306
    logMetacat.warn("Time to add relationship to return fields (part 3 in return fields): "
1307
                             + (endRelation - startRelation));
1308
    MetaCatUtil.writeDebugToFile("-----------------------------------------Add relationship to return field(part3 in return fields): "
1309
            + (endRelation - startRelation));
1310
    MetaCatUtil.writeDebugToDelimiteredFile(" "+ (endRelation - startRelation), false);
1311

    
1312
    return docListResult;
1313
  }//addRelation
1314

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

    
1388

    
1389
    /*
1390
     * A method to search if Vector contains a particular key string
1391
     */
1392
    private boolean containsKey(Vector parentidList, String parentId)
1393
    {
1394

    
1395
        Vector tempVector = null;
1396

    
1397
        for (int count = 0; count < parentidList.size(); count++) {
1398
            tempVector = (Vector) parentidList.get(count);
1399
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1400
        }
1401
        return false;
1402
    }
1403

    
1404
    /*
1405
     * A method to put key and value in Vector
1406
     */
1407
    private void putInArray(Vector parentidList, String key,
1408
            ReturnFieldValue value)
1409
    {
1410

    
1411
        Vector tempVector = null;
1412

    
1413
        for (int count = 0; count < parentidList.size(); count++) {
1414
            tempVector = (Vector) parentidList.get(count);
1415

    
1416
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1417
                tempVector.remove(1);
1418
                tempVector.add(1, value);
1419
                return;
1420
            }
1421
        }
1422

    
1423
        tempVector = new Vector();
1424
        tempVector.add(0, key);
1425
        tempVector.add(1, value);
1426
        parentidList.add(tempVector);
1427
        return;
1428
    }
1429

    
1430
    /*
1431
     * A method to get value in Vector given a key
1432
     */
1433
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1434
    {
1435

    
1436
        Vector tempVector = null;
1437

    
1438
        for (int count = 0; count < parentidList.size(); count++) {
1439
            tempVector = (Vector) parentidList.get(count);
1440

    
1441
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1442
                    .get(1); }
1443
        }
1444
        return null;
1445
    }
1446

    
1447
    /*
1448
     * A method to get enumeration of all values in Vector
1449
     */
1450
    private Vector getElements(Vector parentidList)
1451
    {
1452
        Vector enumVector = new Vector();
1453
        Vector tempVector = null;
1454

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

    
1458
            enumVector.add(tempVector.get(1));
1459
        }
1460
        return enumVector;
1461
    }
1462

    
1463
  
1464

    
1465
    /*
1466
     * A method to create a query to get owner's docid list
1467
     */
1468
    private String getOwnerQuery(String owner)
1469
    {
1470
        if (owner != null) {
1471
            owner = owner.toLowerCase();
1472
        }
1473
        StringBuffer self = new StringBuffer();
1474

    
1475
        self.append("SELECT docid,docname,doctype,");
1476
        self.append("date_created, date_updated, rev ");
1477
        self.append("FROM xml_documents WHERE docid IN (");
1478
        self.append("(");
1479
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1480
        self.append("nodedata LIKE '%%%' ");
1481
        self.append(") \n");
1482
        self.append(") ");
1483
        self.append(" AND (");
1484
        self.append(" lower(user_owner) = '" + owner + "'");
1485
        self.append(") ");
1486
        return self.toString();
1487
    }
1488

    
1489
    /**
1490
     * format a structured query as an XML document that conforms to the
1491
     * pathquery.dtd and is appropriate for submission to the DBQuery
1492
     * structured query engine
1493
     *
1494
     * @param params The list of parameters that should be included in the
1495
     *            query
1496
     */
1497
    public static String createSQuery(Hashtable params)
1498
    {
1499
        StringBuffer query = new StringBuffer();
1500
        Enumeration elements;
1501
        Enumeration keys;
1502
        String filterDoctype = null;
1503
        String casesensitive = null;
1504
        String searchmode = null;
1505
        Object nextkey;
1506
        Object nextelement;
1507
        //add the xml headers
1508
        query.append("<?xml version=\"1.0\"?>\n");
1509
        query.append("<pathquery version=\"1.2\">\n");
1510

    
1511

    
1512

    
1513
        if (params.containsKey("meta_file_id")) {
1514
            query.append("<meta_file_id>");
1515
            query.append(((String[]) params.get("meta_file_id"))[0]);
1516
            query.append("</meta_file_id>");
1517
        }
1518

    
1519
        if (params.containsKey("returndoctype")) {
1520
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1521
            for (int i = 0; i < returnDoctypes.length; i++) {
1522
                String doctype = (String) returnDoctypes[i];
1523

    
1524
                if (!doctype.equals("any") && !doctype.equals("ANY")
1525
                        && !doctype.equals("")) {
1526
                    query.append("<returndoctype>").append(doctype);
1527
                    query.append("</returndoctype>");
1528
                }
1529
            }
1530
        }
1531

    
1532
        if (params.containsKey("filterdoctype")) {
1533
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1534
            for (int i = 0; i < filterDoctypes.length; i++) {
1535
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1536
                query.append("</filterdoctype>");
1537
            }
1538
        }
1539

    
1540
        if (params.containsKey("returnfield")) {
1541
            String[] returnfield = ((String[]) params.get("returnfield"));
1542
            for (int i = 0; i < returnfield.length; i++) {
1543
                query.append("<returnfield>").append(returnfield[i]);
1544
                query.append("</returnfield>");
1545
            }
1546
        }
1547

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

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

    
1564
        //allows the dynamic switching of boolean operators
1565
        if (params.containsKey("operator")) {
1566
            query.append("<querygroup operator=\""
1567
                    + ((String[]) params.get("operator"))[0] + "\">");
1568
        } else { //the default operator is UNION
1569
            query.append("<querygroup operator=\"UNION\">");
1570
        }
1571

    
1572
        if (params.containsKey("casesensitive")) {
1573
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1574
        } else {
1575
            casesensitive = "false";
1576
        }
1577

    
1578
        if (params.containsKey("searchmode")) {
1579
            searchmode = ((String[]) params.get("searchmode"))[0];
1580
        } else {
1581
            searchmode = "contains";
1582
        }
1583

    
1584
        //anyfield is a special case because it does a
1585
        //free text search. It does not have a <pathexpr>
1586
        //tag. This allows for a free text search within the structured
1587
        //query. This is useful if the INTERSECT operator is used.
1588
        if (params.containsKey("anyfield")) {
1589
            String[] anyfield = ((String[]) params.get("anyfield"));
1590
            //allow for more than one value for anyfield
1591
            for (int i = 0; i < anyfield.length; i++) {
1592
                if (!anyfield[i].equals("")) {
1593
                    query.append("<queryterm casesensitive=\"" + casesensitive
1594
                            + "\" " + "searchmode=\"" + searchmode
1595
                            + "\"><value>" + anyfield[i]
1596
                            + "</value></queryterm>");
1597
                }
1598
            }
1599
        }
1600

    
1601
        //this while loop finds the rest of the parameters
1602
        //and attempts to query for the field specified
1603
        //by the parameter.
1604
        elements = params.elements();
1605
        keys = params.keys();
1606
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1607
            nextkey = keys.nextElement();
1608
            nextelement = elements.nextElement();
1609

    
1610
            //make sure we aren't querying for any of these
1611
            //parameters since the are already in the query
1612
            //in one form or another.
1613
            Vector ignoredParams = new Vector();
1614
            ignoredParams.add("returndoctype");
1615
            ignoredParams.add("filterdoctype");
1616
            ignoredParams.add("action");
1617
            ignoredParams.add("qformat");
1618
            ignoredParams.add("anyfield");
1619
            ignoredParams.add("returnfield");
1620
            ignoredParams.add("owner");
1621
            ignoredParams.add("site");
1622
            ignoredParams.add("operator");
1623
            ignoredParams.add("sessionid");
1624
            ignoredParams.add("pagesize");
1625
            ignoredParams.add("pagestart");
1626

    
1627
            // Also ignore parameters listed in the properties file
1628
            // so that they can be passed through to stylesheets
1629
            String paramsToIgnore = MetaCatUtil
1630
                    .getOption("query.ignored.params");
1631
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1632
            while (st.hasMoreTokens()) {
1633
                ignoredParams.add(st.nextToken());
1634
            }
1635
            if (!ignoredParams.contains(nextkey.toString())) {
1636
                //allow for more than value per field name
1637
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1638
                    if (!((String[]) nextelement)[i].equals("")) {
1639
                        query.append("<queryterm casesensitive=\""
1640
                                + casesensitive + "\" " + "searchmode=\""
1641
                                + searchmode + "\">" + "<value>" +
1642
                                //add the query value
1643
                                ((String[]) nextelement)[i]
1644
                                + "</value><pathexpr>" +
1645
                                //add the path to query by
1646
                                nextkey.toString() + "</pathexpr></queryterm>");
1647
                    }
1648
                }
1649
            }
1650
        }
1651
        query.append("</querygroup></pathquery>");
1652
        //append on the end of the xml and return the result as a string
1653
        return query.toString();
1654
    }
1655

    
1656
    /**
1657
     * format a simple free-text value query as an XML document that conforms
1658
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1659
     * structured query engine
1660
     *
1661
     * @param value the text string to search for in the xml catalog
1662
     * @param doctype the type of documents to include in the result set -- use
1663
     *            "any" or "ANY" for unfiltered result sets
1664
     */
1665
    public static String createQuery(String value, String doctype)
1666
    {
1667
        StringBuffer xmlquery = new StringBuffer();
1668
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1669
        xmlquery.append("<pathquery version=\"1.0\">");
1670

    
1671
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1672
            xmlquery.append("<returndoctype>");
1673
            xmlquery.append(doctype).append("</returndoctype>");
1674
        }
1675

    
1676
        xmlquery.append("<querygroup operator=\"UNION\">");
1677
        //chad added - 8/14
1678
        //the if statement allows a query to gracefully handle a null
1679
        //query. Without this if a nullpointerException is thrown.
1680
        if (!value.equals("")) {
1681
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1682
            xmlquery.append("searchmode=\"contains\">");
1683
            xmlquery.append("<value>").append(value).append("</value>");
1684
            xmlquery.append("</queryterm>");
1685
        }
1686
        xmlquery.append("</querygroup>");
1687
        xmlquery.append("</pathquery>");
1688

    
1689
        return (xmlquery.toString());
1690
    }
1691

    
1692
    /**
1693
     * format a simple free-text value query as an XML document that conforms
1694
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1695
     * structured query engine
1696
     *
1697
     * @param value the text string to search for in the xml catalog
1698
     */
1699
    public static String createQuery(String value)
1700
    {
1701
        return createQuery(value, "any");
1702
    }
1703

    
1704
    /**
1705
     * Check for "READ" permission on @docid for @user and/or @group from DB
1706
     * connection
1707
     */
1708
    private boolean hasPermission(String user, String[] groups, String docid)
1709
            throws SQLException, Exception
1710
    {
1711
        // Check for READ permission on @docid for @user and/or @groups
1712
        PermissionController controller = new PermissionController(docid);
1713
        return controller.hasPermission(user, groups,
1714
                AccessControlInterface.READSTRING);
1715
    }
1716

    
1717
    /**
1718
     * Get all docIds list for a data packadge
1719
     *
1720
     * @param dataPackageDocid, the string in docId field of xml_relation table
1721
     */
1722
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1723
    {
1724
        DBConnection dbConn = null;
1725
        int serialNumber = -1;
1726
        Vector docIdList = new Vector();//return value
1727
        PreparedStatement pStmt = null;
1728
        ResultSet rs = null;
1729
        String docIdInSubjectField = null;
1730
        String docIdInObjectField = null;
1731

    
1732
        // Check the parameter
1733
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1734

    
1735
        //the query stirng
1736
        String query = "SELECT subject, object from xml_relation where docId = ?";
1737
        try {
1738
            dbConn = DBConnectionPool
1739
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1740
            serialNumber = dbConn.getCheckOutSerialNumber();
1741
            pStmt = dbConn.prepareStatement(query);
1742
            //bind the value to query
1743
            pStmt.setString(1, dataPackageDocid);
1744

    
1745
            //excute the query
1746
            pStmt.execute();
1747
            //get the result set
1748
            rs = pStmt.getResultSet();
1749
            //process the result
1750
            while (rs.next()) {
1751
                //In order to get the whole docIds in a data packadge,
1752
                //we need to put the docIds of subject and object field in
1753
                // xml_relation
1754
                //into the return vector
1755
                docIdInSubjectField = rs.getString(1);//the result docId in
1756
                                                      // subject field
1757
                docIdInObjectField = rs.getString(2);//the result docId in
1758
                                                     // object field
1759

    
1760
                //don't put the duplicate docId into the vector
1761
                if (!docIdList.contains(docIdInSubjectField)) {
1762
                    docIdList.add(docIdInSubjectField);
1763
                }
1764

    
1765
                //don't put the duplicate docId into the vector
1766
                if (!docIdList.contains(docIdInObjectField)) {
1767
                    docIdList.add(docIdInObjectField);
1768
                }
1769
            }//while
1770
            //close the pStmt
1771
            pStmt.close();
1772
        }//try
1773
        catch (SQLException e) {
1774
            logMetacat.error("Error in getDocidListForDataPackage: "
1775
                    + e.getMessage());
1776
        }//catch
1777
        finally {
1778
            try {
1779
                pStmt.close();
1780
            }//try
1781
            catch (SQLException ee) {
1782
                logMetacat.error(
1783
                        "Error in getDocidListForDataPackage: "
1784
                                + ee.getMessage());
1785
            }//catch
1786
            finally {
1787
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1788
            }//fianlly
1789
        }//finally
1790
        return docIdList;
1791
    }//getCurrentDocidListForDataPackadge()
1792

    
1793
    /**
1794
     * Get all docIds list for a data packadge
1795
     *
1796
     * @param dataPackageDocid, the string in docId field of xml_relation table
1797
     */
1798
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1799
    {
1800

    
1801
        Vector docIdList = new Vector();//return value
1802
        Vector tripleList = null;
1803
        String xml = null;
1804

    
1805
        // Check the parameter
1806
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1807

    
1808
        try {
1809
            //initial a documentImpl object
1810
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1811
            //transfer to documentImpl object to string
1812
            xml = packageDocument.toString();
1813

    
1814
            //create a tripcollection object
1815
            TripleCollection tripleForPackage = new TripleCollection(
1816
                    new StringReader(xml));
1817
            //get the vetor of triples
1818
            tripleList = tripleForPackage.getCollection();
1819

    
1820
            for (int i = 0; i < tripleList.size(); i++) {
1821
                //put subject docid into docIdlist without duplicate
1822
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1823
                        .getSubject())) {
1824
                    //put subject docid into docIdlist
1825
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1826
                }
1827
                //put object docid into docIdlist without duplicate
1828
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1829
                        .getObject())) {
1830
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1831
                }
1832
            }//for
1833
        }//try
1834
        catch (Exception e) {
1835
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1836
                    + e.getMessage());
1837
        }//catch
1838

    
1839
        // return result
1840
        return docIdList;
1841
    }//getDocidListForPackageInXMLRevisions()
1842

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

    
1895
    /**
1896
     * Check if the user has the permission to export data package
1897
     *
1898
     * @param conn, the connection
1899
     * @param docId, the id need to be checked
1900
     * @param user, the name of user
1901
     * @param groups, the user's group
1902
     */
1903
    private boolean hasPermissionToExportPackage(String docId, String user,
1904
            String[] groups) throws Exception
1905
    {
1906
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1907
        return DocumentImpl.hasReadPermission(user, groups, docId);
1908
    }
1909

    
1910
    /**
1911
     * Get the current Rev for a docid in xml_documents table
1912
     *
1913
     * @param docId, the id need to get version numb If the return value is -5,
1914
     *            means no value in rev field for this docid
1915
     */
1916
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1917
            throws SQLException
1918
    {
1919
        int rev = -5;
1920
        PreparedStatement pStmt = null;
1921
        ResultSet rs = null;
1922
        String query = "SELECT rev from xml_documents where docId = ?";
1923
        DBConnection dbConn = null;
1924
        int serialNumber = -1;
1925
        try {
1926
            dbConn = DBConnectionPool
1927
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1928
            serialNumber = dbConn.getCheckOutSerialNumber();
1929
            pStmt = dbConn.prepareStatement(query);
1930
            //bind the value to query
1931
            pStmt.setString(1, docId);
1932
            //execute the query
1933
            pStmt.execute();
1934
            rs = pStmt.getResultSet();
1935
            //process the result
1936
            if (rs.next()) //There are some records for rev
1937
            {
1938
                rev = rs.getInt(1);
1939
                ;//It is the version for given docid
1940
            } else {
1941
                rev = -5;
1942
            }
1943

    
1944
        }//try
1945
        catch (SQLException e) {
1946
            logMetacat.error(
1947
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1948
                            + e.getMessage());
1949
            throw e;
1950
        }//catch
1951
        finally {
1952
            try {
1953
                pStmt.close();
1954
            }//try
1955
            catch (SQLException ee) {
1956
                logMetacat.error(
1957
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1958
                                + ee.getMessage());
1959
            }//catch
1960
            finally {
1961
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1962
            }//finally
1963
        }//finally
1964
        return rev;
1965
    }//getCurrentRevFromXMLDoumentsTable
1966

    
1967
    /**
1968
     * put a doc into a zip output stream
1969
     *
1970
     * @param docImpl, docmentImpl object which will be sent to zip output
1971
     *            stream
1972
     * @param zipOut, zip output stream which the docImpl will be put
1973
     * @param packageZipEntry, the zip entry name for whole package
1974
     */
1975
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1976
            ZipOutputStream zipOut, String packageZipEntry)
1977
            throws ClassNotFoundException, IOException, SQLException,
1978
            McdbException, Exception
1979
    {
1980
        byte[] byteString = null;
1981
        ZipEntry zEntry = null;
1982

    
1983
        byteString = docImpl.toString().getBytes();
1984
        //use docId as the zip entry's name
1985
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1986
                + docImpl.getDocID());
1987
        zEntry.setSize(byteString.length);
1988
        zipOut.putNextEntry(zEntry);
1989
        zipOut.write(byteString, 0, byteString.length);
1990
        zipOut.closeEntry();
1991

    
1992
    }//addDocToZipOutputStream()
1993

    
1994
    /**
1995
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1996
     * only inlcudes current version. If a DocumentImple object couldn't find
1997
     * for a docid, then the String of this docid was added to vetor rather
1998
     * than DocumentImple object.
1999
     *
2000
     * @param docIdList, a vetor hold a docid list for a data package. In
2001
     *            docid, there is not version number in it.
2002
     */
2003

    
2004
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2005
            throws McdbException, Exception
2006
    {
2007
        //Connection dbConn=null;
2008
        Vector documentImplList = new Vector();
2009
        int rev = 0;
2010

    
2011
        // Check the parameter
2012
        if (docIdList.isEmpty()) { return documentImplList; }//if
2013

    
2014
        //for every docid in vector
2015
        for (int i = 0; i < docIdList.size(); i++) {
2016
            try {
2017
                //get newest version for this docId
2018
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2019
                        .elementAt(i));
2020

    
2021
                // There is no record for this docId in xml_documents table
2022
                if (rev == -5) {
2023
                    // Rather than put DocumentImple object, put a String
2024
                    // Object(docid)
2025
                    // into the documentImplList
2026
                    documentImplList.add((String) docIdList.elementAt(i));
2027
                    // Skip other code
2028
                    continue;
2029
                }
2030

    
2031
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2032
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
2033

    
2034
                //create new documentImpl object
2035
                DocumentImpl documentImplObject = new DocumentImpl(
2036
                        docidPlusVersion);
2037
                //add them to vector
2038
                documentImplList.add(documentImplObject);
2039
            }//try
2040
            catch (Exception e) {
2041
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
2042
                        + e.getMessage());
2043
                // continue the for loop
2044
                continue;
2045
            }
2046
        }//for
2047
        return documentImplList;
2048
    }
2049

    
2050
    /**
2051
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2052
     * object couldn't find for a docid, then the String of this docid was
2053
     * added to vetor rather than DocumentImple object.
2054
     *
2055
     * @param docIdList, a vetor hold a docid list for a data package. In
2056
     *            docid, t here is version number in it.
2057
     */
2058
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2059
    {
2060
        //Connection dbConn=null;
2061
        Vector documentImplList = new Vector();
2062
        String siteCode = null;
2063
        String uniqueId = null;
2064
        int rev = 0;
2065

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

    
2069
        //for every docid in vector
2070
        for (int i = 0; i < docIdList.size(); i++) {
2071

    
2072
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2073

    
2074
            try {
2075
                //create new documentImpl object
2076
                DocumentImpl documentImplObject = new DocumentImpl(
2077
                        docidPlusVersion);
2078
                //add them to vector
2079
                documentImplList.add(documentImplObject);
2080
            }//try
2081
            catch (McdbDocNotFoundException notFoundE) {
2082
                logMetacat.error(
2083
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2084
                                + notFoundE.getMessage());
2085
                // Rather than add a DocumentImple object into vetor, a String
2086
                // object
2087
                // - the doicd was added to the vector
2088
                documentImplList.add(docidPlusVersion);
2089
                // Continue the for loop
2090
                continue;
2091
            }//catch
2092
            catch (Exception e) {
2093
                logMetacat.error(
2094
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2095
                                + e.getMessage());
2096
                // Continue the for loop
2097
                continue;
2098
            }//catch
2099

    
2100
        }//for
2101
        return documentImplList;
2102
    }//getOldVersionAllDocumentImple
2103

    
2104
    /**
2105
     * put a data file into a zip output stream
2106
     *
2107
     * @param docImpl, docmentImpl object which will be sent to zip output
2108
     *            stream
2109
     * @param zipOut, the zip output stream which the docImpl will be put
2110
     * @param packageZipEntry, the zip entry name for whole package
2111
     */
2112
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2113
            ZipOutputStream zipOut, String packageZipEntry)
2114
            throws ClassNotFoundException, IOException, SQLException,
2115
            McdbException, Exception
2116
    {
2117
        byte[] byteString = null;
2118
        ZipEntry zEntry = null;
2119
        // this is data file; add file to zip
2120
        String filePath = MetaCatUtil.getOption("datafilepath");
2121
        if (!filePath.endsWith("/")) {
2122
            filePath += "/";
2123
        }
2124
        String fileName = filePath + docImpl.getDocID();
2125
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2126
        zipOut.putNextEntry(zEntry);
2127
        FileInputStream fin = null;
2128
        try {
2129
            fin = new FileInputStream(fileName);
2130
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2131
            int b = fin.read(buf);
2132
            while (b != -1) {
2133
                zipOut.write(buf, 0, b);
2134
                b = fin.read(buf);
2135
            }//while
2136
            zipOut.closeEntry();
2137
        }//try
2138
        catch (IOException ioe) {
2139
            logMetacat.error("There is an exception: "
2140
                    + ioe.getMessage());
2141
        }//catch
2142
    }//addDataFileToZipOutputStream()
2143

    
2144
    /**
2145
     * create a html summary for data package and put it into zip output stream
2146
     *
2147
     * @param docImplList, the documentImpl ojbects in data package
2148
     * @param zipOut, the zip output stream which the html should be put
2149
     * @param packageZipEntry, the zip entry name for whole package
2150
     */
2151
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2152
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2153
    {
2154
        StringBuffer htmlDoc = new StringBuffer();
2155
        ZipEntry zEntry = null;
2156
        byte[] byteString = null;
2157
        InputStream source;
2158
        DBTransform xmlToHtml;
2159

    
2160
        //create a DBTransform ojbect
2161
        xmlToHtml = new DBTransform();
2162
        //head of html
2163
        htmlDoc.append("<html><head></head><body>");
2164
        for (int i = 0; i < docImplList.size(); i++) {
2165
            // If this String object, this means it is missed data file
2166
            if ((((docImplList.elementAt(i)).getClass()).toString())
2167
                    .equals("class java.lang.String")) {
2168

    
2169
                htmlDoc.append("<a href=\"");
2170
                String dataFileid = (String) docImplList.elementAt(i);
2171
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2172
                htmlDoc.append("Data File: ");
2173
                htmlDoc.append(dataFileid).append("</a><br>");
2174
                htmlDoc.append("<br><hr><br>");
2175

    
2176
            }//if
2177
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2178
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2179
                                              // transform it.
2180
                //transform each file individually then concatenate all of the
2181
                //transformations together.
2182

    
2183
                //for metadata xml title
2184
                htmlDoc.append("<h2>");
2185
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2186
                        .getDocID());
2187
                //htmlDoc.append(".");
2188
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2189
                htmlDoc.append("</h2>");
2190
                //do the actual transform
2191
                StringWriter docString = new StringWriter();
2192
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2193
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2194
                        "-//W3C//HTML//EN", "html", docString);
2195
                htmlDoc.append(docString.toString());
2196
                htmlDoc.append("<br><br><hr><br><br>");
2197
            }//if
2198
            else { //this is a data file so we should link to it in the html
2199
                htmlDoc.append("<a href=\"");
2200
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2201
                        .getDocID();
2202
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2203
                htmlDoc.append("Data File: ");
2204
                htmlDoc.append(dataFileid).append("</a><br>");
2205
                htmlDoc.append("<br><hr><br>");
2206
            }//else
2207
        }//for
2208
        htmlDoc.append("</body></html>");
2209
        byteString = htmlDoc.toString().getBytes();
2210
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2211
        zEntry.setSize(byteString.length);
2212
        zipOut.putNextEntry(zEntry);
2213
        zipOut.write(byteString, 0, byteString.length);
2214
        zipOut.closeEntry();
2215
        //dbConn.close();
2216

    
2217
    }//addHtmlSummaryToZipOutputStream
2218

    
2219
    /**
2220
     * put a data packadge into a zip output stream
2221
     *
2222
     * @param docId, which the user want to put into zip output stream,it has version
2223
     * @param out, a servletoutput stream which the zip output stream will be
2224
     *            put
2225
     * @param user, the username of the user
2226
     * @param groups, the group of the user
2227
     */
2228
    public ZipOutputStream getZippedPackage(String docIdString,
2229
            ServletOutputStream out, String user, String[] groups,
2230
            String passWord) throws ClassNotFoundException, IOException,
2231
            SQLException, McdbException, NumberFormatException, Exception
2232
    {
2233
        ZipOutputStream zOut = null;
2234
        String elementDocid = null;
2235
        DocumentImpl docImpls = null;
2236
        //Connection dbConn = null;
2237
        Vector docIdList = new Vector();
2238
        Vector documentImplList = new Vector();
2239
        Vector htmlDocumentImplList = new Vector();
2240
        String packageId = null;
2241
        String rootName = "package";//the package zip entry name
2242

    
2243
        String docId = null;
2244
        int version = -5;
2245
        // Docid without revision
2246
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2247
        // revision number
2248
        version = MetaCatUtil.getVersionFromString(docIdString);
2249

    
2250
        //check if the reqused docId is a data package id
2251
        if (!isDataPackageId(docId)) {
2252

    
2253
            /*
2254
             * Exception e = new Exception("The request the doc id "
2255
             * +docIdString+ " is not a data package id");
2256
             */
2257

    
2258
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2259
            // zip
2260
            //up the single document and return the zip file.
2261
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2262

    
2263
                Exception e = new Exception("User " + user
2264
                        + " does not have permission"
2265
                        + " to export the data package " + docIdString);
2266
                throw e;
2267
            }
2268

    
2269
            docImpls = new DocumentImpl(docIdString);
2270
            //checking if the user has the permission to read the documents
2271
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2272
                    .getDocID())) {
2273
                zOut = new ZipOutputStream(out);
2274
                //if the docImpls is metadata
2275
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2276
                    //add metadata into zip output stream
2277
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2278
                }//if
2279
                else {
2280
                    //it is data file
2281
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2282
                    htmlDocumentImplList.add(docImpls);
2283
                }//else
2284
            }//if
2285

    
2286
            zOut.finish(); //terminate the zip file
2287
            return zOut;
2288
        }
2289
        // Check the permission of user
2290
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2291

    
2292
            Exception e = new Exception("User " + user
2293
                    + " does not have permission"
2294
                    + " to export the data package " + docIdString);
2295
            throw e;
2296
        } else //it is a packadge id
2297
        {
2298
            //store the package id
2299
            packageId = docId;
2300
            //get current version in database
2301
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2302
            //If it is for current version (-1 means user didn't specify
2303
            // revision)
2304
            if ((version == -1) || version == currentVersion) {
2305
                //get current version number
2306
                version = currentVersion;
2307
                //get package zip entry name
2308
                //it should be docId.revsion.package
2309
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2310
                        + version + MetaCatUtil.getOption("accNumSeparator")
2311
                        + "package";
2312
                //get the whole id list for data packadge
2313
                docIdList = getCurrentDocidListForDataPackage(packageId);
2314
                //get the whole documentImple object
2315
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2316

    
2317
            }//if
2318
            else if (version > currentVersion || version < -1) {
2319
                throw new Exception("The user specified docid: " + docId + "."
2320
                        + version + " doesn't exist");
2321
            }//else if
2322
            else //for an old version
2323
            {
2324

    
2325
                rootName = docIdString
2326
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2327
                //get the whole id list for data packadge
2328
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2329

    
2330
                //get the whole documentImple object
2331
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2332
            }//else
2333

    
2334
            // Make sure documentImplist is not empty
2335
            if (documentImplList.isEmpty()) { throw new Exception(
2336
                    "Couldn't find component for data package: " + packageId); }//if
2337

    
2338
            zOut = new ZipOutputStream(out);
2339
            //put every element into zip output stream
2340
            for (int i = 0; i < documentImplList.size(); i++) {
2341
                // if the object in the vetor is String, this means we couldn't
2342
                // find
2343
                // the document locally, we need find it remote
2344
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2345
                        .equals("class java.lang.String")) {
2346
                    // Get String object from vetor
2347
                    String documentId = (String) documentImplList.elementAt(i);
2348
                    logMetacat.info("docid: " + documentId);
2349
                    // Get doicd without revision
2350
                    String docidWithoutRevision = MetaCatUtil
2351
                            .getDocIdFromString(documentId);
2352
                    logMetacat.info("docidWithoutRevsion: "
2353
                            + docidWithoutRevision);
2354
                    // Get revision
2355
                    String revision = MetaCatUtil
2356
                            .getRevisionStringFromString(documentId);
2357
                    logMetacat.info("revsion from docIdentifier: "
2358
                            + revision);
2359
                    // Zip entry string
2360
                    String zipEntryPath = rootName + "/data/";
2361
                    // Create a RemoteDocument object
2362
                    RemoteDocument remoteDoc = new RemoteDocument(
2363
                            docidWithoutRevision, revision, user, passWord,
2364
                            zipEntryPath);
2365
                    // Here we only read data file from remote metacat
2366
                    String docType = remoteDoc.getDocType();
2367
                    if (docType != null) {
2368
                        if (docType.equals("BIN")) {
2369
                            // Put remote document to zip output
2370
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2371
                            // Add String object to htmlDocumentImplList
2372
                            String elementInHtmlList = remoteDoc
2373
                                    .getDocIdWithoutRevsion()
2374
                                    + MetaCatUtil.getOption("accNumSeparator")
2375
                                    + remoteDoc.getRevision();
2376
                            htmlDocumentImplList.add(elementInHtmlList);
2377
                        }//if
2378
                    }//if
2379

    
2380
                }//if
2381
                else {
2382
                    //create a docmentImpls object (represent xml doc) base on
2383
                    // the docId
2384
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2385
                    //checking if the user has the permission to read the
2386
                    // documents
2387
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2388
                            .getDocID())) {
2389
                        //if the docImpls is metadata
2390
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2391
                            //add metadata into zip output stream
2392
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2393
                            //add the documentImpl into the vetor which will
2394
                            // be used in html
2395
                            htmlDocumentImplList.add(docImpls);
2396

    
2397
                        }//if
2398
                        else {
2399
                            //it is data file
2400
                            addDataFileToZipOutputStream(docImpls, zOut,
2401
                                    rootName);
2402
                            htmlDocumentImplList.add(docImpls);
2403
                        }//else
2404
                    }//if
2405
                }//else
2406
            }//for
2407

    
2408
            //add html summary file
2409
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2410
                    rootName);
2411
            zOut.finish(); //terminate the zip file
2412
            //dbConn.close();
2413
            return zOut;
2414
        }//else
2415
    }//getZippedPackage()
2416

    
2417
    private class ReturnFieldValue
2418
    {
2419

    
2420
        private String docid = null; //return field value for this docid
2421

    
2422
        private String fieldValue = null;
2423

    
2424
        private String xmlFieldValue = null; //return field value in xml
2425
                                             // format
2426

    
2427
        public void setDocid(String myDocid)
2428
        {
2429
            docid = myDocid;
2430
        }
2431

    
2432
        public String getDocid()
2433
        {
2434
            return docid;
2435
        }
2436

    
2437
        public void setFieldValue(String myValue)
2438
        {
2439
            fieldValue = myValue;
2440
        }
2441

    
2442
        public String getFieldValue()
2443
        {
2444
            return fieldValue;
2445
        }
2446

    
2447
        public void setXMLFieldValue(String xml)
2448
        {
2449
            xmlFieldValue = xml;
2450
        }
2451

    
2452
        public String getXMLFieldValue()
2453
        {
2454
            return xmlFieldValue;
2455
        }
2456

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