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-06-14 16:40:14 -0700 (Mon, 14 Jun 2010) $'
14
 * '$Revision: 5387 $'
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

    
1220
	                	   if (existingRFV != null && !existingRFV.getFieldType().equals("ATTRIBUTE")) {
1221
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1222
	                	   }
1223
                	   }
1224
                	   //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1225
                       value.append("<param name=\"");
1226
                       value.append(fieldname);
1227
                       value.append("\">");
1228
                       value.append(fielddata);
1229
                       value.append("</param>");
1230
                       //set returnvalue
1231
                       returnValue.setDocid(docid);
1232
                       returnValue.setFieldValue(fielddata);
1233
                       returnValue.setFieldType(fieldtype);
1234
                       returnValue.setXMLFieldValue(value.toString());
1235
                       // Store it in hastable
1236
                       putInArray(parentidList, parentId, returnValue);
1237
                   }
1238
                   else {
1239
                       // need to merge nodedata if they have same parent id and
1240
                       // node type is text
1241
                       fielddata = (String) ( (ReturnFieldValue)
1242
                                             getArrayValue(
1243
                           parentidList, parentId)).getFieldValue()
1244
                           + fielddata;
1245
                       value.append("<param name=\"");
1246
                       value.append(fieldname);
1247
                       value.append("\">");
1248
                       value.append(fielddata);
1249
                       value.append("</param>");
1250
                       returnValue.setDocid(docid);
1251
                       returnValue.setFieldValue(fielddata);
1252
                       returnValue.setFieldType(fieldtype);
1253
                       returnValue.setXMLFieldValue(value.toString());
1254
                       // remove the old return value from paretnidList
1255
                       parentidList.remove(parentId);
1256
                       // store the new return value in parentidlit
1257
                       putInArray(parentidList, parentId, returnValue);
1258
                   }
1259
                   tableHasRows = rs.next();
1260
               } //while
1261
               rs.close();
1262
               pstmt.close();
1263

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

    
1290
         
1291
           
1292
           
1293
       }//if doclist lenght is great than zero
1294

    
1295
     }//if has extended query
1296

    
1297
      return docListResult;
1298
    }//addReturnfield
1299

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

    
1374

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

    
1381
        Vector tempVector = null;
1382

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

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

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

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

    
1426
        Vector tempVector = null;
1427

    
1428
        for (int count = 0; count < parentidList.size(); count++) 
1429
        {
1430
            tempVector = (Vector) parentidList.get(count);
1431

    
1432
            if (key.compareTo((String) tempVector.get(0)) == 0) 
1433
            { 
1434
                return (ReturnFieldValue) tempVector.get(1); 
1435
            }
1436
        }
1437
        return null;
1438
    }
1439

    
1440
    /*
1441
     * A method to get enumeration of all values in Vector
1442
     */
1443
    private Vector getElements(Vector parentidList)
1444
    {
1445
        Vector enumVector = new Vector();
1446
        Vector tempVector = null;
1447

    
1448
        for (int count = 0; count < parentidList.size(); count++) {
1449
            tempVector = (Vector) parentidList.get(count);
1450

    
1451
            enumVector.add(tempVector.get(1));
1452
        }
1453
        return enumVector;
1454
    }
1455

    
1456
  
1457

    
1458
    /*
1459
     * A method to create a query to get owner's docid list
1460
     */
1461
    private String getOwnerQuery(String owner)
