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: berkley $'
13
 *     '$Date: 2010-05-18 11:43:47 -0700 (Tue, 18 May 2010) $'
14
 * '$Revision: 5363 $'
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.metacat.accesscontrol.AccessControlInterface;
52
import edu.ucsb.nceas.metacat.database.DBConnection;
53
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
54
import edu.ucsb.nceas.metacat.properties.PropertyService;
55
import edu.ucsb.nceas.metacat.util.AuthUtil;
56
import edu.ucsb.nceas.metacat.util.DocumentUtil;
57
import edu.ucsb.nceas.metacat.util.MetacatUtil;
58
import edu.ucsb.nceas.morpho.datapackage.Triple;
59
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
60
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
61

    
62

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

    
72
    static final int ALL = 1;
73

    
74
    static final int WRITE = 2;
75

    
76
    static final int READ = 4;
77

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

    
81
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
82

    
83
    /** true if the metacat spatial option is installed **/
84
    private final boolean METACAT_SPATIAL = true;
85

    
86
    /** useful if you just want to grab a list of docids. Since the docids can be very long,
87
         it is a vector of vector  **/
88
    Vector docidOverride = new Vector();
89
    
90
    // a hash table serves as query reuslt cache. Key of hashtable
91
    // is a query string and value is result xml string
92
    private static Hashtable queryResultCache = new Hashtable();
93
    
94
    // Capacity of the query result cache
95
    private static final int QUERYRESULTCACHESIZE;
96
    static {
97
    	int qryRsltCacheSize = 0;
98
    	try {
99
    		qryRsltCacheSize = Integer.parseInt(PropertyService.getProperty("database.queryresultCacheSize"));
100
    	} catch (PropertyNotFoundException pnfe) {
101
    		System.err.println("Could not get QUERYRESULTCACHESIZE property in static block: "
102
					+ pnfe.getMessage());
103
    	}
104
    	QUERYRESULTCACHESIZE = qryRsltCacheSize;
105
    }
106
    
107

    
108
    // Size of page for non paged query
109
    private static final int NONPAGESIZE = 99999999;
110
    /**
111
     * the main routine used to test the DBQuery utility.
112
     * <p>
113
     * Usage: java DBQuery <xmlfile>
114
     *
115
     * @param xmlfile the filename of the xml file containing the query
116
     */
117
    static public void main(String[] args)
118
    {
119

    
120
        if (args.length < 1) {
121
            System.err.println("Wrong number of arguments!!!");
122
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
123
            return;
124
        } else {
125
            try {
126

    
127
                int i = 0;
128
                boolean showRuntime = false;
129
                boolean useXMLIndex = false;
130
                if (args[i].equals("-t")) {
131
                    showRuntime = true;
132
                    i++;
133
                }
134
                if (args[i].equals("-index")) {
135
                    useXMLIndex = true;
136
                    i++;
137
                }
138
                String xmlfile = args[i];
139

    
140
                // Time the request if asked for
141
                double startTime = System.currentTimeMillis();
142

    
143
                // Open a connection to the database
144
                //Connection dbconn = util.openDBConnection();
145

    
146
                double connTime = System.currentTimeMillis();
147

    
148
                // Execute the query
149
                DBQuery queryobj = new DBQuery();
150
                FileReader xml = new FileReader(new File(xmlfile));
151
                Hashtable nodelist = null;
152
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
153

    
154
                // Print the reulting document listing
155
                StringBuffer result = new StringBuffer();
156
                String document = null;
157
                String docid = null;
158
                result.append("<?xml version=\"1.0\"?>\n");
159
                result.append("<resultset>\n");
160

    
161
                if (!showRuntime) {
162
                    Enumeration doclist = nodelist.keys();
163
                    while (doclist.hasMoreElements()) {
164
                        docid = (String) doclist.nextElement();
165
                        document = (String) nodelist.get(docid);
166
                        result.append("  <document>\n    " + document
167
                                + "\n  </document>\n");
168
                    }
169

    
170
                    result.append("</resultset>\n");
171
                }
172
                // Time the request if asked for
173
                double stopTime = System.currentTimeMillis();
174
                double dbOpenTime = (connTime - startTime) / 1000;
175
                double readTime = (stopTime - connTime) / 1000;
176
                double executionTime = (stopTime - startTime) / 1000;
177
                if (showRuntime) {
178
                    System.out.print("  " + executionTime);
179
                    System.out.print("  " + dbOpenTime);
180
                    System.out.print("  " + readTime);
181
                    System.out.print("  " + nodelist.size());
182
                    System.out.println();
183
                }
184
                //System.out.println(result);
185
                //write into a file "result.txt"
186
                if (!showRuntime) {
187
                    File f = new File("./result.txt");
188
                    FileWriter fw = new FileWriter(f);
189
                    BufferedWriter out = new BufferedWriter(fw);
190
                    out.write(result.toString());
191
                    out.flush();
192
                    out.close();
193
                    fw.close();
194
                }
195

    
196
            } catch (Exception e) {
197
                System.err.println("Error in DBQuery.main");
198
                System.err.println(e.getMessage());
199
                e.printStackTrace(System.err);
200
            }
201
        }
202
    }
203

    
204
    /**
205
     * construct an instance of the DBQuery class
206
     *
207
     * <p>
208
     * Generally, one would call the findDocuments() routine after creating an
209
     * instance to specify the search query
210
     * </p>
211
     *
212

    
213
     * @param parserName the fully qualified name of a Java class implementing
214
     *            the org.xml.sax.XMLReader interface
215
     */
216
    public DBQuery() throws PropertyNotFoundException
217
    {
218
        String parserName = PropertyService.getProperty("xml.saxparser");
219
        this.parserName = parserName;
220
    }
221

    
222
    /**
223
     * 
224
     * Construct an instance of DBQuery Class
225
     * BUT accept a docid Vector that will supersede
226
     * the query.printSQL() method
227
     *
228
     * If a docid Vector is passed in,
229
     * the docids will be used to create a simple IN query 
230
     * without the multiple subselects of the printSQL() method
231
     *
232
     * Using this constructor, we just check for 
233
     * a docidOverride Vector in the findResultDoclist() method
234
     *
235
     * @param docids List of docids to display in the resultset
236
     */
237
    public DBQuery(Vector docids) throws PropertyNotFoundException
238
    {
239
    	// since the query will be too long to be handled, so we divided the 
240
    	// docids vector into couple vectors.
241
    	int size = (new Integer(PropertyService.getProperty("database.appResultsetSize"))).intValue();
242
    	logMetacat.info("DBQuery.DBQuery - The size of select doicds is "+docids.size());
243
    	logMetacat.info("DBQuery.DBQuery - The application result size in metacat.properties is "+size);
244
    	Vector subset = new Vector();
245
    	if (docids != null && docids.size() > size)
246
    	{
247
    		int index = 0;
248
    		for (int i=0; i< docids.size(); i++)
249
    		{
250
    			
251
    			if (index < size)
252
    			{  	
253
    				subset.add(docids.elementAt(i));
254
    				index ++;
255
    			}
256
    			else
257
    			{
258
    				docidOverride.add(subset);
259
    				subset = new Vector();
260
    				subset.add(docids.elementAt(i));
261
    			    index = 1;
262
    			}
263
    		}
264
    		if (!subset.isEmpty())
265
    		{
266
    			docidOverride.add(subset);
267
    		}
268
    		
269
    	}
270
    	else
271
    	{
272
    		this.docidOverride.add(docids);
273
    	}
274
        
275
        String parserName = PropertyService.getProperty("xml.saxparser");
276
        this.parserName = parserName;
277
    }
278

    
279
  /**
280
   * Method put the search result set into out printerwriter
281
   * @param resoponse the return response
282
   * @param out the output printer
283
   * @param params the paratermer hashtable
284
   * @param user the user name (it maybe different to the one in param)
285
   * @param groups the group array
286
   * @param sessionid  the sessionid
287
   */
288
  public void findDocuments(HttpServletResponse response,
289
                                       PrintWriter out, Hashtable params,
290
                                       String user, String[] groups,
291
                                       String sessionid) throws PropertyNotFoundException
292
  {
293
    boolean useXMLIndex = (new Boolean(PropertyService.getProperty("database.usexmlindex")))
294
               .booleanValue();
295
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
296

    
297
  }
298

    
299

    
300
    /**
301
     * Method put the search result set into out printerwriter
302
     * @param resoponse the return response
303
     * @param out the output printer
304
     * @param params the paratermer hashtable
305
     * @param user the user name (it maybe different to the one in param)
306
     * @param groups the group array
307
     * @param sessionid  the sessionid
308
     */
309
    public void findDocuments(HttpServletResponse response,
310
                                         PrintWriter out, Hashtable params,
311
                                         String user, String[] groups,
312
                                         String sessionid, boolean useXMLIndex)
