Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *
12
 *   '$Author: leinfelder $'
13
 *     '$Date: 2011-04-11 17:46:45 -0700 (Mon, 11 Apr 2011) $'
14
 * '$Revision: 6035 $'
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.BufferedWriter;
34
import java.io.File;
35
import java.io.FileInputStream;
36
import java.io.FileOutputStream;
37
import java.io.IOException;
38
import java.io.InputStream;
39
import java.io.InputStreamReader;
40
import java.io.OutputStreamWriter;
41
import java.io.Reader;
42
import java.io.StringReader;
43
import java.io.StringWriter;
44
import java.io.Writer;
45
import java.sql.PreparedStatement;
46
import java.sql.ResultSet;
47
import java.sql.SQLException;
48
import java.util.Enumeration;
49
import java.util.Hashtable;
50
import java.util.Iterator;
51
import java.util.StringTokenizer;
52
import java.util.Vector;
53
import java.util.zip.ZipEntry;
54
import java.util.zip.ZipOutputStream;
55

    
56
import javax.servlet.ServletOutputStream;
57
import javax.servlet.http.HttpServletResponse;
58

    
59
import org.apache.log4j.Logger;
60

    
61
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
62
import edu.ucsb.nceas.metacat.database.DBConnection;
63
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
64
import edu.ucsb.nceas.metacat.properties.PropertyService;
65
import edu.ucsb.nceas.metacat.util.AuthUtil;
66
import edu.ucsb.nceas.metacat.util.DocumentUtil;
67
import edu.ucsb.nceas.metacat.util.MetacatUtil;
68
import edu.ucsb.nceas.morpho.datapackage.Triple;
69
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
70
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
71

    
72

    
73
/**
74
 * A Class that searches a relational DB for elements and attributes that have
75
 * free text matches a query string, or structured query matches to a path
76
 * specified node in the XML hierarchy. It returns a result set consisting of
77
 * the document ID for each document that satisfies the query
78
 */
79
public class DBQuery
80
{
81

    
82
    static final int ALL = 1;
83

    
84
    static final int WRITE = 2;
85

    
86
    static final int READ = 4;
87
    
88
    private String qformat = "xml";
89
    
90
    // are we combining the query with docid list and, if so, using INTERSECT or UNION?
91
    private String operator = null;
92

    
93
    //private Connection conn = null;
94
    private String parserName = null;
95

    
96
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
97

    
98
    /** true if the metacat spatial option is installed **/
99
    private final boolean METACAT_SPATIAL = true;
100

    
101
    /** useful if you just want to grab a list of docids. Since the docids can be very long,
102
         it is a vector of vector  **/
103
    Vector docidOverride = new Vector();
104
    
105
    // a hash table serves as query reuslt cache. Key of hashtable
106
    // is a query string and value is result xml string
107
    private static Hashtable queryResultCache = new Hashtable();
108
    
109
    // Capacity of the query result cache
110
    private static final int QUERYRESULTCACHESIZE;
111
    static {
112
    	int qryRsltCacheSize = 0;
113
    	try {
114
    		qryRsltCacheSize = Integer.parseInt(PropertyService.getProperty("database.queryresultCacheSize"));
115
    	} catch (PropertyNotFoundException pnfe) {
116
    		System.err.println("Could not get QUERYRESULTCACHESIZE property in static block: "
117
					+ pnfe.getMessage());
118
    	}
119
    	QUERYRESULTCACHESIZE = qryRsltCacheSize;
120
    }
121
    
122

    
123
    // Size of page for non paged query
124
    private static final int NONPAGESIZE = 99999999;
125
    /**
126
     * the main routine used to test the DBQuery utility.
127
     * <p>
128
     * Usage: java DBQuery <xmlfile>
129
     * NOTE: encoding should be provided for best results
130
     * @param xmlfile the filename of the xml file containing the query
131
     */
132
    static public void main(String[] args)
133
    {
134

    
135
        if (args.length < 1) {
136
            System.err.println("Wrong number of arguments!!!");
137
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
138
            return;
139
        } else {
140
            try {
141

    
142
                int i = 0;
143
                boolean showRuntime = false;
144
                boolean useXMLIndex = false;
145
                if (args[i].equals("-t")) {
146
                    showRuntime = true;
147
                    i++;
148
                }
149
                if (args[i].equals("-index")) {
150
                    useXMLIndex = true;
151
                    i++;
152
                }
153
                String xmlfile = args[i];
154

    
155
                // Time the request if asked for
156
                double startTime = System.currentTimeMillis();
157

    
158
                // Open a connection to the database
159
                //Connection dbconn = util.openDBConnection();
160

    
161
                double connTime = System.currentTimeMillis();
162

    
163
                // Execute the query
164
                DBQuery queryobj = new DBQuery();
165
                Reader xml = new InputStreamReader(new FileInputStream(new File(xmlfile)));
166
                Hashtable nodelist = null;
167
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
168

    
169
                // Print the reulting document listing
170
                StringBuffer result = new StringBuffer();
171
                String document = null;
172
                String docid = null;
173
                result.append("<?xml version=\"1.0\"?>\n");
174
                result.append("<resultset>\n");
175

    
176
                if (!showRuntime) {
177
                    Enumeration doclist = nodelist.keys();
178
                    while (doclist.hasMoreElements()) {
179
                        docid = (String) doclist.nextElement();
180
                        document = (String) nodelist.get(docid);
181
                        result.append("  <document>\n    " + document
182
                                + "\n  </document>\n");
183
                    }
184

    
185
                    result.append("</resultset>\n");
186
                }
187
                // Time the request if asked for
188
                double stopTime = System.currentTimeMillis();
189
                double dbOpenTime = (connTime - startTime) / 1000;
190
                double readTime = (stopTime - connTime) / 1000;
191
                double executionTime = (stopTime - startTime) / 1000;
192
                if (showRuntime) {
193
                    System.out.print("  " + executionTime);
194
                    System.out.print("  " + dbOpenTime);
195
                    System.out.print("  " + readTime);
196
                    System.out.print("  " + nodelist.size());
197
                    System.out.println();
198
                }
199
                //System.out.println(result);
200
                //write into a file "result.txt"
201
                if (!showRuntime) {
202
                    File f = new File("./result.txt");
203
                    Writer fw = new OutputStreamWriter(new FileOutputStream(f));
204
                    BufferedWriter out = new BufferedWriter(fw);
205
                    out.write(result.toString());
206
                    out.flush();
207
                    out.close();
208
                    fw.close();
209
                }
210

    
211
            } catch (Exception e) {
212
                System.err.println("Error in DBQuery.main");
213
                System.err.println(e.getMessage());
214
                e.printStackTrace(System.err);
215
            }
216
        }
217
    }
218

    
219
    /**
220
     * construct an instance of the DBQuery class
221
     *
222
     * <p>
223
     * Generally, one would call the findDocuments() routine after creating an
224
     * instance to specify the search query
225
     * </p>
226
     *
227

    
228
     * @param parserName the fully qualified name of a Java class implementing
229
     *            the org.xml.sax.XMLReader interface
230
     */
231
    public DBQuery() throws PropertyNotFoundException
232
    {
233
        String parserName = PropertyService.getProperty("xml.saxparser");
234
        this.parserName = parserName;
235
    }
236

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

    
294
  /**
295
   * Method put the search result set into out printerwriter
296
   * @param resoponse the return response
297
   * @param out the output printer
298
   * @param params the paratermer hashtable
299
   * @param user the user name (it maybe different to the one in param)
300
   * @param groups the group array
301
   * @param sessionid  the sessionid
302
   */
303
  public void findDocuments(HttpServletResponse response,
304
                                       Writer out, Hashtable params,
305
                                       String user, String[] groups,
306
                                       String sessionid) throws PropertyNotFoundException
307
  {
308
    boolean useXMLIndex = (new Boolean(PropertyService.getProperty("database.usexmlindex")))
309
               .booleanValue();
310
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
311

    
312
  }
313

    
314

    
315
    /**
316
     * Method put the search result set into out printerwriter
317
     * @param resoponse the return response
318
     * @param out the output printer
319
     * @param params the paratermer hashtable
320
     * @param user the user name (it maybe different to the one in param)
321
     * @param groups the group array
322
     * @param sessionid  the sessionid
323
     */
324
    public void findDocuments(HttpServletResponse response,
325
                                         Writer out, Hashtable params,
326
                                         String user, String[] groups,
327
                                         String sessionid, boolean useXMLIndex)
328
    {
329
      int pagesize = 0;
330
      int pagestart = 0;
331
      long transferWarnLimit = 0; 
332
      
333
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
334
      {
335
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
336
        String pagestartStr = ((String[])params.get("pagestart"))[0];
337
        if(pagesizeStr != null && pagestartStr != null)
338
        {
339
          pagesize = (new Integer(pagesizeStr)).intValue();
340
          pagestart = (new Integer(pagestartStr)).intValue();
341
        }
342
      }
343
      
344
      String xmlquery = null;
345
      String qformat = null;
346
      // get query and qformat
347
      try {
348
    	xmlquery = ((String[])params.get("query"))[0];
349

    
350
        logMetacat.info("DBQuery.findDocuments - SESSIONID: " + sessionid);
351
        logMetacat.info("DBQuery.findDocuments - xmlquery: " + xmlquery);
352
        qformat = ((String[])params.get("qformat"))[0];
353
        logMetacat.info("DBQuery.findDocuments - qformat: " + qformat);
354
      }
355
      catch (Exception ee)
356
      {
357
        logMetacat.error("DBQuery.findDocuments - Couldn't retrieve xmlquery or qformat value from "
358
                  +"params hashtable in DBQuery.findDocuments: "
359
                  + ee.getMessage()); 
360
      }
361
      // Get the XML query and covert it into a SQL statment
362
      QuerySpecification qspec = null;
363
      if ( xmlquery != null)
364
      {
365
         xmlquery = transformQuery(xmlquery);
366
         try
367
         {
368
           qspec = new QuerySpecification(xmlquery,
369
                                          parserName,
370
                                          PropertyService.getProperty("document.accNumSeparator"));
371
         }
372
         catch (Exception ee)
373
         {
374
           logMetacat.error("DBQuery.findDocuments - error generating QuerySpecification object: "
375
                                    + ee.getMessage());
376
         }
377
      }
378

    
379

    
380

    
381
      if (qformat != null && qformat.equals(MetacatUtil.XMLFORMAT))
382
      {
383
        //xml format
384
        if(response != null)
385
        {
386
            response.setContentType("text/xml");
387
        }
388
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex, 
389
          pagesize, pagestart, sessionid, qformat);
390
      }//if
391
      else
392
      {
393
        //knb format, in this case we will get whole result and sent it out
394
        response.setContentType("text/html");
395
        Writer nonout = null;
396
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
397
                                                groups, useXMLIndex, pagesize, 
398
                                                pagestart, sessionid, qformat);
399
        
400
        //transfer the xml to html
401
        try
402
        {
403
         long startHTMLTransform = System.currentTimeMillis();
404
         DBTransform trans = new DBTransform();
405
         response.setContentType("text/html");
406

    
407
         // if the user is a moderator, then pass a param to the 
408
         // xsl specifying the fact
409
         if(AuthUtil.isModerator(user, groups)){
410
        	 params.put("isModerator", new String[] {"true"});
411
         }
412

    
413
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
414
                                 "-//W3C//HTML//EN", qformat, out, params,
415
                                 sessionid);
416
         long transformRunTime = System.currentTimeMillis() - startHTMLTransform;
417
         
418
         transferWarnLimit = Long.parseLong(PropertyService.getProperty("dbquery.transformTimeWarnLimit"));
419
         
420
         if (transformRunTime > transferWarnLimit) {
421
         	logMetacat.warn("DBQuery.findDocuments - The time to transfrom resultset from xml to html format is "
422
                  		                             + transformRunTime);
423
         }
424
          MetacatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Transfrom xml to html  "
425
                             + transformRunTime);