1462
    {
1463
        if (owner != null) {
1464
            owner = owner.toLowerCase();
1465
        }
1466
        StringBuffer self = new StringBuffer();
1467

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

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

    
1504

    
1505

    
1506
        if (params.containsKey("meta_file_id")) {
1507
            query.append("<meta_file_id>");
1508
            query.append(((String[]) params.get("meta_file_id"))[0]);
1509
            query.append("</meta_file_id>");
1510
        }
1511

    
1512
        if (params.containsKey("returndoctype")) {
1513
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1514
            for (int i = 0; i < returnDoctypes.length; i++) {
1515
                String doctype = (String) returnDoctypes[i];
1516

    
1517
                if (!doctype.equals("any") && !doctype.equals("ANY")
1518
                        && !doctype.equals("")) {
1519
                    query.append("<returndoctype>").append(doctype);
1520
                    query.append("</returndoctype>");
1521
                }
1522
            }
1523
        }
1524

    
1525
        if (params.containsKey("filterdoctype")) {
1526
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1527
            for (int i = 0; i < filterDoctypes.length; i++) {
1528
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1529
                query.append("</filterdoctype>");
1530
            }
1531
        }
1532

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

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

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

    
1557
        //allows the dynamic switching of boolean operators
1558
        if (params.containsKey("operator")) {
1559
            query.append("<querygroup operator=\""
1560
                    + ((String[]) params.get("operator"))[0] + "\">");
1561
        } else { //the default operator is UNION
1562
            query.append("<querygroup operator=\"UNION\">");
1563
        }
1564

    
1565
        if (params.containsKey("casesensitive")) {
1566
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1567
        } else {
1568
            casesensitive = "false";
1569
        }
1570

    
1571
        if (params.containsKey("searchmode")) {
1572
            searchmode = ((String[]) params.get("searchmode"))[0];
1573
        } else {
1574
            searchmode = "contains";
1575
        }
1576

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

    
1594
        //this while loop finds the rest of the parameters
1595
        //and attempts to query for the field specified
1596
        //by the parameter.
1597
        elements = params.elements();
1598
        keys = params.keys();
1599
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1600
            nextkey = keys.nextElement();
1601
            nextelement = elements.nextElement();
1602

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

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

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

    
1665
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1666
            xmlquery.append("<returndoctype>");
1667
            xmlquery.append(doctype).append("</returndoctype>");
1668
        }
1669

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

    
1683
        return (xmlquery.toString());
1684
    }
1685

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

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

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

    
1726
        // Check the parameter
1727
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1728

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

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

    
1754
                //don't put the duplicate docId into the vector
1755
                if (!docIdList.contains(docIdInSubjectField)) {
1756
                    docIdList.add(docIdInSubjectField);
1757
                }
1758

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

    
1786
    /**
1787
     * Get all docIds list for a data packadge
1788
     *
1789
     * @param dataPackageDocid, the string in docId field of xml_relation table
1790
     */
1791
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1792
    {
1793

    
1794
        Vector docIdList = new Vector();//return value
1795
        Vector tripleList = null;
1796
        String xml = null;
1797

    
1798
        // Check the parameter
1799
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1800

    
1801
        try {
1802
            //initial a documentImpl object
1803
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1804
            //transfer to documentImpl object to string
1805
            xml = packageDocument.toString();
1806

    
1807
            //create a tripcollection object
1808
            TripleCollection tripleForPackage = new TripleCollection(
1809
                    new StringReader(xml));
1810
            //get the vetor of triples
1811
            tripleList = tripleForPackage.getCollection();
1812

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

    
1832
        // return result
1833
        return docIdList;
1834
    }//getDocidListForPackageInXMLRevisions()
1835

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

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

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

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

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

    
1975
        byteString = docImpl.toString().getBytes();
1976
        //use docId as the zip entry's name
1977
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1978
                + docImpl.getDocID());
1979
        zEntry.setSize(byteString.length);
1980
        zipOut.putNextEntry(zEntry);
1981
        zipOut.write(byteString, 0, byteString.length);
1982
        zipOut.closeEntry();
1983

    
1984
    }//addDocToZipOutputStream()
1985

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

    
1996
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1997
            throws McdbException, Exception
1998
    {
1999
        //Connection dbConn=null;
2000
        Vector documentImplList = new Vector();
2001
        int rev = 0;
2002

    
2003
        // Check the parameter
2004
        if (docIdList.isEmpty()) { return documentImplList; }//if
2005

    
2006
        //for every docid in vector
2007
        for (int i = 0; i < docIdList.size(); i++) {
2008
            try {
2009
                //get newest version for this docId
2010
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2011
                        .elementAt(i));
2012

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

    
2023
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2024
                        + PropertyService.getProperty("document.accNumSeparator") + rev;
2025

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

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

    
2058
        // Check the parameter
2059
        if (docIdList.isEmpty()) { return documentImplList; }//if
2060

    
2061
        //for every docid in vector
2062
        for (int i = 0; i < docIdList.size(); i++) {
2063

    
2064
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2065

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

    
2091
        }//for
2092
        return documentImplList;
2093
    }//getOldVersionAllDocumentImple
2094

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

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

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

    
2160
                htmlDoc.append("<a href=\"");
2161
                String dataFileid = (String) docImplList.elementAt(i);
2162
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2163
                htmlDoc.append("Data File: ");
2164
                htmlDoc.append(dataFileid).append("</a><br>");
2165
                htmlDoc.append("<br><hr><br>");
2166

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

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

    
2208
    }//addHtmlSummaryToZipOutputStream