313
    {
314
      int pagesize = 0;
315
      int pagestart = 0;
316
      long transferWarnLimit = 0; 
317
      
318
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
319
      {
320
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
321
        String pagestartStr = ((String[])params.get("pagestart"))[0];
322
        if(pagesizeStr != null && pagestartStr != null)
323
        {
324
          pagesize = (new Integer(pagesizeStr)).intValue();
325
          pagestart = (new Integer(pagestartStr)).intValue();
326
        }
327
      }
328
      
329
      String xmlquery = null;
330
      String qformat = null;
331
      // get query and qformat
332
      try {
333
    	xmlquery = ((String[])params.get("query"))[0];
334

    
335
        logMetacat.info("DBQuery.findDocuments - SESSIONID: " + sessionid);
336
        logMetacat.info("DBQuery.findDocuments - xmlquery: " + xmlquery);
337
        qformat = ((String[])params.get("qformat"))[0];
338
        logMetacat.info("DBQuery.findDocuments - qformat: " + qformat);
339
      }
340
      catch (Exception ee)
341
      {
342
        logMetacat.error("DBQuery.findDocuments - Couldn't retrieve xmlquery or qformat value from "
343
                  +"params hashtable in DBQuery.findDocuments: "
344
                  + ee.getMessage()); 
345
      }
346
      // Get the XML query and covert it into a SQL statment
347
      QuerySpecification qspec = null;
348
      if ( xmlquery != null)
349
      {
350
         xmlquery = transformQuery(xmlquery);
351
         try
352
         {
353
           qspec = new QuerySpecification(xmlquery,
354
                                          parserName,
355
                                          PropertyService.getProperty("document.accNumSeparator"));
356
         }
357
         catch (Exception ee)
358
         {
359
           logMetacat.error("DBQuery.findDocuments - error generating QuerySpecification object: "
360
                                    + ee.getMessage());
361
         }
362
      }
363

    
364

    
365

    
366
      if (qformat != null && qformat.equals(MetacatUtil.XMLFORMAT))
367
      {
368
        //xml format
369
        if(response != null)
370
            response.setContentType("text/xml");
371
        StringBuffer sb = createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex, 
372
          pagesize, pagestart, sessionid);
373
        //System.out.println("result from createResultDocument: " + sb.toString());
374
      }//if
375
      else
376
      {
377
        //knb format, in this case we will get whole result and sent it out
378
        response.setContentType("text/html");
379
        PrintWriter nonout = null;
380
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
381
                                                groups, useXMLIndex, pagesize, 
382
                                                pagestart, sessionid);
383
        
384
        //transfer the xml to html
385
        try
386
        {
387
         long startHTMLTransform = System.currentTimeMillis();
388
         DBTransform trans = new DBTransform();
389
         response.setContentType("text/html");
390

    
391
         // if the user is a moderator, then pass a param to the 
392
         // xsl specifying the fact
393
         if(AuthUtil.isModerator(user, groups)){
394
        	 params.put("isModerator", new String[] {"true"});
395
         }
396

    
397
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
398
                                 "-//W3C//HTML//EN", qformat, out, params,
399
                                 sessionid);
400
         long transformRunTime = System.currentTimeMillis() - startHTMLTransform;
401
         
402
         transferWarnLimit = Long.parseLong(PropertyService.getProperty("dbquery.transformTimeWarnLimit"));
403
         
404
         if (transformRunTime > transferWarnLimit) {
405
         	logMetacat.warn("DBQuery.findDocuments - The time to transfrom resultset from xml to html format is "
406
                  		                             + transformRunTime);
407
         }
408
          MetacatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Transfrom xml to html  "
409
                             + transformRunTime);
410
          MetacatUtil.writeDebugToDelimiteredFile(" " + transformRunTime, false);
411
        }
412
        catch(Exception e)
413
        {
414
         logMetacat.error("DBQuery.findDocuments - Error in MetaCatServlet.transformResultset:"
415
                                +e.getMessage());
416
         }
417

    
418
      }//else
419

    
420
  }
421
  
422
  /**
423
   * Transforms a hashtable of documents to an xml or html result and sent
424
   * the content to outputstream. Keep going untill hastable is empty. stop it.
425
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
426
   * to xmlquery String
427
   * @param xmlquery
428
   * @param qspec
429
   * @param out
430
   * @param user
431
   * @param groups
432
   * @param useXMLIndex
433
   * @param sessionid
434
   * @return
435
   */
436
    public StringBuffer createResultDocument(String xmlquery,
437
                                              QuerySpecification qspec,
438
                                              PrintWriter out,
439
                                              String user, String[] groups,
440
                                              boolean useXMLIndex)
441
    {
442
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"");
443
    }
444

    
445
  /*
446
   * Transforms a hashtable of documents to an xml or html result and sent
447
   * the content to outputstream. Keep going untill hastable is empty. stop it.
448
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
449
   * to xmlquery String
450
   */
451
  public StringBuffer createResultDocument(String xmlquery,
452
                                            QuerySpecification qspec,
453
                                            PrintWriter out,
454
                                            String user, String[] groups,
455
                                            boolean useXMLIndex, int pagesize,
456
                                            int pagestart, String sessionid)
457
  {
458
    DBConnection dbconn = null;
459
    int serialNumber = -1;
460
    StringBuffer resultset = new StringBuffer();
461

    
462
    //try to get the cached version first    
463
    // Hashtable sessionHash = MetaCatServlet.getSessionHash();
464
    // HttpSession sess = (HttpSession)sessionHash.get(sessionid);
465

    
466
    
467
    resultset.append("<?xml version=\"1.0\"?>\n");
468
    resultset.append("<resultset>\n");
469
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
470
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
471
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
472
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
473

    
474
    resultset.append("  <query>" + xmlquery + "</query>");
475
    //send out a new query
476
    if (out != null)
477
    {
478
      out.println(resultset.toString());
479
    }
480
    if (qspec != null)
481
    {
482
      try
483
      {
484

    
485
        //checkout the dbconnection
486
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
487
        serialNumber = dbconn.getCheckOutSerialNumber();
488

    
489
        //print out the search result
490
        // search the doc list
491
        Vector givenDocids = new Vector();
492
        StringBuffer resultContent = new StringBuffer();
493
        if (docidOverride == null || docidOverride.size() == 0)
494
        {
495
        	logMetacat.debug("DBQuery.createResultDocument - Not in map query");
496
        	resultContent = findResultDoclist(qspec, out, user, groups,
497
                    dbconn, useXMLIndex, pagesize, pagestart, 
498
                    sessionid, givenDocids);
499
        }
500
        else
501
        {
502
        	logMetacat.debug("DBQuery.createResultDocument - In map query");
503
        	// since docid can be too long to be handled. We divide it into several parts
504
        	for (int i= 0; i<docidOverride.size(); i++)
505
        	{
506
        	   logMetacat.debug("DBQuery.createResultDocument - in loop===== "+i);
507
        		givenDocids = (Vector)docidOverride.elementAt(i);
508
        		StringBuffer subset = findResultDoclist(qspec, out, user, groups,
509
                        dbconn, useXMLIndex, pagesize, pagestart, 
510
                        sessionid, givenDocids);
511
        		resultContent.append(subset);
512
        	}
513
        }
514
           
515
        resultset.append(resultContent);
516
      } //try
517
      catch (IOException ioe)
518
      {
519
        logMetacat.error("DBQuery.createResultDocument - IO error: " + ioe.getMessage());
520
      }
521
      catch (SQLException e)
522
      {
523
        logMetacat.error("DBQuery.createResultDocument - SQL Error: " + e.getMessage());
524
      }
525
      catch (Exception ee)
526
      {
527
        logMetacat.error("DBQuery.createResultDocument - General exception: "
528
                                 + ee.getMessage());
529
        ee.printStackTrace();
530
      }
531
      finally
532
      {
533
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
534
      } //finally
535
    }//if
536
    String closeRestultset = "</resultset>";
537
    resultset.append(closeRestultset);
538
    if (out != null)
539
    {
540
      out.println(closeRestultset);
541
    }
542

    
543
    //default to returning the whole resultset
544
    return resultset;
545
  }//createResultDocuments
546

    
547
    /*
548
     * Find the doc list which match the query
549
     */
550
    private StringBuffer findResultDoclist(QuerySpecification qspec,
551
                                      PrintWriter out,
552
                                      String user, String[]groups,
553
                                      DBConnection dbconn, boolean useXMLIndex,
554
                                      int pagesize, int pagestart, String sessionid, Vector givenDocids)
555
                                      throws Exception