426
          MetacatUtil.writeDebugToDelimiteredFile(" " + transformRunTime, false);
427
        }
428
        catch(Exception e)
429
        {
430
         logMetacat.error("DBQuery.findDocuments - Error in MetaCatServlet.transformResultset:"
431
                                +e.getMessage());
432
         }
433

    
434
      }//else
435

    
436
  }
437
    
438
    
439
  
440
  /**
441
   * Transforms a hashtable of documents to an xml or html result and sent
442
   * the content to outputstream. Keep going untill hastable is empty. stop it.
443
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
444
   * to xmlquery String
445
   * @param xmlquery
446
   * @param qspec
447
   * @param out
448
   * @param user
449
   * @param groups
450
   * @param useXMLIndex
451
   * @param sessionid
452
   * @return
453
   */
454
    public StringBuffer createResultDocument(String xmlquery,
455
                                              QuerySpecification qspec,
456
                                              Writer out,
457
                                              String user, String[] groups,
458
                                              boolean useXMLIndex)
459
    {
460
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"", qformat);
461
    }
462

    
463
  /*
464
   * Transforms a hashtable of documents to an xml or html result and sent
465
   * the content to outputstream. Keep going untill hastable is empty. stop it.
466
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
467
   * to xmlquery String
468
   */
469
  public StringBuffer createResultDocument(String xmlquery,
470
                                            QuerySpecification qspec,
471
                                            Writer out,
472
                                            String user, String[] groups,
473
                                            boolean useXMLIndex, int pagesize,
474
                                            int pagestart, String sessionid, 
475
                                            String qformat)
476
  {
477
    DBConnection dbconn = null;
478
    int serialNumber = -1;
479
    StringBuffer resultset = new StringBuffer();
480

    
481
    //try to get the cached version first    
482
    // Hashtable sessionHash = MetaCatServlet.getSessionHash();
483
    // HttpSession sess = (HttpSession)sessionHash.get(sessionid);
484

    
485
    
486
    resultset.append("<?xml version=\"1.0\"?>\n");
487
    resultset.append("<resultset>\n");
488
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
489
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
490
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
491
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
492

    
493
    resultset.append("  <query>" + xmlquery + "</query>");
494
    //send out a new query
495
    if (out != null)
496
    {
497
    	try {
498
    	  out.write(resultset.toString());
499
		} catch (IOException e) {
500
			logMetacat.error(e.getMessage(), e);
501
		}
502
    }
503
    if (qspec != null)
504
    {
505
      try
506
      {
507

    
508
        //checkout the dbconnection
509
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
510
        serialNumber = dbconn.getCheckOutSerialNumber();
511

    
512
        //print out the search result
513
        // search the doc list
514
        Vector givenDocids = new Vector();
515
        StringBuffer resultContent = new StringBuffer();
516
        if (docidOverride == null || docidOverride.size() == 0)
517
        {
518
        	logMetacat.debug("DBQuery.createResultDocument - Not in map query");
519
        	resultContent = findResultDoclist(qspec, out, user, groups,
520
                    dbconn, useXMLIndex, pagesize, pagestart, 
521
                    sessionid, givenDocids, qformat);
522
        }
523
        else
524
        {
525
        	logMetacat.debug("DBQuery.createResultDocument - In map query");
526
        	// since docid can be too long to be handled. We divide it into several parts
527
        	for (int i= 0; i<docidOverride.size(); i++)
528
        	{
529
        	   logMetacat.debug("DBQuery.createResultDocument - in loop===== "+i);
530
        		givenDocids = (Vector)docidOverride.elementAt(i);
531
        		StringBuffer subset = findResultDoclist(qspec, out, user, groups,
532
                        dbconn, useXMLIndex, pagesize, pagestart, 
533
                        sessionid, givenDocids, qformat);
534
        		resultContent.append(subset);
535
        	}
536
        }
537
           
538
        resultset.append(resultContent);
539
      } //try
540
      catch (IOException ioe)
541
      {
542
        logMetacat.error("DBQuery.createResultDocument - IO error: " + ioe.getMessage());
543
      }
544
      catch (SQLException e)
545
      {
546
        logMetacat.error("DBQuery.createResultDocument - SQL Error: " + e.getMessage());
547
      }
548
      catch (Exception ee)
549
      {
550
        logMetacat.error("DBQuery.createResultDocument - General exception: "
551
                                 + ee.getMessage());
552
        ee.printStackTrace();
553
      }
554
      finally
555
      {
556
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
557
      } //finally
558
    }//if
559
    String closeRestultset = "</resultset>";
560
    resultset.append(closeRestultset);
561
    if (out != null)
562
    {
563
      try {
564
		out.write(closeRestultset);
565
		} catch (IOException e) {
566
			logMetacat.error(e.getMessage(), e);
567
		}
568
    }
569

    
570
    //default to returning the whole resultset
571
    return resultset;
572
  }//createResultDocuments