2209

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

    
2234
        String docId = null;
2235
        int version = -5;
2236
        // Docid without revision
2237
        docId = DocumentUtil.getDocIdFromString(docIdString);
2238
        // revision number
2239
        version = DocumentUtil.getVersionFromString(docIdString);
2240

    
2241
        //check if the reqused docId is a data package id
2242
        if (!isDataPackageId(docId)) {
2243

    
2244
            /*
2245
             * Exception e = new Exception("The request the doc id "
2246
             * +docIdString+ " is not a data package id");
2247
             */
2248

    
2249
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2250
            // zip
2251
            //up the single document and return the zip file.
2252
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2253

    
2254
                Exception e = new Exception("User " + user
2255
                        + " does not have permission"
2256
                        + " to export the data package " + docIdString);
2257
                throw e;
2258
            }
2259

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

    
2277
            zOut.finish(); //terminate the zip file
2278
            return zOut;
2279
        }
2280
        // Check the permission of user
2281
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2282

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

    
2308
            }//if
2309
            else if (version > currentVersion || version < -1) {
2310
                throw new Exception("The user specified docid: " + docId + "."
2311
                        + version + " doesn't exist");
2312
            }//else if
2313
            else //for an old version
2314
            {
2315

    
2316
                rootName = docIdString
2317
                        + PropertyService.getProperty("document.accNumSeparator") + "package";
2318
                //get the whole id list for data packadge
2319
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2320

    
2321
                //get the whole documentImple object
2322
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2323
            }//else
2324

    
2325
            // Make sure documentImplist is not empty
2326
            if (documentImplList.isEmpty()) { throw new Exception(
2327
                    "Couldn't find component for data package: " + packageId); }//if
2328

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

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

    
2388
                        }//if
2389
                        else {
2390
                            //it is data file
2391
                            addDataFileToZipOutputStream(docImpls, zOut,
2392
                                    rootName);
2393
                            htmlDocumentImplList.add(docImpls);
2394
                        }//else
2395
                    }//if
2396
                }//else
2397
            }//for
2398

    
2399
            //add html summary file
2400
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2401
                    rootName);
2402
            zOut.finish(); //terminate the zip file
2403
            //dbConn.close();
2404
            return zOut;
2405
        }//else
2406
    }//getZippedPackage()
2407

    
2408
    private class ReturnFieldValue
2409
    {
2410

    
2411
        private String docid = null; //return field value for this docid
2412

    
2413
        private String fieldValue = null;
2414

    
2415
        private String xmlFieldValue = null; //return field value in xml
2416
                                             // format
2417
        private String fieldType = null; //ATTRIBUTE, TEXT...
2418

    
2419
        public void setDocid(String myDocid)
2420
        {
2421
            docid = myDocid;
2422
        }
2423

    
2424
        public String getDocid()
2425
        {
2426
            return docid;
2427
        }
2428

    
2429
        public void setFieldValue(String myValue)
2430
        {
2431
            fieldValue = myValue;
2432
        }
2433

    
2434
        public String getFieldValue()
2435
        {
2436
            return fieldValue;
2437
        }
2438

    
2439
        public void setXMLFieldValue(String xml)
2440
        {
2441
            xmlFieldValue = xml;
2442
        }
2443

    
2444
        public String getXMLFieldValue()
2445
        {
2446
            return xmlFieldValue;
2447
        }
2448
        
2449
        public void setFieldType(String myType)
2450
        {
2451
            fieldType = myType;
2452
        }
2453

    
2454
        public String getFieldType()
2455
        {
2456
            return fieldType;
2457
        }
2458

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