556
    {
557
      StringBuffer resultsetBuffer = new StringBuffer();
558
      String query = null;
559
      int count = 0;
560
      int index = 0;
561
      ResultDocumentSet docListResult = new ResultDocumentSet();
562
      PreparedStatement pstmt = null;
563
      String docid = null;
564
      String docname = null;
565
      String doctype = null;
566
      String createDate = null;
567
      String updateDate = null;
568
      StringBuffer document = null;
569
      boolean lastpage = false;
570
      int rev = 0;
571
      double startTime = 0;
572
      int offset = 1;
573
      long startSelectionTime = System.currentTimeMillis();
574
      ResultSet rs = null;
575
           
576
   
577
      // this is a hack for offset. in postgresql 7, if the returned docid list is too long,
578
      //the extend query which base on the docid will be too long to be run. So we 
579
      // have to cut them into different parts. Page query don't need it somehow.
580
      if (out == null)
581
      {
582
        // for html page, we put everything into one page
583
        offset =
584
            (new Integer(PropertyService.getProperty("database.webResultsetSize"))).intValue();
585
      }
586
      else
587
      {
588
          offset =
589
              (new Integer(PropertyService.getProperty("database.appResultsetSize"))).intValue();
590
      }
591

    
592
      /*
593
       * Check the docidOverride Vector
594
       * if defined, we bypass the qspec.printSQL() method
595
       * and contruct a simpler query based on a 
596
       * list of docids rather than a bunch of subselects
597
       */
598
      if ( givenDocids == null || givenDocids.size() == 0 ) {
599
          query = qspec.printSQL(useXMLIndex);
600
      } else {
601
          logMetacat.info("DBQuery.findResultDoclist - docid override " + givenDocids.size());
602
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
603
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
604
          for (int i = 0; i < givenDocids.size(); i++) {  
605
              queryBuffer.append("'");
606
              queryBuffer.append( (String)givenDocids.elementAt(i) );
607
              queryBuffer.append("',");
608
          }
609
          // empty string hack 
610
          queryBuffer.append( "'') " );
611
          query = queryBuffer.toString();
612
      } 
613
      String ownerQuery = getOwnerQuery(user);
614
      //logMetacat.debug("query: " + query);
615
      logMetacat.debug("DBQuery.findResultDoclist - owner query: " + ownerQuery);
616
      // if query is not the owner query, we need to check the permission
617
      // otherwise we don't need (owner has all permission by default)
618
      if (!query.equals(ownerQuery))
619
      {
620
        // set user name and group
621
        qspec.setUserName(user);
622
        qspec.setGroup(groups);
623
        // Get access query
624
        String accessQuery = qspec.getAccessQuery();
625
        if(!query.endsWith("WHERE")){
626
            query = query + accessQuery;
627
        } else {
628
            query = query + accessQuery.substring(4, accessQuery.length());
629
        }
630
        
631
      }
632
      logMetacat.debug("DBQuery.findResultDoclist - final selection query: " + query);
633
      String selectionAndExtendedQuery = null;
634
      // we only get cache for public
635
      if (user != null && user.equalsIgnoreCase("public") 
636
     		 && pagesize == 0 && PropertyService.getProperty("database.queryCacheOn").equals("true"))
637
      {
638
    	  selectionAndExtendedQuery = query +qspec.getReturnDocList()+qspec.getReturnFieldList();
639
   	      String cachedResult = getResultXMLFromCache(selectionAndExtendedQuery);
640
   	      logMetacat.debug("DBQuery.findResultDoclist - The key of query cache is " + selectionAndExtendedQuery);
641
   	      //System.out.println("==========the string from cache is "+cachedResult);
642
   	      if (cachedResult != null)
643
   	      {
644
   	    	logMetacat.info("DBQuery.findResultDoclist - result from cache !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
645
   	    	 if (out != null)
646
   	         {
647
   	             out.println(cachedResult);
648
   	         }
649
   	    	 resultsetBuffer.append(cachedResult);
650
   	    	 return resultsetBuffer;
651
   	      }
652
      }
653
      
654
      startTime = System.currentTimeMillis() / 1000;
655
      pstmt = dbconn.prepareStatement(query);
656
      rs = pstmt.executeQuery();
657

    
658
      double queryExecuteTime = System.currentTimeMillis() / 1000;
659
      logMetacat.debug("DBQuery.findResultDoclist - Time to execute select docid query is "
660
                    + (queryExecuteTime - startTime));
661
      MetacatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
662
              + (queryExecuteTime - startTime));
663
      MetacatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
664

    
665
      boolean tableHasRows = rs.next();
666
      
667
      if(pagesize == 0)
668
      { //this makes sure we get all results if there is no paging
669
        pagesize = NONPAGESIZE;
670
        pagestart = NONPAGESIZE;
671
      } 
672
      
673
      int currentIndex = 0;
674
      while (tableHasRows)
675
      {
676
        logMetacat.debug("DBQuery.findResultDoclist - getting result: " + currentIndex);
677
        docid = rs.getString(1).trim();
678
        logMetacat.debug("DBQuery.findResultDoclist -  processing: " + docid);
679
        docname = rs.getString(2);
680
        doctype = rs.getString(3);
681
        logMetacat.debug("DBQuery.findResultDoclist - processing: " + doctype);
682
        createDate = rs.getString(4);
683
        updateDate = rs.getString(5);
684
        rev = rs.getInt(6);
685
        
686
         Vector returndocVec = qspec.getReturnDocList();
687
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
688
        {
689
          logMetacat.debug("DBQuery.findResultDoclist - NOT Back tracing now...");
690
           document = new StringBuffer();
691

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

    
786
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
787
     if (out != null)
788
     {
789
         out.println("\n<lastpage>" + lastpage + "</lastpage>\n");
790
     }
791
     
792
     // now we only cached none-paged query and user is public
793
     if (user != null && user.equalsIgnoreCase("public") 
794
    		 && pagesize == NONPAGESIZE && PropertyService.getProperty("database.queryCacheOn").equals("true"))
795
     {
796
       //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
797
  	   storeQueryResultIntoCache(selectionAndExtendedQuery, resultsetBuffer.toString());
798
     }
799
          
800
     return resultsetBuffer;
801
    }//findReturnDoclist
802

    
803

    
804
    /*
805
     * Send completed search hashtable(part of reulst)to output stream
806
     * and buffer into a buffer stream
807
     */
808
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
809
                                           StringBuffer resultset,
810
                                           PrintWriter out, ResultDocumentSet partOfDoclist,
811
                                           String user, String[]groups,
812
                                       DBConnection dbconn, boolean useXMLIndex)
813
                                       throws Exception
814
   {
815
     double startReturnFieldTime = System.currentTimeMillis();
816
     // check if there is a record in xml_returnfield
817
     // and get the returnfield_id and usage count
818
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
819
     boolean enterRecords = false;
820

    
821
     // get value of database.xmlReturnfieldCount
822
     int count = (new Integer(PropertyService
823
                            .getProperty("database.xmlReturnfieldCount")))
824
                            .intValue();
825

    
826
     // set enterRecords to true if usage_count is more than the offset
827
     // specified in metacat.properties
828
     if(usage_count > count){
829
         enterRecords = true;
830
     }
831

    
832
     if(returnfield_id < 0){
833
         logMetacat.warn("DBQuery.handleSubsetResult - Error in getting returnfield id from"
834
                                  + "xml_returnfield table");
835
         enterRecords = false;
836
     }
837

    
838
     // get the hashtable containing the docids that already in the
839
     // xml_queryresult table
840
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist before"
841
                             + " docidsInQueryresultTable(): "
842
                             + partOfDoclist.size());
843
     long startGetReturnValueFromQueryresultable = System.currentTimeMillis();
844
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
845
                                                        partOfDoclist, dbconn);
846

    
847
     // remove the keys in queryresultDocList from partOfDoclist
848
     Enumeration _keys = queryresultDocList.keys();
849
     while (_keys.hasMoreElements()){
850
         partOfDoclist.remove((String)_keys.nextElement());
851
     }
852
     
853
     long queryResultReturnValuetime = System.currentTimeMillis() - startGetReturnValueFromQueryresultable;
854
     long queryResultWarnLimit = 
855
    	 Long.parseLong(PropertyService.getProperty("dbquery.findQueryResultsTimeWarnLimit"));
856
     
857
     if (queryResultReturnValuetime > queryResultWarnLimit) {
858
    	 logMetacat.warn("DBQuery.handleSubsetResult - Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
859
    		 queryResultReturnValuetime);
860
     }
861
     MetacatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
862
    		 queryResultReturnValuetime);
863
     MetacatUtil.writeDebugToDelimiteredFile(" " + queryResultReturnValuetime,false);
864
     
865
     long startExtendedQuery = System.currentTimeMillis();
866
     // backup the keys-elements in partOfDoclist to check later
867
     // if the doc entry is indexed yet
868
     Hashtable partOfDoclistBackup = new Hashtable();
869
     Iterator itt = partOfDoclist.getDocids();
870
     while (itt.hasNext()){
871
       Object key = itt.next();
872
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
873
     }
874

    
875
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist after"
876
                             + " docidsInQueryresultTable(): "
877
                             + partOfDoclist.size());
878

    
879
     //add return fields for the documents in partOfDoclist
880
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
881
                                        dbconn, useXMLIndex);
882
     long extendedQueryRunTime = startExtendedQuery - System.currentTimeMillis();
883
     long extendedQueryWarnLimit = 
884
    	 Long.parseLong(PropertyService.getProperty("dbquery.extendedQueryRunTimeWarnLimit"));
885
  
886
     if (extendedQueryRunTime > extendedQueryWarnLimit) {
887
    	 logMetacat.warn("DBQuery.handleSubsetResult - Get fields from index and node table (Part2 in return fields) "
888
        		                                          + extendedQueryRunTime);
889
     }
890
     MetacatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
891
             + extendedQueryRunTime);
892
     MetacatUtil.writeDebugToDelimiteredFile(" "
893
             + extendedQueryRunTime, false);
894
     //add relationship part part docid list for the documents in partOfDocList
895
     //partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
896

    
897
     long startStoreReturnField = System.currentTimeMillis();
898
     Iterator keys = partOfDoclist.getDocids();
899
     String key = null;
900
     String element = null;
901
     String query = null;
902
     int offset = (new Integer(PropertyService
903
                               .getProperty("database.queryresultStringLength")))
904
                               .intValue();
905
     while (keys.hasNext())
906
     {
907
         key = (String) keys.next();
908
         element = (String)partOfDoclist.get(key);
909
         
910
	 // check if the enterRecords is true, elements is not null, element's
911
         // length is less than the limit of table column and if the document
912
         // has been indexed already
913
         if(enterRecords && element != null
914
		&& element.length() < offset
915
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
916
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
917
                 + "queryresult_string) VALUES (?, ?, ?)";
918

    
919
             PreparedStatement pstmt = null;
920
             pstmt = dbconn.prepareStatement(query);
921
             pstmt.setInt(1, returnfield_id);
922
             pstmt.setString(2, key);
923
             pstmt.setString(3, element);
924
            
925
             dbconn.increaseUsageCount(1);
926
             try
927
             {
928
            	 pstmt.execute();
929
             }
930
             catch(Exception e)
931
             {
932
            	 logMetacat.warn("DBQuery.handleSubsetResult - couldn't insert the element to xml_queryresult table "+e.getLocalizedMessage());
933
             }
934
             finally
935
             {
936
                pstmt.close();
937
             }
938
         }
939
        
940
         // A string with element
941
         String xmlElement = "  <document>" + element + "</document>";
942

    
943
         //send single element to output
944
         if (out != null)
945
         {
946
             out.println(xmlElement);
947
         }
948
         resultset.append(xmlElement);
949
     }//while