573

    
574
    /*
575
     * Find the doc list which match the query
576
     */
577
    private StringBuffer findResultDoclist(QuerySpecification qspec,
578
                                      Writer out,
579
                                      String user, String[]groups,
580
                                      DBConnection dbconn, boolean useXMLIndex,
581
                                      int pagesize, int pagestart, String sessionid, 
582
                                      Vector givenDocids, String qformat)
583
                                      throws Exception
584
    {
585
      StringBuffer resultsetBuffer = new StringBuffer();
586
      String query = null;
587
      int count = 0;
588
      int index = 0;
589
      ResultDocumentSet docListResult = new ResultDocumentSet();
590
      PreparedStatement pstmt = null;
591
      String docid = null;
592
      String docname = null;
593
      String doctype = null;
594
      String createDate = null;
595
      String updateDate = null;
596
      StringBuffer document = null;
597
      boolean lastpage = false;
598
      int rev = 0;
599
      double startTime = 0;
600
      int offset = 1;
601
      long startSelectionTime = System.currentTimeMillis();
602
      ResultSet rs = null;
603
           
604
   
605
      // this is a hack for offset. in postgresql 7, if the returned docid list is too long,
606
      //the extend query which base on the docid will be too long to be run. So we 
607
      // have to cut them into different parts. Page query don't need it somehow.
608
      if (out == null)
609
      {
610
        // for html page, we put everything into one page
611
        offset =
612
            (new Integer(PropertyService.getProperty("database.webResultsetSize"))).intValue();
613
      }
614
      else
615
      {
616
          offset =
617
              (new Integer(PropertyService.getProperty("database.appResultsetSize"))).intValue();
618
      }
619

    
620
      /*
621
       * Check the docidOverride Vector
622
       * if defined, we bypass the qspec.printSQL() method
623
       * and contruct a simpler query based on a 
624
       * list of docids rather than a bunch of subselects
625
       */
626
      if ( givenDocids == null || givenDocids.size() == 0 ) {
627
          query = qspec.printSQL(useXMLIndex);
628
      } else {
629
    	  // condition for the docids
630
    	  StringBuffer docidCondition = new StringBuffer();
631
    	  docidCondition.append( " docid IN (" );
632
          for (int i = 0; i < givenDocids.size(); i++) {  
633
        	  docidCondition.append("'");
634
        	  docidCondition.append( (String)givenDocids.elementAt(i) );
635
        	  docidCondition.append("'");
636
        	  if (i < givenDocids.size()-1) {
637
        		  docidCondition.append(",");
638
        	  }
639
          }
640
          docidCondition.append( ") " );
641
		  
642
    	  // include the docids, either exclusively, or in conjuction with the query
643
    	  if (operator == null) {
644
    		  query = "SELECT docid, docname, doctype, date_created, date_updated, rev FROM xml_documents WHERE";
645
              query = query + docidCondition.toString();
646
    	  } else {
647
    		  // start with the keyword query, but add conditions
648
              query = qspec.printSQL(useXMLIndex);
649
              String myOperator = "";
650
              if (!query.endsWith("WHERE")) {
651
	              if (operator.equalsIgnoreCase(QueryGroup.UNION)) {
652
	            	  myOperator =  " OR ";
653
	              }
654
	              else {
655
	            	  myOperator =  " AND ";
656
	              }
657
              }
658
              query = query + myOperator + docidCondition.toString();
659

    
660
    	  }
661
      } 
662
      String ownerQuery = getOwnerQuery(user);
663
      //logMetacat.debug("query: " + query);
664
      logMetacat.debug("DBQuery.findResultDoclist - owner query: " + ownerQuery);
665
      // if query is not the owner query, we need to check the permission
666
      // otherwise we don't need (owner has all permission by default)
667
      if (!query.equals(ownerQuery))
668
      {
669
        // set user name and group
670
        qspec.setUserName(user);
671
        qspec.setGroup(groups);
672
        // Get access query
673
        String accessQuery = qspec.getAccessQuery();
674
        if(!query.endsWith("WHERE")){
675
            query = query + accessQuery;
676
        } else {
677
            query = query + accessQuery.substring(4, accessQuery.length());
678
        }
679
        
680
      }
681
      logMetacat.debug("DBQuery.findResultDoclist - final selection query: " + query);
682
      String selectionAndExtendedQuery = null;
683
      // we only get cache for public
684
      if (user != null && user.equalsIgnoreCase("public") 
685
     		 && pagesize == 0 && PropertyService.getProperty("database.queryCacheOn").equals("true"))
686
      {
687
    	  selectionAndExtendedQuery = query +qspec.getReturnDocList()+qspec.getReturnFieldList();
688
   	      String cachedResult = getResultXMLFromCache(selectionAndExtendedQuery);
689
   	      logMetacat.debug("DBQuery.findResultDoclist - The key of query cache is " + selectionAndExtendedQuery);
690
   	      //System.out.println("==========the string from cache is "+cachedResult);
691
   	      if (cachedResult != null)
692
   	      {
693
   	    	logMetacat.info("DBQuery.findResultDoclist - result from cache !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
694
   	    	 if (out != null)
695
   	         {
696
   	             out.write(cachedResult);
697
   	         }
698
   	    	 resultsetBuffer.append(cachedResult);
699
   	    	 return resultsetBuffer;
700
   	      }
701
      }
702
      
703
      startTime = System.currentTimeMillis() / 1000;
704
      pstmt = dbconn.prepareStatement(query);
705
      rs = pstmt.executeQuery();
706

    
707
      double queryExecuteTime = System.currentTimeMillis() / 1000;
708
      logMetacat.debug("DBQuery.findResultDoclist - Time to execute select docid query is "
709
                    + (queryExecuteTime - startTime));
710
      MetacatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
711
              + (queryExecuteTime - startTime));
712
      MetacatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
713

    
714
      boolean tableHasRows = rs.next();
715
      
716
      if(pagesize == 0)
717
      { //this makes sure we get all results if there is no paging
718
        pagesize = NONPAGESIZE;
719
        pagestart = NONPAGESIZE;
720
      } 
721
      
722
      int currentIndex = 0;
723
      while (tableHasRows)
724
      {
725
        logMetacat.debug("DBQuery.findResultDoclist - getting result: " + currentIndex);
726
        docid = rs.getString(1).trim();
727
        logMetacat.debug("DBQuery.findResultDoclist -  processing: " + docid);
728
        docname = rs.getString(2);
729
        doctype = rs.getString(3);
730
        logMetacat.debug("DBQuery.findResultDoclist - processing: " + doctype);
731
        createDate = rs.getString(4);
732
        updateDate = rs.getString(5);
733
        rev = rs.getInt(6);
734
        
735
         Vector returndocVec = qspec.getReturnDocList();
736
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
737
        {
738
          logMetacat.debug("DBQuery.findResultDoclist - NOT Back tracing now...");
739
           document = new StringBuffer();
740

    
741
           String completeDocid = docid
742
                            + PropertyService.getProperty("document.accNumSeparator");
743
           completeDocid += rev;
744
           document.append("<docid>").append(completeDocid).append("</docid>");
745
           if (docname != null)
746
           {
747
               document.append("<docname>" + docname + "</docname>");
748
           }
749
           if (doctype != null)
750
           {
751
              document.append("<doctype>" + doctype + "</doctype>");
752
           }
753
           if (createDate != null)
754
           {
755
               document.append("<createdate>" + createDate + "</createdate>");
756
           }
757
           if (updateDate != null)
758
           {
759
             document.append("<updatedate>" + updateDate + "</updatedate>");
760
           }
761
           // Store the document id and the root node id
762
           
763
           docListResult.addResultDocument(
764
             new ResultDocument(docid, (String) document.toString()));
765
           logMetacat.info("DBQuery.findResultDoclist - real result: " + docid);
766
           currentIndex++;
767
           count++;
768
        }//else
769
        
770
        // when doclist reached the offset number, send out doc list and empty
771
        // the hash table
772
        if (count == offset && pagesize == NONPAGESIZE)
773
        { //if pagesize is not 0, do this later.
774
          //reset count
775
          //logMetacat.warn("############doing subset cache");
776
          count = 0;
777
          handleSubsetResult(qspec, resultsetBuffer, out, docListResult,
778
                              user, groups,dbconn, useXMLIndex, qformat);
779
          //reset docListResult
780
          docListResult = new ResultDocumentSet();
781
        }
782
       
783
       logMetacat.debug("DBQuery.findResultDoclist - currentIndex: " + currentIndex);
784
       logMetacat.debug("DBQuery.findResultDoclist - page comparator: " + (pagesize * pagestart) + pagesize);
785
       if(currentIndex >= ((pagesize * pagestart) + pagesize))
786
       {
787
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
788
         for(int i=pagesize*pagestart; i<docListResult.size(); i++)
789
         {
790
           pagedResultsHash.put(docListResult.get(i));
791
         }
792
         
793
         docListResult = pagedResultsHash;
794
         break;
795
       }
796
       // Advance to the next record in the cursor
797
       tableHasRows = rs.next();
798
       if(!tableHasRows)
799
       {
800
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
801
         //get the last page of information then break
802
         if(pagesize != NONPAGESIZE)
803
         {
804
           for(int i=pagesize*pagestart; i<docListResult.size(); i++)
805
           {
806
             pagedResultsHash.put(docListResult.get(i));
807
           }
808
           docListResult = pagedResultsHash;
809
         }
810
         
811
         lastpage = true;
812
         break;
813
       }
814
     }//while
815
     
816
     rs.close();
817
     pstmt.close();
818
     long docListTime = System.currentTimeMillis() - startSelectionTime;
819
     long docListWarnLimit = Long.parseLong(PropertyService.getProperty("dbquery.findDocListTimeWarnLimit"));
820
     if (docListTime > docListWarnLimit) {
821
    	 logMetacat.warn("DBQuery.findResultDoclist - Total time to get docid list is: "
822
                          + docListTime);
823
     }
824
     MetacatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Total selection: "
825
             + docListTime);
826
     MetacatUtil.writeDebugToDelimiteredFile(" "+ docListTime, false);
827
     //if docListResult is not empty, it need to be sent.
828
     if (docListResult.size() != 0)
829
     {
830
      
831
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
832
                              user, groups,dbconn, useXMLIndex, qformat);
833
     }
834

    
835
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
836
     if (out != null)
837
     {
838
         out.write("\n<lastpage>" + lastpage + "</lastpage>\n");
839
     }
840
     
841
     // now we only cached none-paged query and user is public
842
     if (user != null && user.equalsIgnoreCase("public") 
843
    		 && pagesize == NONPAGESIZE && PropertyService.getProperty("database.queryCacheOn").equals("true"))
844
     {
845
       //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
846
  	   storeQueryResultIntoCache(selectionAndExtendedQuery, resultsetBuffer.toString());
847
     }
848
          
849
     return resultsetBuffer;
850
    }//findReturnDoclist
851

    
852

    
853
    /*
854
     * Send completed search hashtable(part of reulst)to output stream
855
     * and buffer into a buffer stream
856
     */
857
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
858
                                           StringBuffer resultset,
859
                                           Writer out, ResultDocumentSet partOfDoclist,
860
                                           String user, String[]groups,
861
                                       DBConnection dbconn, boolean useXMLIndex,
862
                                       String qformat)
863
                                       throws Exception
864
   {
865
     double startReturnFieldTime = System.currentTimeMillis();
866
     // check if there is a record in xml_returnfield
867
     // and get the returnfield_id and usage count
868
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
869
     boolean enterRecords = false;
870

    
871
     // get value of database.xmlReturnfieldCount
872
     int count = (new Integer(PropertyService
873
                            .getProperty("database.xmlReturnfieldCount")))
874
                            .intValue();
875

    
876
     // set enterRecords to true if usage_count is more than the offset
877
     // specified in metacat.properties
878
     if(usage_count > count){
879
         enterRecords = true;
880
     }
881

    
882
     if(returnfield_id < 0){
883
         logMetacat.warn("DBQuery.handleSubsetResult - Error in getting returnfield id from"
884
                                  + "xml_returnfield table");
885
         enterRecords = false;
886
     }
887

    
888
     // get the hashtable containing the docids that already in the
889
     // xml_queryresult table
890
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist before"
891
                             + " docidsInQueryresultTable(): "
892
                             + partOfDoclist.size());
893
     long startGetReturnValueFromQueryresultable = System.currentTimeMillis();
894
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
895
                                                        partOfDoclist, dbconn);
896

    
897
     // remove the keys in queryresultDocList from partOfDoclist
898
     Enumeration _keys = queryresultDocList.keys();
899
     while (_keys.hasMoreElements()){
900
         partOfDoclist.remove((String)_keys.nextElement());
901
     }
902
     
903
     long queryResultReturnValuetime = System.currentTimeMillis() - startGetReturnValueFromQueryresultable;
904
     long queryResultWarnLimit = 
905
    	 Long.parseLong(PropertyService.getProperty("dbquery.findQueryResultsTimeWarnLimit"));
906
     
907
     if (queryResultReturnValuetime > queryResultWarnLimit) {
908
    	 logMetacat.warn("DBQuery.handleSubsetResult - Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
909
    		 queryResultReturnValuetime);
910
     }
911
     MetacatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
912
    		 queryResultReturnValuetime);
913
     MetacatUtil.writeDebugToDelimiteredFile(" " + queryResultReturnValuetime,false);
914
     
915
     long startExtendedQuery = System.currentTimeMillis();
916
     // backup the keys-elements in partOfDoclist to check later
917
     // if the doc entry is indexed yet
918
     Hashtable partOfDoclistBackup = new Hashtable();
919
     Iterator itt = partOfDoclist.getDocids();
920
     while (itt.hasNext()){
921
       Object key = itt.next();
922
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
923
     }
924

    
925
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist after"
926
                             + " docidsInQueryresultTable(): "
927
                             + partOfDoclist.size());
928

    
929
     //add return fields for the documents in partOfDoclist
930
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
931
                                        dbconn, useXMLIndex, qformat);
932
     long extendedQueryRunTime = startExtendedQuery - System.currentTimeMillis();
933
     long extendedQueryWarnLimit = 
934
    	 Long.parseLong(PropertyService.getProperty("dbquery.extendedQueryRunTimeWarnLimit"));
935
  
936
     if (extendedQueryRunTime > extendedQueryWarnLimit) {
937
    	 logMetacat.warn("DBQuery.handleSubsetResult - Get fields from index and node table (Part2 in return fields) "
938
        		                                          + extendedQueryRunTime);
939
     }
940
     MetacatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
941
             + extendedQueryRunTime);
942
     MetacatUtil.writeDebugToDelimiteredFile(" "
943
             + extendedQueryRunTime, false);
944
     //add relationship part part docid list for the documents in partOfDocList
945
     //partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
946

    
947
     long startStoreReturnField = System.currentTimeMillis();
948
     Iterator keys = partOfDoclist.getDocids();
949
     String key = null;
950
     String element = null;
951
     String query = null;
952
     int offset = (new Integer(PropertyService
953
                               .getProperty("database.queryresultStringLength")))
954
                               .intValue();
955
     while (keys.hasNext())