950
     
951
     double storeReturnFieldTime = System.currentTimeMillis() - startStoreReturnField;
952
     long storeReturnFieldWarnLimit = 
953
    	 Long.parseLong(PropertyService.getProperty("dbquery.storeReturnFieldTimeWarnLimit"));
954

    
955
     if (storeReturnFieldTime > storeReturnFieldWarnLimit) {
956
    	 logMetacat.warn("DBQuery.handleSubsetResult - Time to store new return fields into xml_queryresult table (Part4 in return fields) "
957
                   + storeReturnFieldTime);
958
     }
959
     MetacatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
960
             + storeReturnFieldTime);
961
     MetacatUtil.writeDebugToDelimiteredFile(" " + storeReturnFieldTime, false);
962
     
963
     Enumeration keysE = queryresultDocList.keys();
964
     while (keysE.hasMoreElements())
965
     {
966
         key = (String) keysE.nextElement();
967
         element = (String)queryresultDocList.get(key);
968
         // A string with element
969
         String xmlElement = "  <document>" + element + "</document>";
970
         //send single element to output
971
         if (out != null)
972
         {
973
             out.println(xmlElement);
974
         }
975
         resultset.append(xmlElement);
976
     }//while
977
     double returnFieldTime = System.currentTimeMillis() - startReturnFieldTime;
978
     long totalReturnFieldWarnLimit = 
979
    	 Long.parseLong(PropertyService.getProperty("dbquery.totalReturnFieldTimeWarnLimit"));
980

    
981
     if (returnFieldTime > totalReturnFieldWarnLimit) {
982
    	 logMetacat.warn("DBQuery.handleSubsetResult - Total time to get return fields is: "
983
                           + returnFieldTime);
984
     }
985
     MetacatUtil.writeDebugToFile("DBQuery.handleSubsetResult - ---------------------------------------------------------------------------------------------------------------"+
986
    		 "Total to get return fields  " + returnFieldTime);
987
     MetacatUtil.writeDebugToDelimiteredFile("DBQuery.handleSubsetResult - "+ returnFieldTime, false);
988
     return resultset;
989
 }
990

    
991
   /**
992
    * Get the docids already in xml_queryresult table and corresponding
993
    * queryresultstring as a hashtable
994
    */
995
   private Hashtable docidsInQueryresultTable(int returnfield_id,
996
                                              ResultDocumentSet partOfDoclist,
997
                                              DBConnection dbconn){
998

    
999
         Hashtable returnValue = new Hashtable();
1000
         PreparedStatement pstmt = null;
1001
         ResultSet rs = null;
1002

    
1003
         // get partOfDoclist as string for the query
1004
         Iterator keylist = partOfDoclist.getDocids();
1005
         StringBuffer doclist = new StringBuffer();
1006
         while (keylist.hasNext())
1007
         {
1008
             doclist.append("'");
1009
             doclist.append((String) keylist.next());
1010
             doclist.append("',");
1011
         }//while
1012

    
1013

    
1014
         if (doclist.length() > 0)
1015
         {
1016
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1017

    
1018
             // the query to find out docids from xml_queryresult
1019
             String query = "select docid, queryresult_string from "
1020
                          + "xml_queryresult where returnfield_id = " +
1021
                          returnfield_id +" and docid in ("+ doclist + ")";
1022
             logMetacat.info("DBQuery.docidsInQueryresultTable - Query to get docids from xml_queryresult:"
1023
                                      + query);
1024

    
1025
             try {
1026
                 // prepare and execute the query
1027
                 pstmt = dbconn.prepareStatement(query);
1028
                 dbconn.increaseUsageCount(1);
1029
                 pstmt.execute();
1030
                 rs = pstmt.getResultSet();
1031
                 boolean tableHasRows = rs.next();
1032
                 while (tableHasRows) {
1033
                     // store the returned results in the returnValue hashtable
1034
                     String key = rs.getString(1);
1035
                     String element = rs.getString(2);
1036

    
1037
                     if(element != null){
1038
                         returnValue.put(key, element);
1039
                     } else {
1040
                         logMetacat.info("DBQuery.docidsInQueryresultTable - Null elment found ("
1041
                         + "DBQuery.docidsInQueryresultTable)");
1042
                     }
1043
                     tableHasRows = rs.next();
1044
                 }
1045
                 rs.close();
1046
                 pstmt.close();
1047
             } catch (Exception e){
1048
                 logMetacat.error("DBQuery.docidsInQueryresultTable - Error getting docids from "
1049
                                          + "queryresult: " + e.getMessage());
1050
              }
1051
         }
1052
         return returnValue;
1053
     }
1054

    
1055

    
1056
   /**
1057
    * Method to get id from xml_returnfield table
1058
    * for a given query specification
1059
    */
1060
   private int returnfield_id;
1061
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1062
                                           DBConnection dbconn){
1063
       int id = -1;
1064
       int count = 1;
1065
       PreparedStatement pstmt = null;
1066
       ResultSet rs = null;
1067
       String returnfield = qspec.getSortedReturnFieldString();
1068

    
1069
       // query for finding the id from xml_returnfield
1070
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1071
            + "WHERE returnfield_string LIKE ?";
1072
       logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Query:" + query);
1073

    
1074
       try {
1075
           // prepare and run the query
1076
           pstmt = dbconn.prepareStatement(query);
1077
           pstmt.setString(1,returnfield);
1078
           dbconn.increaseUsageCount(1);
1079
           pstmt.execute();
1080
           rs = pstmt.getResultSet();
1081
           boolean tableHasRows = rs.next();
1082

    
1083
           // if record found then increase the usage count
1084
           // else insert a new record and get the id of the new record
1085
           if(tableHasRows){
1086
               // get the id
1087
               id = rs.getInt(1);
1088
               count = rs.getInt(2) + 1;
1089
               rs.close();
1090
               pstmt.close();
1091

    
1092
               // increase the usage count
1093
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1094
                   + "' WHERE returnfield_id ='"+ id +"'";
1095
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Update:"+ query);
1096

    
1097
               pstmt = dbconn.prepareStatement(query);
1098
               dbconn.increaseUsageCount(1);
1099
               pstmt.execute();
1100
               pstmt.close();
1101

    
1102
           } else {
1103
               rs.close();
1104
               pstmt.close();
1105

    
1106
               // insert a new record
1107
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1108
                   + "VALUES (?, '1')";
1109
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Insert:"+ query);
1110
               pstmt = dbconn.prepareStatement(query);
1111
               pstmt.setString(1, returnfield);
1112
               dbconn.increaseUsageCount(1);
1113
               pstmt.execute();
1114
               pstmt.close();
1115

    
1116
               // get the id of the new record
1117
               query = "SELECT returnfield_id FROM xml_returnfield "
1118
                   + "WHERE returnfield_string LIKE ?";
1119
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField query after Insert:" + query);
1120
               pstmt = dbconn.prepareStatement(query);
1121
               pstmt.setString(1, returnfield);
1122

    
1123
               dbconn.increaseUsageCount(1);
1124
               pstmt.execute();
1125
               rs = pstmt.getResultSet();
1126
               if(rs.next()){
1127
                   id = rs.getInt(1);
1128
               } else {
1129
                   id = -1;
1130
               }
1131
               rs.close();
1132
               pstmt.close();
1133
           }
1134

    
1135
       } catch (Exception e){
1136
           logMetacat.error("DBQuery.getXmlReturnfieldsTableId - Error getting id from xml_returnfield in "
1137
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1138
                                     + e.getMessage());
1139
           id = -1;
1140
       }
1141

    
1142
       returnfield_id = id;
1143
       return count;
1144
   }
1145

    
1146

    
1147
    /*
1148
     * A method to add return field to return doclist hash table
1149
     */
1150
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1151
                                      QuerySpecification qspec,
1152
                                      String user, String[]groups,
1153
                                      DBConnection dbconn, boolean useXMLIndex )
1154
                                      throws Exception