956
     {
957
         key = (String) keys.next();
958
         element = (String)partOfDoclist.get(key);
959
         
960
	 // check if the enterRecords is true, elements is not null, element's
961
         // length is less than the limit of table column and if the document
962
         // has been indexed already
963
         if(enterRecords && element != null
964
		&& element.length() < offset
965
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
966
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
967
                 + "queryresult_string) VALUES (?, ?, ?)";
968

    
969
             PreparedStatement pstmt = null;
970
             pstmt = dbconn.prepareStatement(query);
971
             pstmt.setInt(1, returnfield_id);
972
             pstmt.setString(2, key);
973
             pstmt.setString(3, element);
974
            
975
             dbconn.increaseUsageCount(1);
976
             try
977
             {
978
            	 pstmt.execute();
979
             }
980
             catch(Exception e)
981
             {
982
            	 logMetacat.warn("DBQuery.handleSubsetResult - couldn't insert the element to xml_queryresult table "+e.getLocalizedMessage());
983
             }
984
             finally
985
             {
986
                pstmt.close();
987
             }
988
         }
989
        
990
         // A string with element
991
         String xmlElement = "  <document>" + element + "</document>";
992

    
993
         //send single element to output
994
         if (out != null)
995
         {
996
             out.write(xmlElement);
997
         }
998
         resultset.append(xmlElement);
999
     }//while
1000
     
1001
     double storeReturnFieldTime = System.currentTimeMillis() - startStoreReturnField;
1002
     long storeReturnFieldWarnLimit = 
1003
    	 Long.parseLong(PropertyService.getProperty("dbquery.storeReturnFieldTimeWarnLimit"));
1004

    
1005
     if (storeReturnFieldTime > storeReturnFieldWarnLimit) {
1006
    	 logMetacat.warn("DBQuery.handleSubsetResult - Time to store new return fields into xml_queryresult table (Part4 in return fields) "
1007
                   + storeReturnFieldTime);
1008
     }
1009
     MetacatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
1010
             + storeReturnFieldTime);
1011
     MetacatUtil.writeDebugToDelimiteredFile(" " + storeReturnFieldTime, false);
1012
     
1013
     Enumeration keysE = queryresultDocList.keys();
1014
     while (keysE.hasMoreElements())
1015
     {
1016
         key = (String) keysE.nextElement();
1017
         element = (String)queryresultDocList.get(key);
1018
         // A string with element
1019
         String xmlElement = "  <document>" + element + "</document>";
1020
         //send single element to output
1021
         if (out != null)
1022
         {
1023
             out.write(xmlElement);
1024
         }
1025
         resultset.append(xmlElement);
1026
     }//while
1027
     double returnFieldTime = System.currentTimeMillis() - startReturnFieldTime;
1028
     long totalReturnFieldWarnLimit = 
1029
    	 Long.parseLong(PropertyService.getProperty("dbquery.totalReturnFieldTimeWarnLimit"));
1030

    
1031
     if (returnFieldTime > totalReturnFieldWarnLimit) {
1032
    	 logMetacat.warn("DBQuery.handleSubsetResult - Total time to get return fields is: "
1033
                           + returnFieldTime);
1034
     }
1035
     MetacatUtil.writeDebugToFile("DBQuery.handleSubsetResult - ---------------------------------------------------------------------------------------------------------------"+
1036
    		 "Total to get return fields  " + returnFieldTime);
1037
     MetacatUtil.writeDebugToDelimiteredFile("DBQuery.handleSubsetResult - "+ returnFieldTime, false);
1038
     return resultset;
1039
 }
1040

    
1041
   /**
1042
    * Get the docids already in xml_queryresult table and corresponding
1043
    * queryresultstring as a hashtable
1044
    */
1045
   private Hashtable docidsInQueryresultTable(int returnfield_id,
1046
                                              ResultDocumentSet partOfDoclist,
1047
                                              DBConnection dbconn){
1048

    
1049
         Hashtable returnValue = new Hashtable();
1050
         PreparedStatement pstmt = null;
1051
         ResultSet rs = null;
1052

    
1053
         // get partOfDoclist as string for the query
1054
         Iterator keylist = partOfDoclist.getDocids();
1055
         StringBuffer doclist = new StringBuffer();
1056
         while (keylist.hasNext())
1057
         {
1058
             doclist.append("'");
1059
             doclist.append((String) keylist.next());
1060
             doclist.append("',");
1061
         }//while
1062

    
1063

    
1064
         if (doclist.length() > 0)
1065
         {
1066
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1067

    
1068
             // the query to find out docids from xml_queryresult
1069
             String query = "select docid, queryresult_string from "
1070
                          + "xml_queryresult where returnfield_id = " +
1071
                          returnfield_id +" and docid in ("+ doclist + ")";
1072
             logMetacat.info("DBQuery.docidsInQueryresultTable - Query to get docids from xml_queryresult:"
1073
                                      + query);
1074

    
1075
             try {
1076
                 // prepare and execute the query
1077
                 pstmt = dbconn.prepareStatement(query);
1078
                 dbconn.increaseUsageCount(1);
1079
                 pstmt.execute();
1080
                 rs = pstmt.getResultSet();
1081
                 boolean tableHasRows = rs.next();
1082
                 while (tableHasRows) {
1083
                     // store the returned results in the returnValue hashtable
1084
                     String key = rs.getString(1);
1085
                     String element = rs.getString(2);
1086

    
1087
                     if(element != null){
1088
                         returnValue.put(key, element);
1089
                     } else {
1090
                         logMetacat.info("DBQuery.docidsInQueryresultTable - Null elment found ("
1091
                         + "DBQuery.docidsInQueryresultTable)");
1092
                     }
1093
                     tableHasRows = rs.next();
1094
                 }
1095
                 rs.close();
1096
                 pstmt.close();
1097
             } catch (Exception e){
1098
                 logMetacat.error("DBQuery.docidsInQueryresultTable - Error getting docids from "
1099
                                          + "queryresult: " + e.getMessage());
1100
              }
1101
         }
1102
         return returnValue;
1103
     }
1104

    
1105

    
1106
   /**
1107
    * Method to get id from xml_returnfield table
1108
    * for a given query specification
1109
    */
1110
   private int returnfield_id;
1111
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1112
                                           DBConnection dbconn){
1113
       int id = -1;
1114
       int count = 1;
1115
       PreparedStatement pstmt = null;
1116
       ResultSet rs = null;
1117
       String returnfield = qspec.getSortedReturnFieldString();
1118

    
1119
       // query for finding the id from xml_returnfield
1120
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1121
            + "WHERE returnfield_string LIKE ?";
1122
       logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Query:" + query);
1123

    
1124
       try {
1125
           // prepare and run the query
1126
           pstmt = dbconn.prepareStatement(query);
1127
           pstmt.setString(1,returnfield);
1128
           dbconn.increaseUsageCount(1);
1129
           pstmt.execute();
1130
           rs = pstmt.getResultSet();
1131
           boolean tableHasRows = rs.next();
1132

    
1133
           // if record found then increase the usage count
1134
           // else insert a new record and get the id of the new record
1135
           if(tableHasRows){
1136
               // get the id
1137
               id = rs.getInt(1);
1138
               count = rs.getInt(2) + 1;
1139
               rs.close();
1140
               pstmt.close();
1141

    
1142
               // increase the usage count
1143
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1144
                   + "' WHERE returnfield_id ='"+ id +"'";
1145
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Update:"+ query);
1146

    
1147
               pstmt = dbconn.prepareStatement(query);
1148
               dbconn.increaseUsageCount(1);
1149
               pstmt.execute();
1150
               pstmt.close();
1151

    
1152
           } else {
1153
               rs.close();
1154
               pstmt.close();
1155

    
1156
               // insert a new record
1157
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1158
                   + "VALUES (?, '1')";
1159
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Insert:"+ query);
1160
               pstmt = dbconn.prepareStatement(query);
1161
               pstmt.setString(1, returnfield);
1162
               dbconn.increaseUsageCount(1);
1163
               pstmt.execute();
1164
               pstmt.close();
1165

    
1166
               // get the id of the new record
1167
               query = "SELECT returnfield_id FROM xml_returnfield "
1168
                   + "WHERE returnfield_string LIKE ?";
1169
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField query after Insert:" + query);
1170
               pstmt = dbconn.prepareStatement(query);
1171
               pstmt.setString(1, returnfield);
1172

    
1173
               dbconn.increaseUsageCount(1);
1174
               pstmt.execute();
1175
               rs = pstmt.getResultSet();
1176
               if(rs.next()){
1177
                   id = rs.getInt(1);
1178
               } else {
1179
                   id = -1;
1180
               }
1181
               rs.close();
1182
               pstmt.close();
1183
           }
1184

    
1185
       } catch (Exception e){
1186
           logMetacat.error("DBQuery.getXmlReturnfieldsTableId - Error getting id from xml_returnfield in "
1187
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1188
                                     + e.getMessage());
1189
           id = -1;
1190
       }
1191

    
1192
       returnfield_id = id;
1193
       return count;
1194
   }