1155
    {
1156
      PreparedStatement pstmt = null;
1157
      ResultSet rs = null;
1158
      String docid = null;
1159
      String fieldname = null;
1160
      String fieldtype = null;
1161
      String fielddata = null;
1162
      String relation = null;
1163

    
1164
      if (qspec.containsExtendedSQL())
1165
      {
1166
        qspec.setUserName(user);
1167
        qspec.setGroup(groups);
1168
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1169
        Vector results = new Vector();
1170
        Iterator keylist = docListResult.getDocids();
1171
        StringBuffer doclist = new StringBuffer();
1172
        Vector parentidList = new Vector();
1173
        Hashtable returnFieldValue = new Hashtable();
1174
        while (keylist.hasNext())
1175
        {
1176
          doclist.append("'");
1177
          doclist.append((String) keylist.next());
1178
          doclist.append("',");
1179
        }
1180
        if (doclist.length() > 0)
1181
        {
1182
          Hashtable controlPairs = new Hashtable();
1183
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1184
          boolean tableHasRows = false;
1185
        
1186

    
1187
           String extendedQuery =
1188
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex);
1189
           logMetacat.info("DBQuery.addReturnfield - Extended query: " + extendedQuery);
1190

    
1191
           if(extendedQuery != null){
1192
//        	   long extendedQueryStart = System.currentTimeMillis();
1193
               pstmt = dbconn.prepareStatement(extendedQuery);
1194
               //increase dbconnection usage count
1195
               dbconn.increaseUsageCount(1);
1196
               pstmt.execute();
1197
               rs = pstmt.getResultSet();
1198
//               MetacatUtil.writeDebugToDelimiteredFile(" "+ (extendedQueryEnd - extendedQueryStart), false);
1199
               tableHasRows = rs.next();
1200
               while (tableHasRows) {
1201
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1202
                   docid = rs.getString(1).trim();
1203
                   fieldname = rs.getString(2);
1204
                   fielddata = rs.getString(3);
1205
                   fielddata = MetacatUtil.normalize(fielddata);
1206
                   String parentId = rs.getString(4);
1207
                   fieldtype = rs.getString(5);
1208
                   StringBuffer value = new StringBuffer();
1209

    
1210
                   //handle case when usexmlindex is true differently
1211
                   //at one point merging the nodedata (for large text elements) was 
1212
                   //deemed unnecessary - but now it is needed.  but not for attribute nodes
1213
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1214
                	   //merge node data only for non-ATTRIBUTEs
1215
                	   if (fieldtype != null && !fieldtype.equals("ATTRIBUTE")) {
1216
	                	   //try merging the data
1217
	                	   ReturnFieldValue existingRFV =
1218
	                		   getArrayValue(parentidList, parentId);
1219
	                	   if (existingRFV != null) {
1220
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1221
	                	   }
1222
                	   }
1223
                       value.append("<param name=\"");
1224
                       value.append(fieldname);
1225
                       value.append("\">");
1226
                       value.append(fielddata);
1227
                       value.append("</param>");
1228
                       //set returnvalue
1229
                       returnValue.setDocid(docid);
1230
                       returnValue.setFieldValue(fielddata);
1231
                       returnValue.setFieldType(fieldtype);
1232
                       returnValue.setXMLFieldValue(value.toString());
1233
                       // Store it in hastable
1234
                       putInArray(parentidList, parentId, returnValue);
1235
                   }
1236
                   else {
1237
                       // need to merge nodedata if they have same parent id and
1238
                       // node type is text
1239
                       fielddata = (String) ( (ReturnFieldValue)
1240
                                             getArrayValue(
1241
                           parentidList, parentId)).getFieldValue()
1242
                           + fielddata;
1243
                       value.append("<param name=\"");
1244
                       value.append(fieldname);
1245
                       value.append("\">");
1246
                       value.append(fielddata);
1247
                       value.append("</param>");
1248
                       returnValue.setDocid(docid);
1249
                       returnValue.setFieldValue(fielddata);
1250
                       returnValue.setFieldType(fieldtype);
1251
                       returnValue.setXMLFieldValue(value.toString());
1252
                       // remove the old return value from paretnidList
1253
                       parentidList.remove(parentId);
1254
                       // store the new return value in parentidlit
1255
                       putInArray(parentidList, parentId, returnValue);
1256
                   }
1257
                   tableHasRows = rs.next();
1258
               } //while
1259
               rs.close();
1260
               pstmt.close();
1261

    
1262
               // put the merger node data info into doclistReult
1263
               Enumeration xmlFieldValue = (getElements(parentidList)).
1264
                   elements();
1265
               while (xmlFieldValue.hasMoreElements()) {
1266
                   ReturnFieldValue object =
1267
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1268
                   docid = object.getDocid();
1269
                   if (docListResult.containsDocid(docid)) {
1270
                       String removedelement = (String) docListResult.
1271
                           remove(docid);
1272
                       docListResult.
1273
                           addResultDocument(new ResultDocument(docid,
1274
                               removedelement + object.getXMLFieldValue()));
1275
                   }
1276
                   else {
1277
                       docListResult.addResultDocument(
1278
                         new ResultDocument(docid, object.getXMLFieldValue()));
1279
                   }
1280
               } //while
1281
//               double docListResultEnd = System.currentTimeMillis() / 1000;
1282
//               logMetacat.warn(
1283
//                   "Time to prepare ResultDocumentSet after"
1284
//                   + " execute extended query: "
1285
//                   + (docListResultEnd - extendedQueryEnd));
1286
           }
1287

    
1288
         
1289
           
1290
           
1291
       }//if doclist lenght is great than zero
1292

    
1293
     }//if has extended query
1294

    
1295
      return docListResult;
1296
    }//addReturnfield
1297

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

    
1372

    
1373
    /*
1374
     * A method to search if Vector contains a particular key string
1375
     */
1376
    private boolean containsKey(Vector parentidList, String parentId)
1377
    {
1378

    
1379
        Vector tempVector = null;
1380

    
1381
        for (int count = 0; count < parentidList.size(); count++) {
1382
            tempVector = (Vector) parentidList.get(count);
1383
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1384
        }
1385
        return false;
1386
    }
1387
    
1388
    /*
1389
     * A method to put key and value in Vector
1390
     */
1391
    private void putInArray(Vector parentidList, String key,
1392
            ReturnFieldValue value)
1393
    {
1394

    
1395
        Vector tempVector = null;
1396
        //only filter if the field type is NOT an attribute (say, for text)
1397
        String fieldType = value.getFieldType();
1398
        if (fieldType != null && !fieldType.equals("ATTRIBUTE")) {
1399
        
1400
	        for (int count = 0; count < parentidList.size(); count++) {
1401
	            tempVector = (Vector) parentidList.get(count);
1402
	
1403
	            if (key.compareTo((String) tempVector.get(0)) == 0) {
1404
	                tempVector.remove(1);
1405
	                tempVector.add(1, value);
1406
	                return;
1407
	            }
1408
	        }
1409
        }
1410

    
1411
        tempVector = new Vector();
1412
        tempVector.add(0, key);
1413
        tempVector.add(1, value);
1414
        parentidList.add(tempVector);
1415
        return;
1416
    }
1417

    
1418
    /*
1419
     * A method to get value in Vector given a key
1420
     */
1421
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1422
    {
1423

    
1424
        Vector tempVector = null;
1425

    
1426
        for (int count = 0; count < parentidList.size(); count++) {
1427
            tempVector = (Vector) parentidList.get(count);
1428

    
1429
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1430
                    .get(1); }
1431
        }
1432
        return null;
1433
    }
1434

    
1435
    /*
1436
     * A method to get enumeration of all values in Vector
1437
     */
1438
    private Vector getElements(Vector parentidList)
1439
    {
1440
        Vector enumVector = new Vector();
1441
        Vector tempVector = null;
1442

    
1443
        for (int count = 0; count < parentidList.size(); count++) {
1444
            tempVector = (Vector) parentidList.get(count);
1445

    
1446
            enumVector.add(tempVector.get(1));
1447
        }
1448
        return enumVector;
1449
    }
1450

    
1451
  
1452

    
1453
    /*
1454
     * A method to create a query to get owner's docid list
1455
     */
1456
    private String getOwnerQuery(String owner)
1457
    {
1458
        if (owner != null) {
1459
            owner = owner.toLowerCase();
1460
        }
1461
        StringBuffer self = new StringBuffer();
1462

    
1463
        self.append("SELECT docid,docname,doctype,");
1464
        self.append("date_created, date_updated, rev ");
1465
        self.append("FROM xml_documents WHERE docid IN (");
1466
        self.append("(");
1467
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1468
        self.append("nodedata LIKE '%%%' ");
1469
        self.append(") \n");
1470
        self.append(") ");
1471
        self.append(" AND (");
1472
        self.append(" lower(user_owner) = '" + owner + "'");
1473
        self.append(") ");
1474
        return self.toString();
1475
    }
1476

    
1477
    /**
1478
     * format a structured query as an XML document that conforms to the
1479
     * pathquery.dtd and is appropriate for submission to the DBQuery
1480
     * structured query engine
1481
     *
1482
     * @param params The list of parameters that should be included in the
1483
     *            query
1484
     */
1485
    public static String createSQuery(Hashtable params) throws PropertyNotFoundException