1195

    
1196

    
1197
    /*
1198
     * A method to add return field to return doclist hash table
1199
     */
1200
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1201
                                      QuerySpecification qspec,
1202
                                      String user, String[]groups,
1203
                                      DBConnection dbconn, boolean useXMLIndex,
1204
                                      String qformat)
1205
                                      throws Exception
1206
    {
1207
      PreparedStatement pstmt = null;
1208
      ResultSet rs = null;
1209
      String docid = null;
1210
      String fieldname = null;
1211
      String fieldtype = null;
1212
      String fielddata = null;
1213
      String relation = null;
1214

    
1215
      if (qspec.containsExtendedSQL())
1216
      {
1217
        qspec.setUserName(user);
1218
        qspec.setGroup(groups);
1219
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1220
        Vector results = new Vector();
1221
        Iterator keylist = docListResult.getDocids();
1222
        StringBuffer doclist = new StringBuffer();
1223
        Vector parentidList = new Vector();
1224
        Hashtable returnFieldValue = new Hashtable();
1225
        while (keylist.hasNext())
1226
        {
1227
          String key = (String)keylist.next();
1228
          doclist.append("'");
1229
          doclist.append(key);
1230
          doclist.append("',");
1231
        }
1232
        if (doclist.length() > 0)
1233
        {
1234
          Hashtable controlPairs = new Hashtable();
1235
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1236
          boolean tableHasRows = false;
1237
        
1238

    
1239
           String extendedQuery =
1240
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex);
1241
           logMetacat.info("DBQuery.addReturnfield - Extended query: " + extendedQuery);
1242

    
1243
           if(extendedQuery != null){
1244
//        	   long extendedQueryStart = System.currentTimeMillis();
1245
               pstmt = dbconn.prepareStatement(extendedQuery);
1246
               //increase dbconnection usage count
1247
               dbconn.increaseUsageCount(1);
1248
               pstmt.execute();
1249
               rs = pstmt.getResultSet();
1250
               tableHasRows = rs.next();
1251
               while (tableHasRows) {
1252
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1253
                   docid = rs.getString(1).trim();
1254
                   fieldname = rs.getString(2);
1255
                   
1256
                   if(qformat.toLowerCase().trim().equals("xml"))
1257
                   {
1258
                       byte[] b = rs.getBytes(3);
1259
                       fielddata = new String(b, 0, b.length, MetaCatServlet.DEFAULT_ENCODING);
1260
                   }
1261
                   else
1262
                   {
1263
                       fielddata = rs.getString(3);
1264
                   }
1265
                   
1266
                   //System.out.println("raw fielddata: " + fielddata);
1267
                   fielddata = MetacatUtil.normalize(fielddata);
1268
                   //System.out.println("normalized fielddata: " + fielddata);
1269
                   String parentId = rs.getString(4);
1270
                   fieldtype = rs.getString(5);
1271
                   StringBuffer value = new StringBuffer();
1272

    
1273
                   //handle case when usexmlindex is true differently
1274
                   //at one point merging the nodedata (for large text elements) was 
1275
                   //deemed unnecessary - but now it is needed.  but not for attribute nodes
1276
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1277
                	   //merge node data only for non-ATTRIBUTEs
1278
                	   if (fieldtype != null && !fieldtype.equals("ATTRIBUTE")) {
1279
	                	   //try merging the data
1280
	                	   ReturnFieldValue existingRFV =
1281
	                		   getArrayValue(parentidList, parentId);
1282
	                	   if (existingRFV != null && !existingRFV.getFieldType().equals("ATTRIBUTE")) {
1283
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1284
	                	   }
1285
                	   }
1286
                	   //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1287

    
1288
                       value.append("<param name=\"");
1289
                       value.append(fieldname);
1290
                       value.append("\">");
1291
                       value.append(fielddata);
1292
                       value.append("</param>");
1293
                       //set returnvalue
1294
                       returnValue.setDocid(docid);
1295
                       returnValue.setFieldValue(fielddata);
1296
                       returnValue.setFieldType(fieldtype);
1297
                       returnValue.setXMLFieldValue(value.toString());
1298
                       // Store it in hastable
1299
                       putInArray(parentidList, parentId, returnValue);
1300
                   }
1301
                   else {
1302
                       
1303
                       // need to merge nodedata if they have same parent id and
1304
                       // node type is text
1305
                       fielddata = (String) ( (ReturnFieldValue)
1306
                                             getArrayValue(
1307
                           parentidList, parentId)).getFieldValue()
1308
                           + fielddata;
1309
                       //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1310
                       value.append("<param name=\"");
1311
                       value.append(fieldname);
1312
                       value.append("\">");
1313
                       value.append(fielddata);
1314
                       value.append("</param>");
1315
                       returnValue.setDocid(docid);
1316
                       returnValue.setFieldValue(fielddata);
1317
                       returnValue.setFieldType(fieldtype);
1318
                       returnValue.setXMLFieldValue(value.toString());
1319
                       // remove the old return value from paretnidList
1320
                       parentidList.remove(parentId);
1321
                       // store the new return value in parentidlit
1322
                       putInArray(parentidList, parentId, returnValue);
1323
                   }
1324
                   tableHasRows = rs.next();
1325
               } //while
1326
               rs.close();
1327
               pstmt.close();
1328

    
1329
               // put the merger node data info into doclistReult
1330
               Enumeration xmlFieldValue = (getElements(parentidList)).
1331
                   elements();
1332
               while (xmlFieldValue.hasMoreElements()) {
1333
                   ReturnFieldValue object =
1334
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1335
                   docid = object.getDocid();
1336
                   if (docListResult.containsDocid(docid)) {
1337
                       String removedelement = (String) docListResult.
1338
                           remove(docid);
1339
                       docListResult.
1340
                           addResultDocument(new ResultDocument(docid,
1341
                               removedelement + object.getXMLFieldValue()));
1342
                   }
1343
                   else {
1344
                       docListResult.addResultDocument(
1345
                         new ResultDocument(docid, object.getXMLFieldValue()));
1346
                   }
1347
               } //while
1348
//               double docListResultEnd = System.currentTimeMillis() / 1000;
1349
//               logMetacat.warn(
1350
//                   "Time to prepare ResultDocumentSet after"
1351
//                   + " execute extended query: "
1352
//                   + (docListResultEnd - extendedQueryEnd));
1353
           }
1354
       }//if doclist lenght is great than zero
1355
     }//if has extended query
1356

    
1357
      return docListResult;
1358
    }//addReturnfield
1359

    
1360
  
1361
  /**
1362
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1363
   * string as a param instead of a hashtable.
1364
   *
1365
   * @param xmlquery a string representing a query.
1366
   */
1367
   private  String transformQuery(String xmlquery)
1368
   {
1369
     xmlquery = xmlquery.trim();
1370
     int index = xmlquery.indexOf("?>");
1371
     if (index != -1)
1372
     {
1373
       return xmlquery.substring(index + 2, xmlquery.length());
1374
     }
1375
     else
1376
     {
1377
       return xmlquery;
1378
     }
1379
   }
1380
   
1381
   /*
1382
    * Method to store query string and result xml string into query result
1383
    * cache. If the size alreay reache the limitation, the cache will be
1384
    * cleared first, then store them.
1385
    */
1386
   private void storeQueryResultIntoCache(String query, String resultXML)
1387
   {
1388
	   synchronized (queryResultCache)
1389
	   {
1390
		   if (queryResultCache.size() >= QUERYRESULTCACHESIZE)
1391
		   {
1392
			   queryResultCache.clear();
1393
		   }
1394
		   queryResultCache.put(query, resultXML);
1395
		   
1396
	   }
1397
   }