1486
    {
1487
        StringBuffer query = new StringBuffer();
1488
        Enumeration elements;
1489
        Enumeration keys;
1490
        String filterDoctype = null;
1491
        String casesensitive = null;
1492
        String searchmode = null;
1493
        Object nextkey;
1494
        Object nextelement;
1495
        //add the xml headers
1496
        query.append("<?xml version=\"1.0\"?>\n");
1497
        query.append("<pathquery version=\"1.2\">\n");
1498

    
1499

    
1500

    
1501
        if (params.containsKey("meta_file_id")) {
1502
            query.append("<meta_file_id>");
1503
            query.append(((String[]) params.get("meta_file_id"))[0]);
1504
            query.append("</meta_file_id>");
1505
        }
1506

    
1507
        if (params.containsKey("returndoctype")) {
1508
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1509
            for (int i = 0; i < returnDoctypes.length; i++) {
1510
                String doctype = (String) returnDoctypes[i];
1511

    
1512
                if (!doctype.equals("any") && !doctype.equals("ANY")
1513
                        && !doctype.equals("")) {
1514
                    query.append("<returndoctype>").append(doctype);
1515
                    query.append("</returndoctype>");
1516
                }
1517
            }
1518
        }
1519

    
1520
        if (params.containsKey("filterdoctype")) {
1521
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1522
            for (int i = 0; i < filterDoctypes.length; i++) {
1523
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1524
                query.append("</filterdoctype>");
1525
            }
1526
        }
1527

    
1528
        if (params.containsKey("returnfield")) {
1529
            String[] returnfield = ((String[]) params.get("returnfield"));
1530
            for (int i = 0; i < returnfield.length; i++) {
1531
                query.append("<returnfield>").append(returnfield[i]);
1532
                query.append("</returnfield>");
1533
            }
1534
        }
1535

    
1536
        if (params.containsKey("owner")) {
1537
            String[] owner = ((String[]) params.get("owner"));
1538
            for (int i = 0; i < owner.length; i++) {
1539
                query.append("<owner>").append(owner[i]);
1540
                query.append("</owner>");
1541
            }
1542
        }
1543

    
1544
        if (params.containsKey("site")) {
1545
            String[] site = ((String[]) params.get("site"));
1546
            for (int i = 0; i < site.length; i++) {
1547
                query.append("<site>").append(site[i]);
1548
                query.append("</site>");
1549
            }
1550
        }
1551

    
1552
        //allows the dynamic switching of boolean operators
1553
        if (params.containsKey("operator")) {
1554
            query.append("<querygroup operator=\""
1555
                    + ((String[]) params.get("operator"))[0] + "\">");
1556
        } else { //the default operator is UNION
1557
            query.append("<querygroup operator=\"UNION\">");
1558
        }
1559

    
1560
        if (params.containsKey("casesensitive")) {
1561
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1562
        } else {
1563
            casesensitive = "false";
1564
        }
1565

    
1566
        if (params.containsKey("searchmode")) {
1567
            searchmode = ((String[]) params.get("searchmode"))[0];
1568
        } else {
1569
            searchmode = "contains";
1570
        }
1571

    
1572
        //anyfield is a special case because it does a
1573
        //free text search. It does not have a <pathexpr>
1574
        //tag. This allows for a free text search within the structured
1575
        //query. This is useful if the INTERSECT operator is used.
1576
        if (params.containsKey("anyfield")) {
1577
            String[] anyfield = ((String[]) params.get("anyfield"));
1578
            //allow for more than one value for anyfield
1579
            for (int i = 0; i < anyfield.length; i++) {
1580
                if (anyfield[i] != null && !anyfield[i].equals("")) {
1581
                    query.append("<queryterm casesensitive=\"" + casesensitive
1582
                            + "\" " + "searchmode=\"" + searchmode
1583
                            + "\"><value>" + anyfield[i]
1584
                            + "</value></queryterm>");
1585
                }
1586
            }
1587
        }
1588

    
1589
        //this while loop finds the rest of the parameters
1590
        //and attempts to query for the field specified
1591
        //by the parameter.
1592
        elements = params.elements();
1593
        keys = params.keys();
1594
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1595
            nextkey = keys.nextElement();
1596
            nextelement = elements.nextElement();
1597

    
1598
            //make sure we aren't querying for any of these
1599
            //parameters since the are already in the query
1600
            //in one form or another.
1601
            Vector ignoredParams = new Vector();
1602
            ignoredParams.add("returndoctype");
1603
            ignoredParams.add("filterdoctype");
1604
            ignoredParams.add("action");
1605
            ignoredParams.add("qformat");
1606
            ignoredParams.add("anyfield");
1607
            ignoredParams.add("returnfield");
1608
            ignoredParams.add("owner");
1609
            ignoredParams.add("site");
1610
            ignoredParams.add("operator");
1611
            ignoredParams.add("sessionid");
1612
            ignoredParams.add("pagesize");
1613
            ignoredParams.add("pagestart");
1614
            ignoredParams.add("searchmode");
1615

    
1616
            // Also ignore parameters listed in the properties file
1617
            // so that they can be passed through to stylesheets
1618
            String paramsToIgnore = PropertyService
1619
                    .getProperty("database.queryignoredparams");
1620
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1621
            while (st.hasMoreTokens()) {
1622
                ignoredParams.add(st.nextToken());
1623
            }
1624
            if (!ignoredParams.contains(nextkey.toString())) {
1625
                //allow for more than value per field name
1626
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1627
                    if (!((String[]) nextelement)[i].equals("")) {
1628
                        query.append("<queryterm casesensitive=\""
1629
                                + casesensitive + "\" " + "searchmode=\""
1630
                                + searchmode + "\">" + "<value>" +
1631
                                //add the query value
1632
                                ((String[]) nextelement)[i]
1633
                                + "</value><pathexpr>" +
1634
                                //add the path to query by
1635
                                nextkey.toString() + "</pathexpr></queryterm>");
1636
                    }
1637
                }
1638
            }
1639
        }
1640
        query.append("</querygroup></pathquery>");
1641
        //append on the end of the xml and return the result as a string
1642
        return query.toString();
1643
    }
1644

    
1645
    /**
1646
     * format a simple free-text value query as an XML document that conforms
1647
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1648
     * structured query engine
1649
     *
1650
     * @param value the text string to search for in the xml catalog
1651
     * @param doctype the type of documents to include in the result set -- use
1652
     *            "any" or "ANY" for unfiltered result sets
1653
     */
1654
    public static String createQuery(String value, String doctype)
1655
    {
1656
        StringBuffer xmlquery = new StringBuffer();
1657
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1658
        xmlquery.append("<pathquery version=\"1.0\">");
1659

    
1660
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1661
            xmlquery.append("<returndoctype>");
1662
            xmlquery.append(doctype).append("</returndoctype>");
1663
        }
1664

    
1665
        xmlquery.append("<querygroup operator=\"UNION\">");
1666
        //chad added - 8/14
1667
        //the if statement allows a query to gracefully handle a null
1668
        //query. Without this if a nullpointerException is thrown.
1669
        if (!value.equals("")) {
1670
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1671
            xmlquery.append("searchmode=\"contains\">");
1672
            xmlquery.append("<value>").append(value).append("</value>");
1673
            xmlquery.append("</queryterm>");
1674
        }
1675
        xmlquery.append("</querygroup>");
1676
        xmlquery.append("</pathquery>");
1677

    
1678
        return (xmlquery.toString());
1679
    }
1680

    
1681
    /**
1682
     * format a simple free-text value query as an XML document that conforms
1683
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1684
     * structured query engine
1685
     *
1686
     * @param value the text string to search for in the xml catalog
1687
     */
1688
    public static String createQuery(String value)
1689
    {
1690
        return createQuery(value, "any");
1691
    }
1692

    
1693
    /**
1694
     * Check for "READ" permission on @docid for @user and/or @group from DB
1695
     * connection
1696
     */
1697
    private boolean hasPermission(String user, String[] groups, String docid)
1698
            throws SQLException, Exception
1699
    {
1700
        // Check for READ permission on @docid for @user and/or @groups
1701
        PermissionController controller = new PermissionController(docid);
1702
        return controller.hasPermission(user, groups,
1703
                AccessControlInterface.READSTRING);
1704
    }
1705

    
1706
    /**
1707
     * Get all docIds list for a data packadge
1708
     *
1709
     * @param dataPackageDocid, the string in docId field of xml_relation table
1710
     */
1711
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1712
    {
1713
        DBConnection dbConn = null;
1714
        int serialNumber = -1;
1715
        Vector docIdList = new Vector();//return value
1716
        PreparedStatement pStmt = null;
1717
        ResultSet rs = null;
1718
        String docIdInSubjectField = null;
1719
        String docIdInObjectField = null;
1720

    
1721
        // Check the parameter
1722
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1723

    
1724
        //the query stirng
1725
        String query = "SELECT subject, object from xml_relation where docId = ?";
1726
        try {
1727
            dbConn = DBConnectionPool
1728
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1729
            serialNumber = dbConn.getCheckOutSerialNumber();
1730
            pStmt = dbConn.prepareStatement(query);
1731
            //bind the value to query
1732
            pStmt.setString(1, dataPackageDocid);
1733

    
1734
            //excute the query
1735
            pStmt.execute();
1736
            //get the result set
1737
            rs = pStmt.getResultSet();
1738
            //process the result
1739
            while (rs.next()) {
1740
                //In order to get the whole docIds in a data packadge,
1741
                //we need to put the docIds of subject and object field in
1742
                // xml_relation
1743
                //into the return vector
1744
                docIdInSubjectField = rs.getString(1);//the result docId in
1745
                                                      // subject field
1746
                docIdInObjectField = rs.getString(2);//the result docId in
1747
                                                     // object field
1748

    
1749
                //don't put the duplicate docId into the vector
1750
                if (!docIdList.contains(docIdInSubjectField)) {
1751
                    docIdList.add(docIdInSubjectField);
1752
                }
1753

    
1754
                //don't put the duplicate docId into the vector
1755
                if (!docIdList.contains(docIdInObjectField)) {
1756
                    docIdList.add(docIdInObjectField);
1757
                }
1758
            }//while
1759
            //close the pStmt
1760
            pStmt.close();
1761
        }//try
1762
        catch (SQLException e) {
1763
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - Error in getDocidListForDataPackage: "
1764
                    + e.getMessage());
1765
        }//catch
1766
        finally {
1767
            try {
1768
                pStmt.close();
1769
            }//try
1770
            catch (SQLException ee) {
1771
                logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - SQL Error: "
1772
                                + ee.getMessage());
1773
            }//catch
1774
            finally {
1775
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1776
            }//fianlly
1777
        }//finally
1778
        return docIdList;
1779
    }//getCurrentDocidListForDataPackadge()
1780

    
1781
    /**
1782
     * Get all docIds list for a data packadge
1783
     *
1784
     * @param dataPackageDocid, the string in docId field of xml_relation table
1785
     */
1786
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1787
    {
1788

    
1789
        Vector docIdList = new Vector();//return value
1790
        Vector tripleList = null;
1791
        String xml = null;
1792

    
1793
        // Check the parameter
1794
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1795

    
1796
        try {
1797
            //initial a documentImpl object
1798
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1799
            //transfer to documentImpl object to string
1800
            xml = packageDocument.toString();
1801

    
1802
            //create a tripcollection object
1803
            TripleCollection tripleForPackage = new TripleCollection(
1804
                    new StringReader(xml));
1805
            //get the vetor of triples
1806
            tripleList = tripleForPackage.getCollection();
1807

    
1808
            for (int i = 0; i < tripleList.size(); i++) {
1809
                //put subject docid into docIdlist without duplicate
1810
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1811
                        .getSubject())) {
1812
                    //put subject docid into docIdlist
1813
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1814
                }
1815
                //put object docid into docIdlist without duplicate
1816
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1817
                        .getObject())) {
1818
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1819
                }
1820
            }//for
1821
        }//try
1822
        catch (Exception e) {
1823
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - General error: "
1824
                    + e.getMessage());
1825
        }//catch
1826

    
1827
        // return result
1828
        return docIdList;
1829
    }//getDocidListForPackageInXMLRevisions()
1830

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

    
1883
    /**
1884
     * Check if the user has the permission to export data package
1885
     *
1886
     * @param conn, the connection
1887
     * @param docId, the id need to be checked
1888
     * @param user, the name of user
1889
     * @param groups, the user's group
1890
     */
1891
    private boolean hasPermissionToExportPackage(String docId, String user,
1892
            String[] groups) throws Exception
1893
    {
1894
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1895
        return DocumentImpl.hasReadPermission(user, groups, docId);
1896
    }
1897

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

    
1932
        }//try
1933
        catch (SQLException e) {
1934
            logMetacat.error("DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
1935
                            + e.getMessage());
1936
            throw e;
1937
        }//catch
1938
        finally {
1939
            try {
1940
                pStmt.close();
1941
            }//try
1942
            catch (SQLException ee) {
1943
                logMetacat.error(
1944
                        "DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
1945
                                + ee.getMessage());
1946
            }//catch
1947
            finally {
1948
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1949
            }//finally
1950
        }//finally
1951
        return rev;
1952
    }//getCurrentRevFromXMLDoumentsTable
1953

    
1954
    /**
1955
     * put a doc into a zip output stream
1956
     *
1957
     * @param docImpl, docmentImpl object which will be sent to zip output
1958
     *            stream
1959
     * @param zipOut, zip output stream which the docImpl will be put
1960
     * @param packageZipEntry, the zip entry name for whole package
1961
     */
1962
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1963
            ZipOutputStream zipOut, String packageZipEntry)
1964
            throws ClassNotFoundException, IOException, SQLException,
1965
            McdbException, Exception
1966
    {
1967
        byte[] byteString = null;
1968
        ZipEntry zEntry = null;
1969

    
1970
        byteString = docImpl.toString().getBytes();
1971
        //use docId as the zip entry's name
1972
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1973
                + docImpl.getDocID());
1974
        zEntry.setSize(byteString.length);
1975
        zipOut.putNextEntry(zEntry);
1976
        zipOut.write(byteString, 0, byteString.length);
1977
        zipOut.closeEntry();
1978

    
1979
    }//addDocToZipOutputStream()
1980

    
1981
    /**
1982
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1983
     * only inlcudes current version. If a DocumentImple object couldn't find
1984
     * for a docid, then the String of this docid was added to vetor rather
1985
     * than DocumentImple object.
1986
     *
1987
     * @param docIdList, a vetor hold a docid list for a data package. In
1988
     *            docid, there is not version number in it.
1989
     */
1990

    
1991
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1992
            throws McdbException, Exception
1993
    {
1994
        //Connection dbConn=null;
1995
        Vector documentImplList = new Vector();
1996
        int rev = 0;
1997

    
1998
        // Check the parameter
1999
        if (docIdList.isEmpty()) { return documentImplList; }//if
2000

    
2001
        //for every docid in vector
2002
        for (int i = 0; i < docIdList.size(); i++) {
2003
            try {
2004
                //get newest version for this docId
2005
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2006
                        .elementAt(i));
2007

    
2008
                // There is no record for this docId in xml_documents table
2009
                if (rev == -5) {
2010
                    // Rather than put DocumentImple object, put a String
2011
                    // Object(docid)
2012
                    // into the documentImplList
2013
                    documentImplList.add((String) docIdList.elementAt(i));
2014
                    // Skip other code
2015
                    continue;
2016
                }
2017

    
2018
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2019
                        + PropertyService.getProperty("document.accNumSeparator") + rev;
2020

    
2021
                //create new documentImpl object
2022
                DocumentImpl documentImplObject = new DocumentImpl(
2023
                        docidPlusVersion);
2024
                //add them to vector
2025
                documentImplList.add(documentImplObject);
2026
            }//try
2027
            catch (Exception e) {
2028
                logMetacat.error("DBQuery.getCurrentAllDocumentImpl - General error: "
2029
                        + e.getMessage());
2030
                // continue the for loop
2031
                continue;
2032
            }
2033
        }//for
2034
        return documentImplList;
2035
    }
2036

    
2037
    /**
2038
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2039
     * object couldn't find for a docid, then the String of this docid was
2040
     * added to vetor rather than DocumentImple object.
2041
     *
2042
     * @param docIdList, a vetor hold a docid list for a data package. In
2043
     *            docid, t here is version number in it.
2044
     */
2045
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2046
    {
2047
        //Connection dbConn=null;
2048
        Vector documentImplList = new Vector();
2049
        String siteCode = null;
2050
        String uniqueId = null;
2051
        int rev = 0;
2052

    
2053
        // Check the parameter
2054
        if (docIdList.isEmpty()) { return documentImplList; }//if
2055

    
2056
        //for every docid in vector
2057
        for (int i = 0; i < docIdList.size(); i++) {
2058

    
2059
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2060

    
2061
            try {
2062
                //create new documentImpl object
2063
                DocumentImpl documentImplObject = new DocumentImpl(
2064
                        docidPlusVersion);
2065
                //add them to vector
2066
                documentImplList.add(documentImplObject);
2067
            }//try
2068
            catch (McdbDocNotFoundException notFoundE) {
2069
                logMetacat.error("DBQuery.getOldVersionAllDocument - Error finding doc " 
2070
                		+ docidPlusVersion + " : " + notFoundE.getMessage());
2071
                // Rather than add a DocumentImple object into vetor, a String
2072
                // object
2073
                // - the doicd was added to the vector
2074
                documentImplList.add(docidPlusVersion);
2075
                // Continue the for loop
2076
                continue;
2077
            }//catch
2078
            catch (Exception e) {
2079
                logMetacat.error(
2080
                        "DBQuery.getOldVersionAllDocument - General error: "
2081
                                + e.getMessage());
2082
                // Continue the for loop
2083
                continue;
2084
            }//catch
2085

    
2086
        }//for
2087
        return documentImplList;
2088
    }//getOldVersionAllDocumentImple
2089

    
2090
    /**
2091
     * put a data file into a zip output stream
2092
     *
2093
     * @param docImpl, docmentImpl object which will be sent to zip output
2094
     *            stream
2095
     * @param zipOut, the zip output stream which the docImpl will be put
2096
     * @param packageZipEntry, the zip entry name for whole package
2097
     */
2098
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2099
            ZipOutputStream zipOut, String packageZipEntry)
2100
            throws ClassNotFoundException, IOException, SQLException,
2101
            McdbException, Exception
2102
    {
2103
        byte[] byteString = null;
2104
        ZipEntry zEntry = null;
2105
        // this is data file; add file to zip
2106
        String filePath = PropertyService.getProperty("application.datafilepath");
2107
        if (!filePath.endsWith("/")) {
2108
            filePath += "/";
2109
        }
2110
        String fileName = filePath + docImpl.getDocID();
2111
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2112
        zipOut.putNextEntry(zEntry);
2113
        FileInputStream fin = null;
2114
        try {
2115
            fin = new FileInputStream(fileName);
2116
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2117
            int b = fin.read(buf);
2118
            while (b != -1) {
2119
                zipOut.write(buf, 0, b);
2120
                b = fin.read(buf);
2121
            }//while
2122
            zipOut.closeEntry();
2123
        }//try
2124
        catch (IOException ioe) {
2125
            logMetacat.error("DBQuery.addDataFileToZipOutputStream - I/O error: "
2126
                    + ioe.getMessage());
2127
        }//catch
2128
    }//addDataFileToZipOutputStream()
2129

    
2130
    /**
2131
     * create a html summary for data package and put it into zip output stream
2132
     *
2133
     * @param docImplList, the documentImpl ojbects in data package
2134
     * @param zipOut, the zip output stream which the html should be put
2135
     * @param packageZipEntry, the zip entry name for whole package
2136
     */
2137
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2138
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2139
    {
2140
        StringBuffer htmlDoc = new StringBuffer();
2141
        ZipEntry zEntry = null;
2142
        byte[] byteString = null;
2143
        InputStream source;
2144
        DBTransform xmlToHtml;
2145

    
2146
        //create a DBTransform ojbect
2147
        xmlToHtml = new DBTransform();
2148
        //head of html
2149
        htmlDoc.append("<html><head></head><body>");
2150
        for (int i = 0; i < docImplList.size(); i++) {
2151
            // If this String object, this means it is missed data file
2152
            if ((((docImplList.elementAt(i)).getClass()).toString())
2153
                    .equals("class java.lang.String")) {
2154

    
2155
                htmlDoc.append("<a href=\"");
2156
                String dataFileid = (String) docImplList.elementAt(i);
2157
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2158
                htmlDoc.append("Data File: ");
2159
                htmlDoc.append(dataFileid).append("</a><br>");
2160
                htmlDoc.append("<br><hr><br>");
2161

    
2162
            }//if
2163
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2164
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2165
                                              // transform it.
2166
                //transform each file individually then concatenate all of the
2167
                //transformations together.
2168

    
2169
                //for metadata xml title
2170
                htmlDoc.append("<h2>");
2171
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2172
                        .getDocID());
2173
                //htmlDoc.append(".");
2174
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2175
                htmlDoc.append("</h2>");
2176
                //do the actual transform
2177
                StringWriter docString = new StringWriter();
2178
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2179
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2180
                        "-//W3C//HTML//EN", "html", docString, null, null);