1398
   
1399
   /*
1400
    * Method to get result xml string from query result cache. 
1401
    * Note: the returned string can be null.
1402
    */
1403
   private String getResultXMLFromCache(String query)
1404
   {
1405
	   String resultSet = null;
1406
	   synchronized (queryResultCache)
1407
	   {
1408
          try
1409
          {
1410
        	 logMetacat.info("DBQuery.getResultXMLFromCache - Get query from cache");
1411
		     resultSet = (String)queryResultCache.get(query);
1412
		   
1413
          }
1414
          catch (Exception e)
1415
          {
1416
        	  resultSet = null;
1417
          }
1418
		   
1419
	   }
1420
	   return resultSet;
1421
   }
1422
   
1423
   /**
1424
    * Method to clear the query result cache.
1425
    */
1426
   public static void clearQueryResultCache()
1427
   {
1428
	   synchronized (queryResultCache)
1429
	   {
1430
		   queryResultCache.clear();
1431
	   }
1432
   }
1433

    
1434

    
1435
    /*
1436
     * A method to search if Vector contains a particular key string
1437
     */
1438
    private boolean containsKey(Vector parentidList, String parentId)
1439
    {
1440

    
1441
        Vector tempVector = null;
1442

    
1443
        for (int count = 0; count < parentidList.size(); count++) {
1444
            tempVector = (Vector) parentidList.get(count);
1445
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1446
        }
1447
        return false;
1448
    }
1449
    
1450
    /*
1451
     * A method to put key and value in Vector
1452
     */
1453
    private void putInArray(Vector parentidList, String key,
1454
            ReturnFieldValue value)
1455
    {
1456

    
1457
        Vector tempVector = null;
1458
        //only filter if the field type is NOT an attribute (say, for text)
1459
        String fieldType = value.getFieldType();
1460
        if (fieldType != null && !fieldType.equals("ATTRIBUTE")) {
1461
        
1462
	        for (int count = 0; count < parentidList.size(); count++) {
1463
	            tempVector = (Vector) parentidList.get(count);
1464
	
1465
	            if (key.compareTo((String) tempVector.get(0)) == 0) {
1466
	                tempVector.remove(1);
1467
	                tempVector.add(1, value);
1468
	                return;
1469
	            }
1470
	        }
1471
        }
1472

    
1473
        tempVector = new Vector();
1474
        tempVector.add(0, key);
1475
        tempVector.add(1, value);
1476
        parentidList.add(tempVector);
1477
        return;
1478
    }
1479

    
1480
    /*
1481
     * A method to get value in Vector given a key
1482
     */
1483
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1484
    {
1485

    
1486
        Vector tempVector = null;
1487

    
1488
        for (int count = 0; count < parentidList.size(); count++) {
1489
            tempVector = (Vector) parentidList.get(count);
1490

    
1491
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1492
                    .get(1); }
1493
        }
1494
        return null;
1495
    }
1496

    
1497
    /*
1498
     * A method to get enumeration of all values in Vector
1499
     */
1500
    private Vector getElements(Vector parentidList)
1501
    {
1502
        Vector enumVector = new Vector();
1503
        Vector tempVector = null;
1504

    
1505
        for (int count = 0; count < parentidList.size(); count++) {
1506
            tempVector = (Vector) parentidList.get(count);
1507

    
1508
            enumVector.add(tempVector.get(1));
1509
        }
1510
        return enumVector;
1511
    }
1512

    
1513
  
1514

    
1515
    /*
1516
     * A method to create a query to get owner's docid list
1517
     */
1518
    private String getOwnerQuery(String owner)
1519
    {
1520
        if (owner != null) {
1521
            owner = owner.toLowerCase();
1522
        }
1523
        StringBuffer self = new StringBuffer();
1524

    
1525
        self.append("SELECT docid,docname,doctype,");
1526
        self.append("date_created, date_updated, rev ");
1527
        self.append("FROM xml_documents WHERE docid IN (");
1528
        self.append("(");
1529
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1530
        self.append("nodedata LIKE '%%%' ");
1531
        self.append(") \n");
1532
        self.append(") ");
1533
        self.append(" AND (");
1534
        self.append(" lower(user_owner) = '" + owner + "'");
1535
        self.append(") ");
1536
        return self.toString();
1537
    }
1538

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

    
1561

    
1562

    
1563
        if (params.containsKey("meta_file_id")) {
1564
            query.append("<meta_file_id>");
1565
            query.append(((String[]) params.get("meta_file_id"))[0]);
1566
            query.append("</meta_file_id>");
1567
        }
1568

    
1569
        if (params.containsKey("returndoctype")) {
1570
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1571
            for (int i = 0; i < returnDoctypes.length; i++) {
1572
                String doctype = (String) returnDoctypes[i];
1573

    
1574
                if (!doctype.equals("any") && !doctype.equals("ANY")
1575
                        && !doctype.equals("")) {
1576
                    query.append("<returndoctype>").append(doctype);
1577
                    query.append("</returndoctype>");
1578
                }
1579
            }
1580
        }
1581

    
1582
        if (params.containsKey("filterdoctype")) {
1583
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1584
            for (int i = 0; i < filterDoctypes.length; i++) {
1585
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1586
                query.append("</filterdoctype>");
1587
            }
1588
        }
1589

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

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

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

    
1614
        //allows the dynamic switching of boolean operators
1615
        if (params.containsKey("operator")) {
1616
            query.append("<querygroup operator=\""
1617
                    + ((String[]) params.get("operator"))[0] + "\">");
1618
        } else { //the default operator is UNION
1619
            query.append("<querygroup operator=\"UNION\">");
1620
        }
1621

    
1622
        if (params.containsKey("casesensitive")) {
1623
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1624
        } else {
1625
            casesensitive = "false";
1626
        }
1627

    
1628
        if (params.containsKey("searchmode")) {
1629
            searchmode = ((String[]) params.get("searchmode"))[0];
1630
        } else {
1631
            searchmode = "contains";
1632
        }
1633

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

    
1651
        //this while loop finds the rest of the parameters
1652
        //and attempts to query for the field specified
1653
        //by the parameter.
1654
        elements = params.elements();
1655
        keys = params.keys();
1656
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1657
            nextkey = keys.nextElement();
1658
            nextelement = elements.nextElement();
1659

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

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

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

    
1722
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1723
            xmlquery.append("<returndoctype>");
1724
            xmlquery.append(doctype).append("</returndoctype>");
1725
        }
1726

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

    
1740
        return (xmlquery.toString());
1741
    }
1742

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

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

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

    
1783
        // Check the parameter
1784
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1785

    
1786
        //the query stirng
1787
        String query = "SELECT subject, object from xml_relation where docId = ?";
1788
        try {
1789
            dbConn = DBConnectionPool
1790
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1791
            serialNumber = dbConn.getCheckOutSerialNumber();
1792
            pStmt = dbConn.prepareStatement(query);
1793
            //bind the value to query
1794
            pStmt.setString(1, dataPackageDocid);
1795

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

    
1811
                //don't put the duplicate docId into the vector
1812
                if (!docIdList.contains(docIdInSubjectField)) {
1813
                    docIdList.add(docIdInSubjectField);
1814
                }
1815

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

    
1843
    /**
1844
     * Get all docIds list for a data packadge
1845
     *
1846
     * @param dataPackageDocid, the string in docId field of xml_relation table
1847
     */
1848
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1849
    {
1850

    
1851
        Vector docIdList = new Vector();//return value
1852
        Vector tripleList = null;
1853
        String xml = null;
1854

    
1855
        // Check the parameter
1856
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1857

    
1858
        try {
1859
            //initial a documentImpl object
1860
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1861
            //transfer to documentImpl object to string
1862
            xml = packageDocument.toString();
1863

    
1864
            //create a tripcollection object
1865
            TripleCollection tripleForPackage = new TripleCollection(
1866
                    new StringReader(xml));
1867
            //get the vetor of triples
1868
            tripleList = tripleForPackage.getCollection();
1869

    
1870
            for (int i = 0; i < tripleList.size(); i++) {
1871
                //put subject docid into docIdlist without duplicate
1872
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1873
                        .getSubject())) {
1874
                    //put subject docid into docIdlist
1875
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1876
                }
1877
                //put object docid into docIdlist without duplicate
1878
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1879
                        .getObject())) {
1880
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1881
                }
1882
            }//for
1883
        }//try
1884
        catch (Exception e) {
1885
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - General error: "
1886
                    + e.getMessage());
1887
        }//catch
1888

    
1889
        // return result
1890
        return docIdList;
1891
    }//getDocidListForPackageInXMLRevisions()
1892

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

    
1945
    public String getOperator() {
1946
		return operator;
1947
	}
1948

    
1949
    /**
1950
     * Specifies if and how docid overrides should be included in the general query
1951
     * @param operator null, UNION, or INTERSECT (see QueryGroup)
1952
     */
1953
	public void setOperator(String operator) {
1954
		this.operator = operator;
1955
	}
1956

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

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

    
2006
        }//try
2007
        catch (SQLException e) {
2008
            logMetacat.error("DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
2009
                            + e.getMessage());
2010
            throw e;
2011
        }//catch
2012
        finally {
2013
            try {
2014
                pStmt.close();
2015
            }//try
2016
            catch (SQLException ee) {
2017
                logMetacat.error(
2018
                        "DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
2019
                                + ee.getMessage());
2020
            }//catch
2021
            finally {
2022
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2023
            }//finally
2024
        }//finally
2025
        return rev;
2026
    }//getCurrentRevFromXMLDoumentsTable
2027

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

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

    
2053
    }//addDocToZipOutputStream()
2054

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

    
2065
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2066
            throws McdbException, Exception
2067
    {
2068
        //Connection dbConn=null;
2069
        Vector documentImplList = new Vector();
2070
        int rev = 0;
2071

    
2072
        // Check the parameter
2073
        if (docIdList.isEmpty()) { return documentImplList; }//if
2074

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

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

    
2092
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2093
                        + PropertyService.getProperty("document.accNumSeparator") + rev;
2094

    
2095
                //create new documentImpl object
2096
                DocumentImpl documentImplObject = new DocumentImpl(
2097
                        docidPlusVersion);
2098
                //add them to vector
2099
                documentImplList.add(documentImplObject);
2100
            }//try
2101
            catch (Exception e) {
2102
                logMetacat.error("DBQuery.getCurrentAllDocumentImpl - General error: "
2103
                        + e.getMessage());
2104
                // continue the for loop
2105
                continue;
2106
            }
2107
        }//for
2108
        return documentImplList;
2109
    }
2110

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

    
2127
        // Check the parameter
2128
        if (docIdList.isEmpty()) { return documentImplList; }//if
2129

    
2130
        //for every docid in vector
2131
        for (int i = 0; i < docIdList.size(); i++) {
2132

    
2133
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2134

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

    
2160
        }//for
2161
        return documentImplList;
2162
    }//getOldVersionAllDocumentImple
2163

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

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

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

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

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

    
2243
                //for metadata xml title
2244
                htmlDoc.append("<h2>");
2245
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2246
                        .getDocID());
2247
                //htmlDoc.append(".");
2248
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2249
                htmlDoc.append("</h2>");
2250
                //do the actual transform
2251
                StringWriter docString = new StringWriter();
2252
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2253
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2254
                        "-//W3C//HTML//EN", "html", docString, null, null);
2255
                htmlDoc.append(docString.toString());
2256
                htmlDoc.append("<br><br><hr><br><br>");
2257
            }//if
2258
            else { //this is a data file so we should link to it in the html
2259
                htmlDoc.append("<a href=\"");
2260
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2261
                        .getDocID();
2262
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2263
                htmlDoc.append("Data File: ");
2264
                htmlDoc.append(dataFileid).append("</a><br>");
2265
                htmlDoc.append("<br><hr><br>");
2266
            }//else
2267
        }//for
2268
        htmlDoc.append("</body></html>");
2269
        // use standard encoding even though the different docs might have use different encodings,
2270
        // the String objects in java should be correct and able to be encoded as the same Metacat default
2271
        byteString = htmlDoc.toString().getBytes(MetaCatServlet.DEFAULT_ENCODING);
2272
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2273
        zEntry.setSize(byteString.length);
2274
        zipOut.putNextEntry(zEntry);
2275
        zipOut.write(byteString, 0, byteString.length);
2276
        zipOut.closeEntry();
2277
        //dbConn.close();
2278

    
2279
    }//addHtmlSummaryToZipOutputStream
2280

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

    
2305
        String docId = null;
2306
        int version = -5;
2307
        // Docid without revision
2308
        docId = DocumentUtil.getDocIdFromString(docIdString);
2309
        // revision number
2310
        version = DocumentUtil.getVersionFromString(docIdString);
2311

    
2312
        //check if the reqused docId is a data package id
2313
        if (!isDataPackageId(docId)) {
2314

    
2315
            /*
2316
             * Exception e = new Exception("The request the doc id "
2317
             * +docIdString+ " is not a data package id");
2318
             */
2319

    
2320
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2321
            // zip
2322
            //up the single document and return the zip file.
2323
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2324

    
2325
                Exception e = new Exception("User " + user
2326
                        + " does not have permission"
2327
                        + " to export the data package " + docIdString);
2328
                throw e;
2329
            }
2330

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

    
2348
            zOut.finish(); //terminate the zip file
2349
            return zOut;
2350
        }
2351
        // Check the permission of user
2352
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2353

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

    
2379
            }//if
2380
            else if (version > currentVersion || version < -1) {
2381
                throw new Exception("The user specified docid: " + docId + "."
2382
                        + version + " doesn't exist");
2383
            }//else if
2384
            else //for an old version
2385
            {
2386

    
2387
                rootName = docIdString
2388
                        + PropertyService.getProperty("document.accNumSeparator") + "package";
2389
                //get the whole id list for data packadge
2390
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2391

    
2392
                //get the whole documentImple object
2393
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2394
            }//else
2395

    
2396
            // Make sure documentImplist is not empty
2397
            if (documentImplList.isEmpty()) { throw new Exception(
2398
                    "Couldn't find component for data package: " + packageId); }//if
2399

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

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

    
2459
                        }//if
2460
                        else {
2461
                            //it is data file
2462
                            addDataFileToZipOutputStream(docImpls, zOut,
2463
                                    rootName);
2464
                            htmlDocumentImplList.add(docImpls);
2465
                        }//else
2466
                    }//if
2467
                }//else
2468
            }//for
2469

    
2470
            //add html summary file
2471
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2472
                    rootName);
2473
            zOut.finish(); //terminate the zip file
2474
            //dbConn.close();
2475
            return zOut;
2476
        }//else
2477
    }//getZippedPackage()
2478

    
2479
    private class ReturnFieldValue
2480
    {
2481

    
2482
        private String docid = null; //return field value for this docid
2483

    
2484
        private String fieldValue = null;
2485

    
2486
        private String xmlFieldValue = null; //return field value in xml
2487
                                             // format
2488
        private String fieldType = null; //ATTRIBUTE, TEXT...
2489

    
2490
        public void setDocid(String myDocid)
2491
        {
2492
            docid = myDocid;
2493
        }
2494

    
2495
        public String getDocid()
2496
        {
2497
            return docid;
2498
        }
2499

    
2500
        public void setFieldValue(String myValue)
2501
        {
2502
            fieldValue = myValue;
2503
        }
2504

    
2505
        public String getFieldValue()
2506
        {
2507
            return fieldValue;
2508
        }
2509

    
2510
        public void setXMLFieldValue(String xml)
2511
        {
2512
            xmlFieldValue = xml;
2513
        }
2514

    
2515
        public String getXMLFieldValue()
2516
        {
2517
            return xmlFieldValue;
2518
        }
2519
        
2520
        public void setFieldType(String myType)
2521
        {
2522
            fieldType = myType;
2523
        }
2524

    
2525
        public String getFieldType()
2526
        {
2527
            return fieldType;
2528
        }
2529

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