2181
                htmlDoc.append(docString.toString());
2182
                htmlDoc.append("<br><br><hr><br><br>");
2183
            }//if
2184
            else { //this is a data file so we should link to it in the html
2185
                htmlDoc.append("<a href=\"");
2186
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2187
                        .getDocID();
2188
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2189
                htmlDoc.append("Data File: ");
2190
                htmlDoc.append(dataFileid).append("</a><br>");
2191
                htmlDoc.append("<br><hr><br>");
2192
            }//else
2193
        }//for
2194
        htmlDoc.append("</body></html>");
2195
        byteString = htmlDoc.toString().getBytes();
2196
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2197
        zEntry.setSize(byteString.length);
2198
        zipOut.putNextEntry(zEntry);
2199
        zipOut.write(byteString, 0, byteString.length);
2200
        zipOut.closeEntry();
2201
        //dbConn.close();
2202

    
2203
    }//addHtmlSummaryToZipOutputStream
2204

    
2205
    /**
2206
     * put a data packadge into a zip output stream
2207
     *
2208
     * @param docId, which the user want to put into zip output stream,it has version
2209
     * @param out, a servletoutput stream which the zip output stream will be
2210
     *            put
2211
     * @param user, the username of the user
2212
     * @param groups, the group of the user
2213
     */
2214
    public ZipOutputStream getZippedPackage(String docIdString,
2215
            ServletOutputStream out, String user, String[] groups,
2216
            String passWord) throws ClassNotFoundException, IOException,
2217
            SQLException, McdbException, NumberFormatException, Exception
2218
    {
2219
        ZipOutputStream zOut = null;
2220
        String elementDocid = null;
2221
        DocumentImpl docImpls = null;
2222
        //Connection dbConn = null;
2223
        Vector docIdList = new Vector();
2224
        Vector documentImplList = new Vector();
2225
        Vector htmlDocumentImplList = new Vector();
2226
        String packageId = null;
2227
        String rootName = "package";//the package zip entry name
2228

    
2229
        String docId = null;
2230
        int version = -5;
2231
        // Docid without revision
2232
        docId = DocumentUtil.getDocIdFromString(docIdString);
2233
        // revision number
2234
        version = DocumentUtil.getVersionFromString(docIdString);
2235

    
2236
        //check if the reqused docId is a data package id
2237
        if (!isDataPackageId(docId)) {
2238

    
2239
            /*
2240
             * Exception e = new Exception("The request the doc id "
2241
             * +docIdString+ " is not a data package id");
2242
             */
2243

    
2244
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2245
            // zip
2246
            //up the single document and return the zip file.
2247
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2248

    
2249
                Exception e = new Exception("User " + user
2250
                        + " does not have permission"
2251
                        + " to export the data package " + docIdString);
2252
                throw e;
2253
            }
2254

    
2255
            docImpls = new DocumentImpl(docIdString);
2256
            //checking if the user has the permission to read the documents
2257
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2258
                    .getDocID())) {
2259
                zOut = new ZipOutputStream(out);
2260
                //if the docImpls is metadata
2261
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2262
                    //add metadata into zip output stream
2263
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2264
                }//if
2265
                else {
2266
                    //it is data file
2267
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2268
                    htmlDocumentImplList.add(docImpls);
2269
                }//else
2270
            }//if
2271

    
2272
            zOut.finish(); //terminate the zip file
2273
            return zOut;
2274
        }
2275
        // Check the permission of user
2276
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2277

    
2278
            Exception e = new Exception("User " + user
2279
                    + " does not have permission"
2280
                    + " to export the data package " + docIdString);
2281
            throw e;
2282
        } else //it is a packadge id
2283
        {
2284
            //store the package id
2285
            packageId = docId;
2286
            //get current version in database
2287
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2288
            //If it is for current version (-1 means user didn't specify
2289
            // revision)
2290
            if ((version == -1) || version == currentVersion) {
2291
                //get current version number
2292
                version = currentVersion;
2293
                //get package zip entry name
2294
                //it should be docId.revsion.package
2295
                rootName = packageId + PropertyService.getProperty("document.accNumSeparator")
2296
                        + version + PropertyService.getProperty("document.accNumSeparator")
2297
                        + "package";
2298
                //get the whole id list for data packadge
2299
                docIdList = getCurrentDocidListForDataPackage(packageId);
2300
                //get the whole documentImple object
2301
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2302

    
2303
            }//if
2304
            else if (version > currentVersion || version < -1) {
2305
                throw new Exception("The user specified docid: " + docId + "."
2306
                        + version + " doesn't exist");
2307
            }//else if
2308
            else //for an old version
2309
            {
2310

    
2311
                rootName = docIdString
2312
                        + PropertyService.getProperty("document.accNumSeparator") + "package";
2313
                //get the whole id list for data packadge
2314
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2315

    
2316
                //get the whole documentImple object
2317
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2318
            }//else
2319

    
2320
            // Make sure documentImplist is not empty
2321
            if (documentImplList.isEmpty()) { throw new Exception(
2322
                    "Couldn't find component for data package: " + packageId); }//if
2323

    
2324
            zOut = new ZipOutputStream(out);
2325
            //put every element into zip output stream
2326
            for (int i = 0; i < documentImplList.size(); i++) {
2327
                // if the object in the vetor is String, this means we couldn't
2328
                // find
2329
                // the document locally, we need find it remote
2330
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2331
                        .equals("class java.lang.String")) {
2332
                    // Get String object from vetor
2333
                    String documentId = (String) documentImplList.elementAt(i);
2334
                    logMetacat.info("DBQuery.getZippedPackage - docid: " + documentId);
2335
                    // Get doicd without revision
2336
                    String docidWithoutRevision = 
2337
                    	DocumentUtil.getDocIdFromString(documentId);
2338
                    logMetacat.info("DBQuery.getZippedPackage - docidWithoutRevsion: "
2339
                            + docidWithoutRevision);
2340
                    // Get revision
2341
                    String revision = 
2342
                    	DocumentUtil.getRevisionStringFromString(documentId);
2343
                    logMetacat.info("DBQuery.getZippedPackage - revision from docIdentifier: "
2344
                            + revision);
2345
                    // Zip entry string
2346
                    String zipEntryPath = rootName + "/data/";
2347
                    // Create a RemoteDocument object
2348
                    RemoteDocument remoteDoc = new RemoteDocument(
2349
                            docidWithoutRevision, revision, user, passWord,
2350
                            zipEntryPath);
2351
                    // Here we only read data file from remote metacat
2352
                    String docType = remoteDoc.getDocType();
2353
                    if (docType != null) {
2354
                        if (docType.equals("BIN")) {
2355
                            // Put remote document to zip output
2356
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2357
                            // Add String object to htmlDocumentImplList
2358
                            String elementInHtmlList = remoteDoc
2359
                                    .getDocIdWithoutRevsion()
2360
                                    + PropertyService.getProperty("document.accNumSeparator")
2361
                                    + remoteDoc.getRevision();
2362
                            htmlDocumentImplList.add(elementInHtmlList);
2363
                        }//if
2364
                    }//if
2365

    
2366
                }//if
2367
                else {
2368
                    //create a docmentImpls object (represent xml doc) base on
2369
                    // the docId
2370
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2371
                    //checking if the user has the permission to read the
2372
                    // documents
2373
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2374
                            .getDocID())) {
2375
                        //if the docImpls is metadata
2376
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2377
                            //add metadata into zip output stream
2378
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2379
                            //add the documentImpl into the vetor which will
2380
                            // be used in html
2381
                            htmlDocumentImplList.add(docImpls);
2382

    
2383
                        }//if
2384
                        else {
2385
                            //it is data file
2386
                            addDataFileToZipOutputStream(docImpls, zOut,
2387
                                    rootName);
2388
                            htmlDocumentImplList.add(docImpls);
2389
                        }//else
2390
                    }//if
2391
                }//else
2392
            }//for
2393

    
2394
            //add html summary file
2395
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2396
                    rootName);
2397
            zOut.finish(); //terminate the zip file
2398
            //dbConn.close();
2399
            return zOut;
2400
        }//else
2401
    }//getZippedPackage()
2402

    
2403
    private class ReturnFieldValue
2404
    {
2405

    
2406
        private String docid = null; //return field value for this docid
2407

    
2408
        private String fieldValue = null;
2409

    
2410
        private String xmlFieldValue = null; //return field value in xml
2411
                                             // format
2412
        private String fieldType = null; //ATTRIBUTE, TEXT...
2413

    
2414
        public void setDocid(String myDocid)
2415
        {
2416
            docid = myDocid;
2417
        }
2418

    
2419
        public String getDocid()
2420
        {
2421
            return docid;
2422
        }
2423

    
2424
        public void setFieldValue(String myValue)
2425
        {
2426
            fieldValue = myValue;
2427
        }
2428

    
2429
        public String getFieldValue()
2430
        {
2431
            return fieldValue;
2432
        }
2433

    
2434
        public void setXMLFieldValue(String xml)
2435
        {
2436
            xmlFieldValue = xml;
2437
        }
2438

    
2439
        public String getXMLFieldValue()
2440
        {
2441
            return xmlFieldValue;
2442
        }
2443
        
2444
        public void setFieldType(String myType)
2445
        {
2446
            fieldType = myType;
2447
        }
2448

    
2449
        public String getFieldType()
2450
        {
2451
            return fieldType;
2452
        }
2453

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