Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *
12
 *   '$Author: tao $'
13
 *     '$Date: 2011-12-13 11:06:02 -0800 (Tue, 13 Dec 2011) $'
14
 * '$Revision: 6774 $'
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.sql.Timestamp;
49
import java.util.ArrayList;
50
import java.util.Date;
51
import java.util.Enumeration;
52
import java.util.Hashtable;
53
import java.util.Iterator;
54
import java.util.List;
55
import java.util.StringTokenizer;
56
import java.util.Vector;
57
import java.util.zip.ZipEntry;
58
import java.util.zip.ZipOutputStream;
59

    
60
import javax.servlet.ServletOutputStream;
61
import javax.servlet.http.HttpServletResponse;
62

    
63
import org.apache.log4j.Logger;
64

    
65
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
66
import edu.ucsb.nceas.metacat.database.DBConnection;
67
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
68
import edu.ucsb.nceas.metacat.properties.PropertyService;
69
import edu.ucsb.nceas.metacat.util.AuthUtil;
70
import edu.ucsb.nceas.metacat.util.DocumentUtil;
71
import edu.ucsb.nceas.metacat.util.MetacatUtil;
72
import edu.ucsb.nceas.morpho.datapackage.Triple;
73
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
74
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
75

    
76

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

    
86
    static final int ALL = 1;
87

    
88
    static final int WRITE = 2;
89

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

    
97
    //private Connection conn = null;
98
    private String parserName = null;
99

    
100
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
101

    
102
    /** true if the metacat spatial option is installed **/
103
    private final boolean METACAT_SPATIAL = true;
104

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

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

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

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

    
159
                // Time the request if asked for
160
                double startTime = System.currentTimeMillis();
161

    
162
                // Open a connection to the database
163
                //Connection dbconn = util.openDBConnection();
164

    
165
                double connTime = System.currentTimeMillis();
166

    
167
                // Execute the query
168
                DBQuery queryobj = new DBQuery();
169
                Reader xml = new InputStreamReader(new FileInputStream(new File(xmlfile)));
170
                Hashtable nodelist = null;
171
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
172

    
173
                // Print the reulting document listing
174
                StringBuffer result = new StringBuffer();
175
                String document = null;
176
                String docid = null;
177
                result.append("<?xml version=\"1.0\"?>\n");
178
                result.append("<resultset>\n");
179

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

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

    
215
            } catch (Exception e) {
216
                System.err.println("Error in DBQuery.main");
217
                System.err.println(e.getMessage());
218
                e.printStackTrace(System.err);
219
            }
220
        }
221
    }
222

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

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

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

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

    
316
  }
317

    
318

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

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

    
383

    
384

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

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

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

    
438
      }//else
439

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

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

    
485
    //try to get the cached version first    
486
    // Hashtable sessionHash = MetaCatServlet.getSessionHash();
487
    // HttpSession sess = (HttpSession)sessionHash.get(sessionid);
488

    
489
    
490
    resultset.append("<?xml version=\"1.0\"?>\n");
491
    resultset.append("<resultset>\n");
492
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
493
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
494
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
495
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
496

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

    
512
        //checkout the dbconnection
513
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
514
        serialNumber = dbconn.getCheckOutSerialNumber();
515

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

    
574
    //default to returning the whole resultset
575
    return resultset;
576
  }//createResultDocuments
577

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

    
627
      /*
628
       * Check the docidOverride Vector
629
       * if defined, we bypass the qspec.printSQL() method
630
       * and contruct a simpler query based on a 
631
       * list of docids rather than a bunch of subselects
632
       */
633
      // keep track of the values we add as prepared statement question marks (?)
634
	  List<Object> docidValues = new ArrayList<Object>();
635
      if ( givenDocids == null || givenDocids.size() == 0 ) {
636
          query = qspec.printSQL(useXMLIndex, docidValues);
637
          parameterValues.addAll(docidValues);
638
      } else {
639
    	  // condition for the docids
640
    	  List<Object> docidConditionValues = new ArrayList<Object>();
641
    	  StringBuffer docidCondition = new StringBuffer();
642
    	  docidCondition.append( " docid IN (" );
643
          for (int i = 0; i < givenDocids.size(); i++) {  
644
        	  docidCondition.append("?");
645
        	  if (i < givenDocids.size()-1) {
646
        		  docidCondition.append(",");
647
        	  }
648
        	  docidConditionValues.add((String)givenDocids.elementAt(i));
649
          }
650
          docidCondition.append( ") " );
651
		  
652
    	  // include the docids, either exclusively, or in conjuction with the query
653
    	  if (operator == null) {
654
    		  query = "SELECT docid, docname, doctype, date_created, date_updated, rev FROM xml_documents WHERE";
655
              query = query + docidCondition.toString();
656
              parameterValues.addAll(docidConditionValues);
657
    	  } else {
658
    		  // start with the keyword query, but add conditions
659
              query = qspec.printSQL(useXMLIndex, docidValues);
660
              parameterValues.addAll(docidValues);
661
              String myOperator = "";
662
              if (!query.endsWith("WHERE")) {
663
	              if (operator.equalsIgnoreCase(QueryGroup.UNION)) {
664
	            	  myOperator =  " OR ";
665
	              }
666
	              else {
667
	            	  myOperator =  " AND ";
668
	              }
669
              }
670
              query = query + myOperator + docidCondition.toString();
671
              parameterValues.addAll(docidConditionValues);
672

    
673
    	  }
674
      } 
675
      // we don't actually use this query for anything
676
      List<Object> ownerValues = new ArrayList<Object>();
677
      String ownerQuery = getOwnerQuery(user, ownerValues);
678
      //logMetacat.debug("query: " + query);
679
      logMetacat.debug("DBQuery.findResultDoclist - owner query: " + ownerQuery);
680
      // if query is not the owner query, we need to check the permission
681
      // otherwise we don't need (owner has all permission by default)
682
      if (!query.equals(ownerQuery))
683
      {
684
        // set user name and group
685
        qspec.setUserName(user);
686
        qspec.setGroup(groups);
687
        // Get access query
688
        String accessQuery = qspec.getAccessQuery();
689
        if(!query.endsWith("WHERE")){
690
            query = query + accessQuery;
691
        } else {
692
            query = query + accessQuery.substring(4, accessQuery.length());
693
        }
694
        
695
      }
696
      logMetacat.debug("DBQuery.findResultDoclist - final selection query: " + query);
697
      
698
    
699
      pstmt = dbconn.prepareStatement(query);     
700
      // set all the values we have collected 
701
      pstmt = setPreparedStatementValues(parameterValues, pstmt);
702
      
703
      String queryCacheKey = null;
704
      // we only get cache for public
705
      if (user != null && user.equalsIgnoreCase("public") 
706
         && pagesize == 0 && PropertyService.getProperty("database.queryCacheOn").equals("true"))
707
      {
708
          queryCacheKey = pstmt.toString() +qspec.getReturnDocList()+qspec.getReturnFieldList();
709
          String cachedResult = getResultXMLFromCache(queryCacheKey);
710
          logMetacat.debug("=======DBQuery.findResultDoclist - The key of query cache is " + queryCacheKey);
711
          //System.out.println("==========the string from cache is "+cachedResult);
712
          if (cachedResult != null)
713
          {
714
          logMetacat.info("DBQuery.findResultDoclist - result from cache !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
715
           if (out != null)
716
             {
717
                 out.write(cachedResult);
718
             }
719
           resultsetBuffer.append(cachedResult);
720
           pstmt.close();
721
           return resultsetBuffer;
722
          }
723
      }
724
      
725
      startTime = System.currentTimeMillis() / 1000;
726
      logMetacat.debug("Prepared statement after setting parameter values: " + pstmt.toString());
727
      rs = pstmt.executeQuery();
728

    
729
      double queryExecuteTime = System.currentTimeMillis() / 1000;
730
      logMetacat.debug("DBQuery.findResultDoclist - Time to execute select docid query is "
731
                    + (queryExecuteTime - startTime));
732
      MetacatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
733
              + (queryExecuteTime - startTime));
734
      MetacatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
735

    
736
      boolean tableHasRows = rs.next();
737
      
738
      if(pagesize == 0)
739
      { //this makes sure we get all results if there is no paging
740
        pagesize = NONPAGESIZE;
741
        pagestart = NONPAGESIZE;
742
      } 
743
      
744
      int currentIndex = 0;
745
      while (tableHasRows)
746
      {
747
        logMetacat.debug("DBQuery.findResultDoclist - getting result: " + currentIndex);
748
        docid = rs.getString(1).trim();
749
        logMetacat.debug("DBQuery.findResultDoclist -  processing: " + docid);
750
        docname = rs.getString(2);
751
        doctype = rs.getString(3);
752
        logMetacat.debug("DBQuery.findResultDoclist - processing: " + doctype);
753
        createDate = rs.getString(4);
754
        updateDate = rs.getString(5);
755
        rev = rs.getInt(6);
756
        
757
         Vector returndocVec = qspec.getReturnDocList();
758
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
759
        {
760
          logMetacat.debug("DBQuery.findResultDoclist - NOT Back tracing now...");
761
           document = new StringBuffer();
762

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

    
857
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
858
     if (out != null)
859
     {
860
         out.write("\n<lastpage>" + lastpage + "</lastpage>\n");
861
     }
862
     
863
     // now we only cached none-paged query and user is public
864
     if (user != null && user.equalsIgnoreCase("public") 
865
    		 && pagesize == NONPAGESIZE && PropertyService.getProperty("database.queryCacheOn").equals("true"))
866
     {
867
       //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
868
  	   storeQueryResultIntoCache(queryCacheKey, resultsetBuffer.toString());
869
     }
870
          
871
     return resultsetBuffer;
872
    }//findReturnDoclist
873

    
874

    
875
    /*
876
     * Send completed search hashtable(part of reulst)to output stream
877
     * and buffer into a buffer stream
878
     */
879
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
880
                                           StringBuffer resultset,
881
                                           Writer out, ResultDocumentSet partOfDoclist,
882
                                           String user, String[]groups,
883
                                       DBConnection dbconn, boolean useXMLIndex,
884
                                       String qformat)
885
                                       throws Exception
886
   {
887
     double startReturnFieldTime = System.currentTimeMillis();
888
     // check if there is a record in xml_returnfield
889
     // and get the returnfield_id and usage count
890
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
891
     boolean enterRecords = false;
892

    
893
     // get value of database.xmlReturnfieldCount
894
     int count = (new Integer(PropertyService
895
                            .getProperty("database.xmlReturnfieldCount")))
896
                            .intValue();
897

    
898
     // set enterRecords to true if usage_count is more than the offset
899
     // specified in metacat.properties
900
     if(usage_count > count){
901
         enterRecords = true;
902
     }
903

    
904
     if(returnfield_id < 0){
905
         logMetacat.warn("DBQuery.handleSubsetResult - Error in getting returnfield id from"
906
                                  + "xml_returnfield table");
907
         enterRecords = false;
908
     }
909

    
910
     // get the hashtable containing the docids that already in the
911
     // xml_queryresult table
912
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist before"
913
                             + " docidsInQueryresultTable(): "
914
                             + partOfDoclist.size());
915
     long startGetReturnValueFromQueryresultable = System.currentTimeMillis();
916
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
917
                                                        partOfDoclist, dbconn);
918

    
919
     // remove the keys in queryresultDocList from partOfDoclist
920
     Enumeration _keys = queryresultDocList.keys();
921
     while (_keys.hasMoreElements()){
922
         partOfDoclist.remove((String)_keys.nextElement());
923
     }
924
     
925
     long queryResultReturnValuetime = System.currentTimeMillis() - startGetReturnValueFromQueryresultable;
926
     long queryResultWarnLimit = 
927
    	 Long.parseLong(PropertyService.getProperty("dbquery.findQueryResultsTimeWarnLimit"));
928
     
929
     if (queryResultReturnValuetime > queryResultWarnLimit) {
930
    	 logMetacat.warn("DBQuery.handleSubsetResult - Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
931
    		 queryResultReturnValuetime);
932
     }
933
     MetacatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
934
    		 queryResultReturnValuetime);
935
     MetacatUtil.writeDebugToDelimiteredFile(" " + queryResultReturnValuetime,false);
936
     
937
     long startExtendedQuery = System.currentTimeMillis();
938
     // backup the keys-elements in partOfDoclist to check later
939
     // if the doc entry is indexed yet
940
     Hashtable partOfDoclistBackup = new Hashtable();
941
     Iterator itt = partOfDoclist.getDocids();
942
     while (itt.hasNext()){
943
       Object key = itt.next();
944
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
945
     }
946

    
947
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist after"
948
                             + " docidsInQueryresultTable(): "
949
                             + partOfDoclist.size());
950

    
951
     //add return fields for the documents in partOfDoclist
952
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
953
                                        dbconn, useXMLIndex, qformat);
954
     long extendedQueryRunTime = startExtendedQuery - System.currentTimeMillis();
955
     long extendedQueryWarnLimit = 
956
    	 Long.parseLong(PropertyService.getProperty("dbquery.extendedQueryRunTimeWarnLimit"));
957
  
958
     if (extendedQueryRunTime > extendedQueryWarnLimit) {
959
    	 logMetacat.warn("DBQuery.handleSubsetResult - Get fields from index and node table (Part2 in return fields) "
960
        		                                          + extendedQueryRunTime);
961
     }
962
     MetacatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
963
             + extendedQueryRunTime);
964
     MetacatUtil.writeDebugToDelimiteredFile(" "
965
             + extendedQueryRunTime, false);
966
     //add relationship part part docid list for the documents in partOfDocList
967
     //partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
968

    
969
     long startStoreReturnField = System.currentTimeMillis();
970
     Iterator keys = partOfDoclist.getDocids();
971
     String key = null;
972
     String element = null;
973
     String query = null;
974
     int offset = (new Integer(PropertyService
975
                               .getProperty("database.queryresultStringLength")))
976
                               .intValue();
977
     while (keys.hasNext())
978
     {
979
         key = (String) keys.next();
980
         element = (String)partOfDoclist.get(key);
981
         
982
	 // check if the enterRecords is true, elements is not null, element's
983
         // length is less than the limit of table column and if the document
984
         // has been indexed already
985
         if(enterRecords && element != null
986
		&& element.length() < offset
987
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
988
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
989
                 + "queryresult_string) VALUES (?, ?, ?)";
990

    
991
             PreparedStatement pstmt = null;
992
             pstmt = dbconn.prepareStatement(query);
993
             pstmt.setInt(1, returnfield_id);
994
             pstmt.setString(2, key);
995
             pstmt.setString(3, element);
996
            
997
             dbconn.increaseUsageCount(1);
998
             try
999
             {
1000
            	 pstmt.execute();
1001
             }
1002
             catch(Exception e)
1003
             {
1004
            	 logMetacat.warn("DBQuery.handleSubsetResult - couldn't insert the element to xml_queryresult table "+e.getLocalizedMessage());
1005
             }
1006
             finally
1007
             {
1008
                pstmt.close();
1009
             }
1010
         }
1011
        
1012
         // A string with element
1013
         String xmlElement = "  <document>" + element + "</document>";
1014

    
1015
         //send single element to output
1016
         if (out != null)
1017
         {
1018
             out.write(xmlElement);
1019
         }
1020
         resultset.append(xmlElement);
1021
     }//while
1022
     
1023
     double storeReturnFieldTime = System.currentTimeMillis() - startStoreReturnField;
1024
     long storeReturnFieldWarnLimit = 
1025
    	 Long.parseLong(PropertyService.getProperty("dbquery.storeReturnFieldTimeWarnLimit"));
1026

    
1027
     if (storeReturnFieldTime > storeReturnFieldWarnLimit) {
1028
    	 logMetacat.warn("DBQuery.handleSubsetResult - Time to store new return fields into xml_queryresult table (Part4 in return fields) "
1029
                   + storeReturnFieldTime);
1030
     }
1031
     MetacatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
1032
             + storeReturnFieldTime);
1033
     MetacatUtil.writeDebugToDelimiteredFile(" " + storeReturnFieldTime, false);
1034
     
1035
     Enumeration keysE = queryresultDocList.keys();
1036
     while (keysE.hasMoreElements())
1037
     {
1038
         key = (String) keysE.nextElement();
1039
         element = (String)queryresultDocList.get(key);
1040
         // A string with element
1041
         String xmlElement = "  <document>" + element + "</document>";
1042
         //send single element to output
1043
         if (out != null)
1044
         {
1045
             out.write(xmlElement);
1046
         }
1047
         resultset.append(xmlElement);
1048
     }//while
1049
     double returnFieldTime = System.currentTimeMillis() - startReturnFieldTime;
1050
     long totalReturnFieldWarnLimit = 
1051
    	 Long.parseLong(PropertyService.getProperty("dbquery.totalReturnFieldTimeWarnLimit"));
1052

    
1053
     if (returnFieldTime > totalReturnFieldWarnLimit) {
1054
    	 logMetacat.warn("DBQuery.handleSubsetResult - Total time to get return fields is: "
1055
                           + returnFieldTime);
1056
     }
1057
     MetacatUtil.writeDebugToFile("DBQuery.handleSubsetResult - ---------------------------------------------------------------------------------------------------------------"+
1058
    		 "Total to get return fields  " + returnFieldTime);
1059
     MetacatUtil.writeDebugToDelimiteredFile("DBQuery.handleSubsetResult - "+ returnFieldTime, false);
1060
     return resultset;
1061
 }
1062

    
1063
   /**
1064
    * Get the docids already in xml_queryresult table and corresponding
1065
    * queryresultstring as a hashtable
1066
    */
1067
   private Hashtable docidsInQueryresultTable(int returnfield_id,
1068
                                              ResultDocumentSet partOfDoclist,
1069
                                              DBConnection dbconn){
1070

    
1071
         Hashtable returnValue = new Hashtable();
1072
         PreparedStatement pstmt = null;
1073
         ResultSet rs = null;
1074
         
1075
         // keep track of parameter values
1076
         List<Object> parameterValues = new ArrayList<Object>();
1077

    
1078
         // get partOfDoclist as string for the query
1079
         Iterator keylist = partOfDoclist.getDocids();
1080
         StringBuffer doclist = new StringBuffer();
1081
         while (keylist.hasNext())
1082
         {
1083
             doclist.append("?,");
1084
             parameterValues.add((String) keylist.next());
1085
         }//while
1086

    
1087
         if (doclist.length() > 0)
1088
         {
1089
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1090

    
1091
             // the query to find out docids from xml_queryresult
1092
             String query = "select docid, queryresult_string from "
1093
                          + "xml_queryresult where returnfield_id = " +
1094
                          returnfield_id +" and docid in ("+ doclist + ")";
1095
             logMetacat.info("DBQuery.docidsInQueryresultTable - Query to get docids from xml_queryresult:"
1096
                                      + query);
1097

    
1098
             try {
1099
                 // prepare and execute the query
1100
                 pstmt = dbconn.prepareStatement(query);
1101
                 // bind parameter values
1102
                 pstmt = setPreparedStatementValues(parameterValues, pstmt);
1103
                 
1104
                 dbconn.increaseUsageCount(1);
1105
                 pstmt.execute();
1106
                 rs = pstmt.getResultSet();
1107
                 boolean tableHasRows = rs.next();
1108
                 while (tableHasRows) {
1109
                     // store the returned results in the returnValue hashtable
1110
                     String key = rs.getString(1);
1111
                     String element = rs.getString(2);
1112

    
1113
                     if(element != null){
1114
                         returnValue.put(key, element);
1115
                     } else {
1116
                         logMetacat.info("DBQuery.docidsInQueryresultTable - Null elment found ("
1117
                         + "DBQuery.docidsInQueryresultTable)");
1118
                     }
1119
                     tableHasRows = rs.next();
1120
                 }
1121
                 rs.close();
1122
                 pstmt.close();
1123
             } catch (Exception e){
1124
                 logMetacat.error("DBQuery.docidsInQueryresultTable - Error getting docids from "
1125
                                          + "queryresult: " + e.getMessage());
1126
              }
1127
         }
1128
         return returnValue;
1129
     }
1130

    
1131

    
1132
   /**
1133
    * Method to get id from xml_returnfield table
1134
    * for a given query specification
1135
    */
1136
   private int returnfield_id;
1137
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1138
                                           DBConnection dbconn){
1139
       int id = -1;
1140
       int count = 1;
1141
       PreparedStatement pstmt = null;
1142
       ResultSet rs = null;
1143
       String returnfield = qspec.getSortedReturnFieldString();
1144

    
1145
       // query for finding the id from xml_returnfield
1146
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1147
            + "WHERE returnfield_string LIKE ?";
1148
       logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Query:" + query);
1149

    
1150
       try {
1151
           // prepare and run the query
1152
           pstmt = dbconn.prepareStatement(query);
1153
           pstmt.setString(1,returnfield);
1154
           dbconn.increaseUsageCount(1);
1155
           pstmt.execute();
1156
           rs = pstmt.getResultSet();
1157
           boolean tableHasRows = rs.next();
1158

    
1159
           // if record found then increase the usage count
1160
           // else insert a new record and get the id of the new record
1161
           if(tableHasRows){
1162
               // get the id
1163
               id = rs.getInt(1);
1164
               count = rs.getInt(2) + 1;
1165
               rs.close();
1166
               pstmt.close();
1167

    
1168
               // increase the usage count
1169
               query = "UPDATE xml_returnfield SET usage_count = ?"
1170
                   + " WHERE returnfield_id = ?";
1171
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Update:"+ query);
1172

    
1173
               pstmt = dbconn.prepareStatement(query);
1174
               pstmt.setInt(1, count);
1175
               pstmt.setInt(2, id);
1176
               dbconn.increaseUsageCount(1);
1177
               pstmt.execute();
1178
               pstmt.close();
1179

    
1180
           } else {
1181
               rs.close();
1182
               pstmt.close();
1183

    
1184
               // insert a new record
1185
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1186
                   + "VALUES (?, '1')";
1187
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Insert:"+ query);
1188
               pstmt = dbconn.prepareStatement(query);
1189
               pstmt.setString(1, returnfield);
1190
               dbconn.increaseUsageCount(1);
1191
               pstmt.execute();
1192
               pstmt.close();
1193

    
1194
               // get the id of the new record
1195
               query = "SELECT returnfield_id FROM xml_returnfield "
1196
                   + "WHERE returnfield_string LIKE ?";
1197
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField query after Insert:" + query);
1198
               pstmt = dbconn.prepareStatement(query);
1199
               pstmt.setString(1, returnfield);
1200

    
1201
               dbconn.increaseUsageCount(1);
1202
               pstmt.execute();
1203
               rs = pstmt.getResultSet();
1204
               if(rs.next()){
1205
                   id = rs.getInt(1);
1206
               } else {
1207
                   id = -1;
1208
               }
1209
               rs.close();
1210
               pstmt.close();
1211
           }
1212

    
1213
       } catch (Exception e){
1214
           logMetacat.error("DBQuery.getXmlReturnfieldsTableId - Error getting id from xml_returnfield in "
1215
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1216
                                     + e.getMessage());
1217
           id = -1;
1218
       }
1219

    
1220
       returnfield_id = id;
1221
       return count;
1222
   }
1223

    
1224

    
1225
    /*
1226
     * A method to add return field to return doclist hash table
1227
     */
1228
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1229
                                      QuerySpecification qspec,
1230
                                      String user, String[]groups,
1231
                                      DBConnection dbconn, boolean useXMLIndex,
1232
                                      String qformat)
1233
                                      throws Exception
1234
    {
1235
      PreparedStatement pstmt = null;
1236
      ResultSet rs = null;
1237
      String docid = null;
1238
      String fieldname = null;
1239
      String fieldtype = null;
1240
      String fielddata = null;
1241
      String relation = null;
1242
      // keep track of parameter values
1243
      List<Object> parameterValues = new ArrayList<Object>();
1244

    
1245
      if (qspec.containsExtendedSQL())
1246
      {
1247
        qspec.setUserName(user);
1248
        qspec.setGroup(groups);
1249
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1250
        Vector results = new Vector();
1251
        Iterator keylist = docListResult.getDocids();
1252
        StringBuffer doclist = new StringBuffer();
1253
        List<Object> doclistValues = new ArrayList<Object>();
1254
        Vector parentidList = new Vector();
1255
        Hashtable returnFieldValue = new Hashtable();
1256
        while (keylist.hasNext())
1257
        {
1258
          String key = (String)keylist.next();
1259
          doclist.append("?,");
1260
          doclistValues.add(key);
1261
        }
1262
        if (doclist.length() > 0)
1263
        {
1264
          Hashtable controlPairs = new Hashtable();
1265
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1266
          boolean tableHasRows = false;
1267
        
1268

    
1269
          
1270
           String extendedQuery =
1271
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex, parameterValues, doclistValues);
1272
           // DO not add doclist values -- they are included in the query
1273
           //parameterValues.addAll(doclistValues);
1274
           logMetacat.info("DBQuery.addReturnfield - Extended query: " + extendedQuery);
1275

    
1276
           if(extendedQuery != null){
1277
//        	   long extendedQueryStart = System.currentTimeMillis();
1278
               pstmt = dbconn.prepareStatement(extendedQuery);
1279
               // set the parameter values
1280
               pstmt = DBQuery.setPreparedStatementValues(parameterValues, pstmt);
1281
               //increase dbconnection usage count
1282
               dbconn.increaseUsageCount(1);
1283
               pstmt.execute();
1284
               rs = pstmt.getResultSet();
1285
               tableHasRows = rs.next();
1286
               while (tableHasRows) {
1287
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1288
                   docid = rs.getString(1).trim();
1289
                   fieldname = rs.getString(2);
1290
                   
1291
                   if(qformat.toLowerCase().trim().equals("xml"))
1292
                   {
1293
                       byte[] b = rs.getBytes(3);
1294
                       fielddata = new String(b, 0, b.length, MetaCatServlet.DEFAULT_ENCODING);
1295
                   }
1296
                   else
1297
                   {
1298
                       fielddata = rs.getString(3);
1299
                   }
1300
                   
1301
                   //System.out.println("raw fielddata: " + fielddata);
1302
                   fielddata = MetacatUtil.normalize(fielddata);
1303
                   //System.out.println("normalized fielddata: " + fielddata);
1304
                   String parentId = rs.getString(4);
1305
                   fieldtype = rs.getString(5);
1306
                   StringBuffer value = new StringBuffer();
1307

    
1308
                   //handle case when usexmlindex is true differently
1309
                   //at one point merging the nodedata (for large text elements) was 
1310
                   //deemed unnecessary - but now it is needed.  but not for attribute nodes
1311
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1312
                	   //merge node data only for non-ATTRIBUTEs
1313
                	   if (fieldtype != null && !fieldtype.equals("ATTRIBUTE")) {
1314
	                	   //try merging the data
1315
	                	   ReturnFieldValue existingRFV =
1316
	                		   getArrayValue(parentidList, parentId);
1317
	                	   if (existingRFV != null && !existingRFV.getFieldType().equals("ATTRIBUTE")) {
1318
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1319
	                	   }
1320
                	   }
1321
                	   //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1322

    
1323
                       value.append("<param name=\"");
1324
                       value.append(fieldname);
1325
                       value.append("\">");
1326
                       value.append(fielddata);
1327
                       value.append("</param>");
1328
                       //set returnvalue
1329
                       returnValue.setDocid(docid);
1330
                       returnValue.setFieldValue(fielddata);
1331
                       returnValue.setFieldType(fieldtype);
1332
                       returnValue.setXMLFieldValue(value.toString());
1333
                       // Store it in hastable
1334
                       putInArray(parentidList, parentId, returnValue);
1335
                   }
1336
                   else {
1337
                       
1338
                       // need to merge nodedata if they have same parent id and
1339
                       // node type is text
1340
                       fielddata = (String) ( (ReturnFieldValue)
1341
                                             getArrayValue(
1342
                           parentidList, parentId)).getFieldValue()
1343
                           + fielddata;
1344
                       //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1345
                       value.append("<param name=\"");
1346
                       value.append(fieldname);
1347
                       value.append("\">");
1348
                       value.append(fielddata);
1349
                       value.append("</param>");
1350
                       returnValue.setDocid(docid);
1351
                       returnValue.setFieldValue(fielddata);
1352
                       returnValue.setFieldType(fieldtype);
1353
                       returnValue.setXMLFieldValue(value.toString());
1354
                       // remove the old return value from paretnidList
1355
                       parentidList.remove(parentId);
1356
                       // store the new return value in parentidlit
1357
                       putInArray(parentidList, parentId, returnValue);
1358
                   }
1359
                   tableHasRows = rs.next();
1360
               } //while
1361
               rs.close();
1362
               pstmt.close();
1363

    
1364
               // put the merger node data info into doclistReult
1365
               Enumeration xmlFieldValue = (getElements(parentidList)).
1366
                   elements();
1367
               while (xmlFieldValue.hasMoreElements()) {
1368
                   ReturnFieldValue object =
1369
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1370
                   docid = object.getDocid();
1371
                   if (docListResult.containsDocid(docid)) {
1372
                       String removedelement = (String) docListResult.
1373
                           remove(docid);
1374
                       docListResult.
1375
                           addResultDocument(new ResultDocument(docid,
1376
                               removedelement + object.getXMLFieldValue()));
1377
                   }
1378
                   else {
1379
                       docListResult.addResultDocument(
1380
                         new ResultDocument(docid, object.getXMLFieldValue()));
1381
                   }
1382
               } //while
1383
//               double docListResultEnd = System.currentTimeMillis() / 1000;
1384
//               logMetacat.warn(
1385
//                   "Time to prepare ResultDocumentSet after"
1386
//                   + " execute extended query: "
1387
//                   + (docListResultEnd - extendedQueryEnd));
1388
           }
1389
       }//if doclist lenght is great than zero
1390
     }//if has extended query
1391

    
1392
      return docListResult;
1393
    }//addReturnfield
1394

    
1395
  
1396
  /**
1397
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1398
   * string as a param instead of a hashtable.
1399
   *
1400
   * @param xmlquery a string representing a query.
1401
   */
1402
   private  String transformQuery(String xmlquery)
1403
   {
1404
     xmlquery = xmlquery.trim();
1405
     int index = xmlquery.indexOf("?>");
1406
     if (index != -1)
1407
     {
1408
       return xmlquery.substring(index + 2, xmlquery.length());
1409
     }
1410
     else
1411
     {
1412
       return xmlquery;
1413
     }
1414
   }
1415
   
1416
   /*
1417
    * Method to store query string and result xml string into query result
1418
    * cache. If the size alreay reache the limitation, the cache will be
1419
    * cleared first, then store them.
1420
    */
1421
   private void storeQueryResultIntoCache(String query, String resultXML)
1422
   {
1423
	   synchronized (queryResultCache)
1424
	   {
1425
		   if (queryResultCache.size() >= QUERYRESULTCACHESIZE)
1426
		   {
1427
			   queryResultCache.clear();
1428
		   }
1429
		   queryResultCache.put(query, resultXML);
1430
		   
1431
	   }
1432
   }
1433
   
1434
   /*
1435
    * Method to get result xml string from query result cache. 
1436
    * Note: the returned string can be null.
1437
    */
1438
   private String getResultXMLFromCache(String query)
1439
   {
1440
	   String resultSet = null;
1441
	   synchronized (queryResultCache)
1442
	   {
1443
          try
1444
          {
1445
        	 logMetacat.info("DBQuery.getResultXMLFromCache - Get query from cache");
1446
		     resultSet = (String)queryResultCache.get(query);
1447
		   
1448
          }
1449
          catch (Exception e)
1450
          {
1451
        	  resultSet = null;
1452
          }
1453
		   
1454
	   }
1455
	   return resultSet;
1456
   }
1457
   
1458
   /**
1459
    * Method to clear the query result cache.
1460
    */
1461
   public static void clearQueryResultCache()
1462
   {
1463
	   synchronized (queryResultCache)
1464
	   {
1465
		   queryResultCache.clear();
1466
	   }
1467
   }
1468
   
1469
   /**
1470
    * Set the parameter values in the prepared statement using instrospection
1471
    * of the given value objects
1472
    * @param parameterValues
1473
    * @param pstmt
1474
    * @return
1475
    * @throws SQLException
1476
    */
1477
   public static PreparedStatement setPreparedStatementValues(List<Object> parameterValues, PreparedStatement pstmt) throws SQLException {
1478
	   // set all the values we have collected 
1479
      int parameterIndex = 1;
1480
      for (Object parameterValue: parameterValues) {
1481
    	  if (parameterValue instanceof String) {
1482
    		  pstmt.setString(parameterIndex, (String) parameterValue);
1483
    	  }
1484
    	  else if (parameterValue instanceof Integer) {
1485
    		  pstmt.setInt(parameterIndex, (Integer) parameterValue);
1486
    	  }
1487
    	  else if (parameterValue instanceof Float) {
1488
    		  pstmt.setFloat(parameterIndex, (Float) parameterValue);
1489
    	  }
1490
    	  else if (parameterValue instanceof Double) {
1491
    		  pstmt.setDouble(parameterIndex, (Double) parameterValue);
1492
    	  }
1493
    	  else if (parameterValue instanceof Date) {
1494
    		  pstmt.setTimestamp(parameterIndex, new Timestamp(((Date) parameterValue).getTime()));
1495
    	  }
1496
    	  else {
1497
    		  pstmt.setObject(parameterIndex, parameterValue);
1498
    	  }
1499
    	  parameterIndex++;
1500
      }
1501
      return pstmt;
1502
   }
1503

    
1504

    
1505
    /*
1506
     * A method to search if Vector contains a particular key string
1507
     */
1508
    private boolean containsKey(Vector parentidList, String parentId)
1509
    {
1510

    
1511
        Vector tempVector = null;
1512

    
1513
        for (int count = 0; count < parentidList.size(); count++) {
1514
            tempVector = (Vector) parentidList.get(count);
1515
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1516
        }
1517
        return false;
1518
    }
1519
    
1520
    /*
1521
     * A method to put key and value in Vector
1522
     */
1523
    private void putInArray(Vector parentidList, String key,
1524
            ReturnFieldValue value)
1525
    {
1526

    
1527
        Vector tempVector = null;
1528
        //only filter if the field type is NOT an attribute (say, for text)
1529
        String fieldType = value.getFieldType();
1530
        if (fieldType != null && !fieldType.equals("ATTRIBUTE")) {
1531
        
1532
	        for (int count = 0; count < parentidList.size(); count++) {
1533
	            tempVector = (Vector) parentidList.get(count);
1534
	
1535
	            if (key.compareTo((String) tempVector.get(0)) == 0) {
1536
	                tempVector.remove(1);
1537
	                tempVector.add(1, value);
1538
	                return;
1539
	            }
1540
	        }
1541
        }
1542

    
1543
        tempVector = new Vector();
1544
        tempVector.add(0, key);
1545
        tempVector.add(1, value);
1546
        parentidList.add(tempVector);
1547
        return;
1548
    }
1549

    
1550
    /*
1551
     * A method to get value in Vector given a key
1552
     */
1553
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1554
    {
1555

    
1556
        Vector tempVector = null;
1557

    
1558
        for (int count = 0; count < parentidList.size(); count++) {
1559
            tempVector = (Vector) parentidList.get(count);
1560

    
1561
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1562
                    .get(1); }
1563
        }
1564
        return null;
1565
    }
1566

    
1567
    /*
1568
     * A method to get enumeration of all values in Vector
1569
     */
1570
    private Vector getElements(Vector parentidList)
1571
    {
1572
        Vector enumVector = new Vector();
1573
        Vector tempVector = null;
1574

    
1575
        for (int count = 0; count < parentidList.size(); count++) {
1576
            tempVector = (Vector) parentidList.get(count);
1577

    
1578
            enumVector.add(tempVector.get(1));
1579
        }
1580
        return enumVector;
1581
    }
1582

    
1583
  
1584

    
1585
    /*
1586
     * A method to create a query to get owner's docid list
1587
     */
1588
    private String getOwnerQuery(String owner, List<Object> parameterValues)
1589
    {
1590
        if (owner != null) {
1591
            owner = owner.toLowerCase();
1592
        }
1593
        StringBuffer self = new StringBuffer();
1594

    
1595
        self.append("SELECT docid,docname,doctype,");
1596
        self.append("date_created, date_updated, rev ");
1597
        self.append("FROM xml_documents WHERE docid IN (");
1598
        self.append("(");
1599
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1600
        self.append("nodedata LIKE '%%%' ");
1601
        self.append(") \n");
1602
        self.append(") ");
1603
        self.append(" AND (");
1604
        self.append(" lower(user_owner) = ?");
1605
        self.append(") ");
1606
        parameterValues.add(owner);
1607
        return self.toString();
1608
    }
1609

    
1610
    /**
1611
     * format a structured query as an XML document that conforms to the
1612
     * pathquery.dtd and is appropriate for submission to the DBQuery
1613
     * structured query engine
1614
     *
1615
     * @param params The list of parameters that should be included in the
1616
     *            query
1617
     */
1618
    public static String createSQuery(Hashtable params) throws PropertyNotFoundException
1619
    {
1620
        StringBuffer query = new StringBuffer();
1621
        Enumeration elements;
1622
        Enumeration keys;
1623
        String filterDoctype = null;
1624
        String casesensitive = null;
1625
        String searchmode = null;
1626
        Object nextkey;
1627
        Object nextelement;
1628
        //add the xml headers
1629
        query.append("<?xml version=\"1.0\"?>\n");
1630
        query.append("<pathquery version=\"1.2\">\n");
1631

    
1632

    
1633

    
1634
        if (params.containsKey("meta_file_id")) {
1635
            query.append("<meta_file_id>");
1636
            query.append(((String[]) params.get("meta_file_id"))[0]);
1637
            query.append("</meta_file_id>");
1638
        }
1639

    
1640
        if (params.containsKey("returndoctype")) {
1641
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1642
            for (int i = 0; i < returnDoctypes.length; i++) {
1643
                String doctype = (String) returnDoctypes[i];
1644

    
1645
                if (!doctype.equals("any") && !doctype.equals("ANY")
1646
                        && !doctype.equals("")) {
1647
                    query.append("<returndoctype>").append(doctype);
1648
                    query.append("</returndoctype>");
1649
                }
1650
            }
1651
        }
1652

    
1653
        if (params.containsKey("filterdoctype")) {
1654
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1655
            for (int i = 0; i < filterDoctypes.length; i++) {
1656
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1657
                query.append("</filterdoctype>");
1658
            }
1659
        }
1660

    
1661
        if (params.containsKey("returnfield")) {
1662
            String[] returnfield = ((String[]) params.get("returnfield"));
1663
            for (int i = 0; i < returnfield.length; i++) {
1664
                query.append("<returnfield>").append(returnfield[i]);
1665
                query.append("</returnfield>");
1666
            }
1667
        }
1668

    
1669
        if (params.containsKey("owner")) {
1670
            String[] owner = ((String[]) params.get("owner"));
1671
            for (int i = 0; i < owner.length; i++) {
1672
                query.append("<owner>").append(owner[i]);
1673
                query.append("</owner>");
1674
            }
1675
        }
1676

    
1677
        if (params.containsKey("site")) {
1678
            String[] site = ((String[]) params.get("site"));
1679
            for (int i = 0; i < site.length; i++) {
1680
                query.append("<site>").append(site[i]);
1681
                query.append("</site>");
1682
            }
1683
        }
1684

    
1685
        //allows the dynamic switching of boolean operators
1686
        if (params.containsKey("operator")) {
1687
            query.append("<querygroup operator=\""
1688
                    + ((String[]) params.get("operator"))[0] + "\">");
1689
        } else { //the default operator is UNION
1690
            query.append("<querygroup operator=\"UNION\">");
1691
        }
1692

    
1693
        if (params.containsKey("casesensitive")) {
1694
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1695
        } else {
1696
            casesensitive = "false";
1697
        }
1698

    
1699
        if (params.containsKey("searchmode")) {
1700
            searchmode = ((String[]) params.get("searchmode"))[0];
1701
        } else {
1702
            searchmode = "contains";
1703
        }
1704

    
1705
        //anyfield is a special case because it does a
1706
        //free text search. It does not have a <pathexpr>
1707
        //tag. This allows for a free text search within the structured
1708
        //query. This is useful if the INTERSECT operator is used.
1709
        if (params.containsKey("anyfield")) {
1710
            String[] anyfield = ((String[]) params.get("anyfield"));
1711
            //allow for more than one value for anyfield
1712
            for (int i = 0; i < anyfield.length; i++) {
1713
                if (anyfield[i] != null && !anyfield[i].equals("")) {
1714
                    query.append("<queryterm casesensitive=\"" + casesensitive
1715
                            + "\" " + "searchmode=\"" + searchmode
1716
                            + "\"><value>" + anyfield[i]
1717
                            + "</value></queryterm>");
1718
                }
1719
            }
1720
        }
1721

    
1722
        //this while loop finds the rest of the parameters
1723
        //and attempts to query for the field specified
1724
        //by the parameter.
1725
        elements = params.elements();
1726
        keys = params.keys();
1727
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1728
            nextkey = keys.nextElement();
1729
            nextelement = elements.nextElement();
1730

    
1731
            //make sure we aren't querying for any of these
1732
            //parameters since the are already in the query
1733
            //in one form or another.
1734
            Vector ignoredParams = new Vector();
1735
            ignoredParams.add("returndoctype");
1736
            ignoredParams.add("filterdoctype");
1737
            ignoredParams.add("action");
1738
            ignoredParams.add("qformat");
1739
            ignoredParams.add("anyfield");
1740
            ignoredParams.add("returnfield");
1741
            ignoredParams.add("owner");
1742
            ignoredParams.add("site");
1743
            ignoredParams.add("operator");
1744
            ignoredParams.add("sessionid");
1745
            ignoredParams.add("pagesize");
1746
            ignoredParams.add("pagestart");
1747
            ignoredParams.add("searchmode");
1748

    
1749
            // Also ignore parameters listed in the properties file
1750
            // so that they can be passed through to stylesheets
1751
            String paramsToIgnore = PropertyService
1752
                    .getProperty("database.queryignoredparams");
1753
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1754
            while (st.hasMoreTokens()) {
1755
                ignoredParams.add(st.nextToken());
1756
            }
1757
            if (!ignoredParams.contains(nextkey.toString())) {
1758
                //allow for more than value per field name
1759
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1760
                    if (!((String[]) nextelement)[i].equals("")) {
1761
                        query.append("<queryterm casesensitive=\""
1762
                                + casesensitive + "\" " + "searchmode=\""
1763
                                + searchmode + "\">" + "<value>" +
1764
                                //add the query value
1765
                                ((String[]) nextelement)[i]
1766
                                + "</value><pathexpr>" +
1767
                                //add the path to query by
1768
                                nextkey.toString() + "</pathexpr></queryterm>");
1769
                    }
1770
                }
1771
            }
1772
        }
1773
        query.append("</querygroup></pathquery>");
1774
        //append on the end of the xml and return the result as a string
1775
        return query.toString();
1776
    }
1777

    
1778
    /**
1779
     * format a simple free-text value query as an XML document that conforms
1780
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1781
     * structured query engine
1782
     *
1783
     * @param value the text string to search for in the xml catalog
1784
     * @param doctype the type of documents to include in the result set -- use
1785
     *            "any" or "ANY" for unfiltered result sets
1786
     */
1787
    public static String createQuery(String value, String doctype)
1788
    {
1789
        StringBuffer xmlquery = new StringBuffer();
1790
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1791
        xmlquery.append("<pathquery version=\"1.0\">");
1792

    
1793
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1794
            xmlquery.append("<returndoctype>");
1795
            xmlquery.append(doctype).append("</returndoctype>");
1796
        }
1797

    
1798
        xmlquery.append("<querygroup operator=\"UNION\">");
1799
        //chad added - 8/14
1800
        //the if statement allows a query to gracefully handle a null
1801
        //query. Without this if a nullpointerException is thrown.
1802
        if (!value.equals("")) {
1803
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1804
            xmlquery.append("searchmode=\"contains\">");
1805
            xmlquery.append("<value>").append(value).append("</value>");
1806
            xmlquery.append("</queryterm>");
1807
        }
1808
        xmlquery.append("</querygroup>");
1809
        xmlquery.append("</pathquery>");
1810

    
1811
        return (xmlquery.toString());
1812
    }
1813

    
1814
    /**
1815
     * format a simple free-text value query as an XML document that conforms
1816
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1817
     * structured query engine
1818
     *
1819
     * @param value the text string to search for in the xml catalog
1820
     */
1821
    public static String createQuery(String value)
1822
    {
1823
        return createQuery(value, "any");
1824
    }
1825

    
1826
    /**
1827
     * Check for "READ" permission on @docid for @user and/or @group from DB
1828
     * connection
1829
     */
1830
    private boolean hasPermission(String user, String[] groups, String docid)
1831
            throws SQLException, Exception
1832
    {
1833
        // Check for READ permission on @docid for @user and/or @groups
1834
        PermissionController controller = new PermissionController(docid);
1835
        return controller.hasPermission(user, groups,
1836
                AccessControlInterface.READSTRING);
1837
    }
1838

    
1839
    /**
1840
     * Get all docIds list for a data packadge
1841
     *
1842
     * @param dataPackageDocid, the string in docId field of xml_relation table
1843
     */
1844
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1845
    {
1846
        DBConnection dbConn = null;
1847
        int serialNumber = -1;
1848
        Vector docIdList = new Vector();//return value
1849
        PreparedStatement pStmt = null;
1850
        ResultSet rs = null;
1851
        String docIdInSubjectField = null;
1852
        String docIdInObjectField = null;
1853

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

    
1857
        //the query stirng
1858
        String query = "SELECT subject, object from xml_relation where docId = ?";
1859
        try {
1860
            dbConn = DBConnectionPool
1861
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1862
            serialNumber = dbConn.getCheckOutSerialNumber();
1863
            pStmt = dbConn.prepareStatement(query);
1864
            //bind the value to query
1865
            pStmt.setString(1, dataPackageDocid);
1866

    
1867
            //excute the query
1868
            pStmt.execute();
1869
            //get the result set
1870
            rs = pStmt.getResultSet();
1871
            //process the result
1872
            while (rs.next()) {
1873
                //In order to get the whole docIds in a data packadge,
1874
                //we need to put the docIds of subject and object field in
1875
                // xml_relation
1876
                //into the return vector
1877
                docIdInSubjectField = rs.getString(1);//the result docId in
1878
                                                      // subject field
1879
                docIdInObjectField = rs.getString(2);//the result docId in
1880
                                                     // object field
1881

    
1882
                //don't put the duplicate docId into the vector
1883
                if (!docIdList.contains(docIdInSubjectField)) {
1884
                    docIdList.add(docIdInSubjectField);
1885
                }
1886

    
1887
                //don't put the duplicate docId into the vector
1888
                if (!docIdList.contains(docIdInObjectField)) {
1889
                    docIdList.add(docIdInObjectField);
1890
                }
1891
            }//while
1892
            //close the pStmt
1893
            pStmt.close();
1894
        }//try
1895
        catch (SQLException e) {
1896
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - Error in getDocidListForDataPackage: "
1897
                    + e.getMessage());
1898
        }//catch
1899
        finally {
1900
            try {
1901
                pStmt.close();
1902
            }//try
1903
            catch (SQLException ee) {
1904
                logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - SQL Error: "
1905
                                + ee.getMessage());
1906
            }//catch
1907
            finally {
1908
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1909
            }//fianlly
1910
        }//finally
1911
        return docIdList;
1912
    }//getCurrentDocidListForDataPackadge()
1913

    
1914
    /**
1915
     * Get all docIds list for a data packadge
1916
     *
1917
     * @param dataPackageDocid, the string in docId field of xml_relation table
1918
     */
1919
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1920
    {
1921

    
1922
        Vector docIdList = new Vector();//return value
1923
        Vector tripleList = null;
1924
        String xml = null;
1925

    
1926
        // Check the parameter
1927
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1928

    
1929
        try {
1930
            //initial a documentImpl object
1931
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1932
            //transfer to documentImpl object to string
1933
            xml = packageDocument.toString();
1934

    
1935
            //create a tripcollection object
1936
            TripleCollection tripleForPackage = new TripleCollection(
1937
                    new StringReader(xml));
1938
            //get the vetor of triples
1939
            tripleList = tripleForPackage.getCollection();
1940

    
1941
            for (int i = 0; i < tripleList.size(); i++) {
1942
                //put subject docid into docIdlist without duplicate
1943
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1944
                        .getSubject())) {
1945
                    //put subject docid into docIdlist
1946
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1947
                }
1948
                //put object docid into docIdlist without duplicate
1949
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1950
                        .getObject())) {
1951
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1952
                }
1953
            }//for
1954
        }//try
1955
        catch (Exception e) {
1956
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - General error: "
1957
                    + e.getMessage());
1958
        }//catch
1959

    
1960
        // return result
1961
        return docIdList;
1962
    }//getDocidListForPackageInXMLRevisions()
1963

    
1964
    /**
1965
     * Check if the docId is a data packadge id. If the id is a data packadage
1966
     * id, it should be store in the docId fields in xml_relation table. So we
1967
     * can use a query to get the entries which the docId equals the given
1968
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1969
     * it is.
1970
     *
1971
     * @param docId, the id need to be checked
1972
     */
1973
    private boolean isDataPackageId(String docId)
1974
    {
1975
        boolean result = false;
1976
        PreparedStatement pStmt = null;
1977
        ResultSet rs = null;
1978
        String query = "SELECT docId from xml_relation where docId = ?";
1979
        DBConnection dbConn = null;
1980
        int serialNumber = -1;
1981
        try {
1982
            dbConn = DBConnectionPool
1983
                    .getDBConnection("DBQuery.isDataPackageId");
1984
            serialNumber = dbConn.getCheckOutSerialNumber();
1985
            pStmt = dbConn.prepareStatement(query);
1986
            //bind the value to query
1987
            pStmt.setString(1, docId);
1988
            //execute the query
1989
            pStmt.execute();
1990
            rs = pStmt.getResultSet();
1991
            //process the result
1992
            if (rs.next()) //There are some records for the id in docId fields
1993
            {
1994
                result = true;//It is a data packadge id
1995
            }
1996
            pStmt.close();
1997
        }//try
1998
        catch (SQLException e) {
1999
            logMetacat.error("DBQuery.isDataPackageId - SQL Error: "
2000
                    + e.getMessage());
2001
        } finally {
2002
            try {
2003
                pStmt.close();
2004
            }//try
2005
            catch (SQLException ee) {
2006
                logMetacat.error("DBQuery.isDataPackageId - SQL Error in isDataPackageId: "
2007
                        + ee.getMessage());
2008
            }//catch
2009
            finally {
2010
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2011
            }//finally
2012
        }//finally
2013
        return result;
2014
    }//isDataPackageId()
2015

    
2016
    public String getOperator() {
2017
		return operator;
2018
	}
2019

    
2020
    /**
2021
     * Specifies if and how docid overrides should be included in the general query
2022
     * @param operator null, UNION, or INTERSECT (see QueryGroup)
2023
     */
2024
	public void setOperator(String operator) {
2025
		this.operator = operator;
2026
	}
2027

    
2028
	/**
2029
     * Check if the user has the permission to export data package
2030
     *
2031
     * @param conn, the connection
2032
     * @param docId, the id need to be checked
2033
     * @param user, the name of user
2034
     * @param groups, the user's group
2035
     */
2036
    private boolean hasPermissionToExportPackage(String docId, String user,
2037
            String[] groups) throws Exception
2038
    {
2039
        //DocumentImpl doc=new DocumentImpl(conn,docId);
2040
        return DocumentImpl.hasReadPermission(user, groups, docId);
2041
    }
2042

    
2043
    /**
2044
     * Get the current Rev for a docid in xml_documents table
2045
     *
2046
     * @param docId, the id need to get version numb If the return value is -5,
2047
     *            means no value in rev field for this docid
2048
     */
2049
    private int getCurrentRevFromXMLDoumentsTable(String docId)
2050
            throws SQLException
2051
    {
2052
        int rev = -5;
2053
        PreparedStatement pStmt = null;
2054
        ResultSet rs = null;
2055
        String query = "SELECT rev from xml_documents where docId = ?";
2056
        DBConnection dbConn = null;
2057
        int serialNumber = -1;
2058
        try {
2059
            dbConn = DBConnectionPool
2060
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
2061
            serialNumber = dbConn.getCheckOutSerialNumber();
2062
            pStmt = dbConn.prepareStatement(query);
2063
            //bind the value to query
2064
            pStmt.setString(1, docId);
2065
            //execute the query
2066
            pStmt.execute();
2067
            rs = pStmt.getResultSet();
2068
            //process the result
2069
            if (rs.next()) //There are some records for rev
2070
            {
2071
                rev = rs.getInt(1);
2072
                ;//It is the version for given docid
2073
            } else {
2074
                rev = -5;
2075
            }
2076

    
2077
        }//try
2078
        catch (SQLException e) {
2079
            logMetacat.error("DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
2080
                            + e.getMessage());
2081
            throw e;
2082
        }//catch
2083
        finally {
2084
            try {
2085
                pStmt.close();
2086
            }//try
2087
            catch (SQLException ee) {
2088
                logMetacat.error(
2089
                        "DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
2090
                                + ee.getMessage());
2091
            }//catch
2092
            finally {
2093
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2094
            }//finally
2095
        }//finally
2096
        return rev;
2097
    }//getCurrentRevFromXMLDoumentsTable
2098

    
2099
    /**
2100
     * put a doc into a zip output stream
2101
     *
2102
     * @param docImpl, docmentImpl object which will be sent to zip output
2103
     *            stream
2104
     * @param zipOut, zip output stream which the docImpl will be put
2105
     * @param packageZipEntry, the zip entry name for whole package
2106
     */
2107
    private void addDocToZipOutputStream(DocumentImpl docImpl,
2108
            ZipOutputStream zipOut, String packageZipEntry)
2109
            throws ClassNotFoundException, IOException, SQLException,
2110
            McdbException, Exception
2111
    {
2112
        byte[] byteString = null;
2113
        ZipEntry zEntry = null;
2114

    
2115
        byteString = docImpl.getBytes();
2116
        //use docId as the zip entry's name
2117
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
2118
                + docImpl.getDocID());
2119
        zEntry.setSize(byteString.length);
2120
        zipOut.putNextEntry(zEntry);
2121
        zipOut.write(byteString, 0, byteString.length);
2122
        zipOut.closeEntry();
2123

    
2124
    }//addDocToZipOutputStream()
2125

    
2126
    /**
2127
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
2128
     * only inlcudes current version. If a DocumentImple object couldn't find
2129
     * for a docid, then the String of this docid was added to vetor rather
2130
     * than DocumentImple object.
2131
     *
2132
     * @param docIdList, a vetor hold a docid list for a data package. In
2133
     *            docid, there is not version number in it.
2134
     */
2135

    
2136
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2137
            throws McdbException, Exception
2138
    {
2139
        //Connection dbConn=null;
2140
        Vector documentImplList = new Vector();
2141
        int rev = 0;
2142

    
2143
        // Check the parameter
2144
        if (docIdList.isEmpty()) { return documentImplList; }//if
2145

    
2146
        //for every docid in vector
2147
        for (int i = 0; i < docIdList.size(); i++) {
2148
            try {
2149
                //get newest version for this docId
2150
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2151
                        .elementAt(i));
2152

    
2153
                // There is no record for this docId in xml_documents table
2154
                if (rev == -5) {
2155
                    // Rather than put DocumentImple object, put a String
2156
                    // Object(docid)
2157
                    // into the documentImplList
2158
                    documentImplList.add((String) docIdList.elementAt(i));
2159
                    // Skip other code
2160
                    continue;
2161
                }
2162

    
2163
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2164
                        + PropertyService.getProperty("document.accNumSeparator") + rev;
2165

    
2166
                //create new documentImpl object
2167
                DocumentImpl documentImplObject = new DocumentImpl(
2168
                        docidPlusVersion);
2169
                //add them to vector
2170
                documentImplList.add(documentImplObject);
2171
            }//try
2172
            catch (Exception e) {
2173
                logMetacat.error("DBQuery.getCurrentAllDocumentImpl - General error: "
2174
                        + e.getMessage());
2175
                // continue the for loop
2176
                continue;
2177
            }
2178
        }//for
2179
        return documentImplList;
2180
    }
2181

    
2182
    /**
2183
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2184
     * object couldn't find for a docid, then the String of this docid was
2185
     * added to vetor rather than DocumentImple object.
2186
     *
2187
     * @param docIdList, a vetor hold a docid list for a data package. In
2188
     *            docid, t here is version number in it.
2189
     */
2190
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2191
    {
2192
        //Connection dbConn=null;
2193
        Vector documentImplList = new Vector();
2194
        String siteCode = null;
2195
        String uniqueId = null;
2196
        int rev = 0;
2197

    
2198
        // Check the parameter
2199
        if (docIdList.isEmpty()) { return documentImplList; }//if
2200

    
2201
        //for every docid in vector
2202
        for (int i = 0; i < docIdList.size(); i++) {
2203

    
2204
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2205

    
2206
            try {
2207
                //create new documentImpl object
2208
                DocumentImpl documentImplObject = new DocumentImpl(
2209
                        docidPlusVersion);
2210
                //add them to vector
2211
                documentImplList.add(documentImplObject);
2212
            }//try
2213
            catch (McdbDocNotFoundException notFoundE) {
2214
                logMetacat.error("DBQuery.getOldVersionAllDocument - Error finding doc " 
2215
                		+ docidPlusVersion + " : " + notFoundE.getMessage());
2216
                // Rather than add a DocumentImple object into vetor, a String
2217
                // object
2218
                // - the doicd was added to the vector
2219
                documentImplList.add(docidPlusVersion);
2220
                // Continue the for loop
2221
                continue;
2222
            }//catch
2223
            catch (Exception e) {
2224
                logMetacat.error(
2225
                        "DBQuery.getOldVersionAllDocument - General error: "
2226
                                + e.getMessage());
2227
                // Continue the for loop
2228
                continue;
2229
            }//catch
2230

    
2231
        }//for
2232
        return documentImplList;
2233
    }//getOldVersionAllDocumentImple
2234

    
2235
    /**
2236
     * put a data file into a zip output stream
2237
     *
2238
     * @param docImpl, docmentImpl object which will be sent to zip output
2239
     *            stream
2240
     * @param zipOut, the zip output stream which the docImpl will be put
2241
     * @param packageZipEntry, the zip entry name for whole package
2242
     */
2243
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2244
            ZipOutputStream zipOut, String packageZipEntry)
2245
            throws ClassNotFoundException, IOException, SQLException,
2246
            McdbException, Exception
2247
    {
2248
        byte[] byteString = null;
2249
        ZipEntry zEntry = null;
2250
        // this is data file; add file to zip
2251
        String filePath = PropertyService.getProperty("application.datafilepath");
2252
        if (!filePath.endsWith("/")) {
2253
            filePath += "/";
2254
        }
2255
        String fileName = filePath + docImpl.getDocID();
2256
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2257
        zipOut.putNextEntry(zEntry);
2258
        FileInputStream fin = null;
2259
        try {
2260
            fin = new FileInputStream(fileName);
2261
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2262
            int b = fin.read(buf);
2263
            while (b != -1) {
2264
                zipOut.write(buf, 0, b);
2265
                b = fin.read(buf);
2266
            }//while
2267
            zipOut.closeEntry();
2268
        }//try
2269
        catch (IOException ioe) {
2270
            logMetacat.error("DBQuery.addDataFileToZipOutputStream - I/O error: "
2271
                    + ioe.getMessage());
2272
        }//catch
2273
    }//addDataFileToZipOutputStream()
2274

    
2275
    /**
2276
     * create a html summary for data package and put it into zip output stream
2277
     *
2278
     * @param docImplList, the documentImpl ojbects in data package
2279
     * @param zipOut, the zip output stream which the html should be put
2280
     * @param packageZipEntry, the zip entry name for whole package
2281
     */
2282
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2283
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2284
    {
2285
        StringBuffer htmlDoc = new StringBuffer();
2286
        ZipEntry zEntry = null;
2287
        byte[] byteString = null;
2288
        InputStream source;
2289
        DBTransform xmlToHtml;
2290

    
2291
        //create a DBTransform ojbect
2292
        xmlToHtml = new DBTransform();
2293
        //head of html
2294
        htmlDoc.append("<html><head></head><body>");
2295
        for (int i = 0; i < docImplList.size(); i++) {
2296
            // If this String object, this means it is missed data file
2297
            if ((((docImplList.elementAt(i)).getClass()).toString())
2298
                    .equals("class java.lang.String")) {
2299

    
2300
                htmlDoc.append("<a href=\"");
2301
                String dataFileid = (String) docImplList.elementAt(i);
2302
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2303
                htmlDoc.append("Data File: ");
2304
                htmlDoc.append(dataFileid).append("</a><br>");
2305
                htmlDoc.append("<br><hr><br>");
2306

    
2307
            }//if
2308
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2309
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2310
                                              // transform it.
2311
                //transform each file individually then concatenate all of the
2312
                //transformations together.
2313

    
2314
                //for metadata xml title
2315
                htmlDoc.append("<h2>");
2316
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2317
                        .getDocID());
2318
                //htmlDoc.append(".");
2319
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2320
                htmlDoc.append("</h2>");
2321
                //do the actual transform
2322
                StringWriter docString = new StringWriter();
2323
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2324
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2325
                        "-//W3C//HTML//EN", "html", docString, null, null);
2326
                htmlDoc.append(docString.toString());
2327
                htmlDoc.append("<br><br><hr><br><br>");
2328
            }//if
2329
            else { //this is a data file so we should link to it in the html
2330
                htmlDoc.append("<a href=\"");
2331
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2332
                        .getDocID();
2333
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2334
                htmlDoc.append("Data File: ");
2335
                htmlDoc.append(dataFileid).append("</a><br>");
2336
                htmlDoc.append("<br><hr><br>");
2337
            }//else
2338
        }//for
2339
        htmlDoc.append("</body></html>");
2340
        // use standard encoding even though the different docs might have use different encodings,
2341
        // the String objects in java should be correct and able to be encoded as the same Metacat default
2342
        byteString = htmlDoc.toString().getBytes(MetaCatServlet.DEFAULT_ENCODING);
2343
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2344
        zEntry.setSize(byteString.length);
2345
        zipOut.putNextEntry(zEntry);
2346
        zipOut.write(byteString, 0, byteString.length);
2347
        zipOut.closeEntry();
2348
        //dbConn.close();
2349

    
2350
    }//addHtmlSummaryToZipOutputStream
2351

    
2352
    /**
2353
     * put a data packadge into a zip output stream
2354
     *
2355
     * @param docId, which the user want to put into zip output stream,it has version
2356
     * @param out, a servletoutput stream which the zip output stream will be
2357
     *            put
2358
     * @param user, the username of the user
2359
     * @param groups, the group of the user
2360
     */
2361
    public ZipOutputStream getZippedPackage(String docIdString,
2362
            ServletOutputStream out, String user, String[] groups,
2363
            String passWord) throws ClassNotFoundException, IOException,
2364
            SQLException, McdbException, NumberFormatException, Exception
2365
    {
2366
        ZipOutputStream zOut = null;
2367
        String elementDocid = null;
2368
        DocumentImpl docImpls = null;
2369
        //Connection dbConn = null;
2370
        Vector docIdList = new Vector();
2371
        Vector documentImplList = new Vector();
2372
        Vector htmlDocumentImplList = new Vector();
2373
        String packageId = null;
2374
        String rootName = "package";//the package zip entry name
2375

    
2376
        String docId = null;
2377
        int version = -5;
2378
        // Docid without revision
2379
        docId = DocumentUtil.getDocIdFromString(docIdString);
2380
        // revision number
2381
        version = DocumentUtil.getVersionFromString(docIdString);
2382

    
2383
        //check if the reqused docId is a data package id
2384
        if (!isDataPackageId(docId)) {
2385

    
2386
            /*
2387
             * Exception e = new Exception("The request the doc id "
2388
             * +docIdString+ " is not a data package id");
2389
             */
2390

    
2391
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2392
            // zip
2393
            //up the single document and return the zip file.
2394
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2395

    
2396
                Exception e = new Exception("User " + user
2397
                        + " does not have permission"
2398
                        + " to export the data package " + docIdString);
2399
                throw e;
2400
            }
2401

    
2402
            docImpls = new DocumentImpl(docIdString);
2403
            //checking if the user has the permission to read the documents
2404
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2405
                    .getDocID())) {
2406
                zOut = new ZipOutputStream(out);
2407
                //if the docImpls is metadata
2408
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2409
                    //add metadata into zip output stream
2410
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2411
                }//if
2412
                else {
2413
                    //it is data file
2414
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2415
                    htmlDocumentImplList.add(docImpls);
2416
                }//else
2417
            }//if
2418

    
2419
            zOut.finish(); //terminate the zip file
2420
            return zOut;
2421
        }
2422
        // Check the permission of user
2423
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2424

    
2425
            Exception e = new Exception("User " + user
2426
                    + " does not have permission"
2427
                    + " to export the data package " + docIdString);
2428
            throw e;
2429
        } else //it is a packadge id
2430
        {
2431
            //store the package id
2432
            packageId = docId;
2433
            //get current version in database
2434
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2435
            //If it is for current version (-1 means user didn't specify
2436
            // revision)
2437
            if ((version == -1) || version == currentVersion) {
2438
                //get current version number
2439
                version = currentVersion;
2440
                //get package zip entry name
2441
                //it should be docId.revsion.package
2442
                rootName = packageId + PropertyService.getProperty("document.accNumSeparator")
2443
                        + version + PropertyService.getProperty("document.accNumSeparator")
2444
                        + "package";
2445
                //get the whole id list for data packadge
2446
                docIdList = getCurrentDocidListForDataPackage(packageId);
2447
                //get the whole documentImple object
2448
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2449

    
2450
            }//if
2451
            else if (version > currentVersion || version < -1) {
2452
                throw new Exception("The user specified docid: " + docId + "."
2453
                        + version + " doesn't exist");
2454
            }//else if
2455
            else //for an old version
2456
            {
2457

    
2458
                rootName = docIdString
2459
                        + PropertyService.getProperty("document.accNumSeparator") + "package";
2460
                //get the whole id list for data packadge
2461
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2462

    
2463
                //get the whole documentImple object
2464
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2465
            }//else
2466

    
2467
            // Make sure documentImplist is not empty
2468
            if (documentImplList.isEmpty()) { throw new Exception(
2469
                    "Couldn't find component for data package: " + packageId); }//if
2470

    
2471
            zOut = new ZipOutputStream(out);
2472
            //put every element into zip output stream
2473
            for (int i = 0; i < documentImplList.size(); i++) {
2474
                // if the object in the vetor is String, this means we couldn't
2475
                // find
2476
                // the document locally, we need find it remote
2477
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2478
                        .equals("class java.lang.String")) {
2479
                    // Get String object from vetor
2480
                    String documentId = (String) documentImplList.elementAt(i);
2481
                    logMetacat.info("DBQuery.getZippedPackage - docid: " + documentId);
2482
                    // Get doicd without revision
2483
                    String docidWithoutRevision = 
2484
                    	DocumentUtil.getDocIdFromString(documentId);
2485
                    logMetacat.info("DBQuery.getZippedPackage - docidWithoutRevsion: "
2486
                            + docidWithoutRevision);
2487
                    // Get revision
2488
                    String revision = 
2489
                    	DocumentUtil.getRevisionStringFromString(documentId);
2490
                    logMetacat.info("DBQuery.getZippedPackage - revision from docIdentifier: "
2491
                            + revision);
2492
                    // Zip entry string
2493
                    String zipEntryPath = rootName + "/data/";
2494
                    // Create a RemoteDocument object
2495
                    RemoteDocument remoteDoc = new RemoteDocument(
2496
                            docidWithoutRevision, revision, user, passWord,
2497
                            zipEntryPath);
2498
                    // Here we only read data file from remote metacat
2499
                    String docType = remoteDoc.getDocType();
2500
                    if (docType != null) {
2501
                        if (docType.equals("BIN")) {
2502
                            // Put remote document to zip output
2503
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2504
                            // Add String object to htmlDocumentImplList
2505
                            String elementInHtmlList = remoteDoc
2506
                                    .getDocIdWithoutRevsion()
2507
                                    + PropertyService.getProperty("document.accNumSeparator")
2508
                                    + remoteDoc.getRevision();
2509
                            htmlDocumentImplList.add(elementInHtmlList);
2510
                        }//if
2511
                    }//if
2512

    
2513
                }//if
2514
                else {
2515
                    //create a docmentImpls object (represent xml doc) base on
2516
                    // the docId
2517
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2518
                    //checking if the user has the permission to read the
2519
                    // documents
2520
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2521
                            .getDocID())) {
2522
                        //if the docImpls is metadata
2523
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2524
                            //add metadata into zip output stream
2525
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2526
                            //add the documentImpl into the vetor which will
2527
                            // be used in html
2528
                            htmlDocumentImplList.add(docImpls);
2529

    
2530
                        }//if
2531
                        else {
2532
                            //it is data file
2533
                            addDataFileToZipOutputStream(docImpls, zOut,
2534
                                    rootName);
2535
                            htmlDocumentImplList.add(docImpls);
2536
                        }//else
2537
                    }//if
2538
                }//else
2539
            }//for
2540

    
2541
            //add html summary file
2542
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2543
                    rootName);
2544
            zOut.finish(); //terminate the zip file
2545
            //dbConn.close();
2546
            return zOut;
2547
        }//else
2548
    }//getZippedPackage()
2549

    
2550
    private class ReturnFieldValue
2551
    {
2552

    
2553
        private String docid = null; //return field value for this docid
2554

    
2555
        private String fieldValue = null;
2556

    
2557
        private String xmlFieldValue = null; //return field value in xml
2558
                                             // format
2559
        private String fieldType = null; //ATTRIBUTE, TEXT...
2560

    
2561
        public void setDocid(String myDocid)
2562
        {
2563
            docid = myDocid;
2564
        }
2565

    
2566
        public String getDocid()
2567
        {
2568
            return docid;
2569
        }
2570

    
2571
        public void setFieldValue(String myValue)
2572
        {
2573
            fieldValue = myValue;
2574
        }
2575

    
2576
        public String getFieldValue()
2577
        {
2578
            return fieldValue;
2579
        }
2580

    
2581
        public void setXMLFieldValue(String xml)
2582
        {
2583
            xmlFieldValue = xml;
2584
        }
2585

    
2586
        public String getXMLFieldValue()
2587
        {
2588
            return xmlFieldValue;
2589
        }
2590
        
2591
        public void setFieldType(String myType)
2592
        {
2593
            fieldType = myType;
2594
        }
2595

    
2596
        public String getFieldType()
2597
        {
2598
            return fieldType;
2599
        }
2600

    
2601
    }
2602
    
2603
    /**
2604
     * a class to store one result document consisting of a docid and a document
2605
     */
2606
    private class ResultDocument
2607
    {
2608
      public String docid;
2609
      public String document;
2610
      
2611
      public ResultDocument(String docid, String document)
2612
      {
2613
        this.docid = docid;
2614
        this.document = document;
2615
      }
2616
    }
2617
    
2618
    /**
2619
     * a private class to handle a set of resultDocuments
2620
     */
2621
    private class ResultDocumentSet
2622
    {
2623
      private Vector docids;
2624
      private Vector documents;
2625
      
2626
      public ResultDocumentSet()
2627
      {
2628
        docids = new Vector();
2629
        documents = new Vector();
2630
      }
2631
      
2632
      /**
2633
       * adds a result document to the set
2634
       */
2635
      public void addResultDocument(ResultDocument rd)
2636
      {
2637
        if(rd.docid == null)
2638
          return;
2639
        if(rd.document == null)
2640
          rd.document = "";
2641
       
2642
           docids.addElement(rd.docid);
2643
           documents.addElement(rd.document);
2644
        
2645
      }
2646
      
2647
      /**
2648
       * gets an iterator of docids
2649
       */
2650
      public Iterator getDocids()
2651
      {
2652
        return docids.iterator();
2653
      }
2654
      
2655
      /**
2656
       * gets an iterator of documents
2657
       */
2658
      public Iterator getDocuments()
2659
      {
2660
        return documents.iterator();
2661
      }
2662
      
2663
      /**
2664
       * returns the size of the set
2665
       */
2666
      public int size()
2667
      {
2668
        return docids.size();
2669
      }
2670
      
2671
      /**
2672
       * tests to see if this set contains the given docid
2673
       */
2674
      private boolean containsDocid(String docid)
2675
      {
2676
        for(int i=0; i<docids.size(); i++)
2677
        {
2678
          String docid0 = (String)docids.elementAt(i);
2679
          if(docid0.trim().equals(docid.trim()))
2680
          {
2681
            return true;
2682
          }
2683
        }
2684
        return false;
2685
      }
2686
      
2687
      /**
2688
       * removes the element with the given docid
2689
       */
2690
      public String remove(String docid)
2691
      {
2692
        for(int i=0; i<docids.size(); i++)
2693
        {
2694
          String docid0 = (String)docids.elementAt(i);
2695
          if(docid0.trim().equals(docid.trim()))
2696
          {
2697
            String returnDoc = (String)documents.elementAt(i);
2698
            documents.remove(i);
2699
            docids.remove(i);
2700
            return returnDoc;
2701
          }
2702
        }
2703
        return null;
2704
      }
2705
      
2706
      /**
2707
       * add a result document
2708
       */
2709
      public void put(ResultDocument rd)
2710
      {
2711
        addResultDocument(rd);
2712
      }
2713
      
2714
      /**
2715
       * add a result document by components
2716
       */
2717
      public void put(String docid, String document)
2718
      {
2719
        addResultDocument(new ResultDocument(docid, document));
2720
      }
2721
      
2722
      /**
2723
       * get the document part of the result document by docid
2724
       */
2725
      public Object get(String docid)
2726
      {
2727
        for(int i=0; i<docids.size(); i++)
2728
        {
2729
          String docid0 = (String)docids.elementAt(i);
2730
          if(docid0.trim().equals(docid.trim()))
2731
          {
2732
            return documents.elementAt(i);
2733
          }
2734
        }
2735
        return null;
2736
      }
2737
      
2738
      /**
2739
       * get the document part of the result document by an object
2740
       */
2741
      public Object get(Object o)
2742
      {
2743
        return get((String)o);
2744
      }
2745
      
2746
      /**
2747
       * get an entire result document by index number
2748
       */
2749
      public ResultDocument get(int index)
2750
      {
2751
        return new ResultDocument((String)docids.elementAt(index), 
2752
          (String)documents.elementAt(index));
2753
      }
2754
      
2755
      /**
2756
       * return a string representation of this object
2757
       */
2758
      public String toString()
2759
      {
2760
        String s = "";
2761
        for(int i=0; i<docids.size(); i++)
2762
        {
2763
          s += (String)docids.elementAt(i) + "\n";
2764
        }
2765
        return s;
2766
      }
2767
      /*
2768
       * Set a new document value for a given docid
2769
       */
2770
      public void set(String docid, String document)
2771
      {
2772
    	   for(int i=0; i<docids.size(); i++)
2773
           {
2774
             String docid0 = (String)docids.elementAt(i);
2775
             if(docid0.trim().equals(docid.trim()))
2776
             {
2777
                 documents.set(i, document);
2778
             }
2779
           }
2780
           
2781
      }
2782
    }
2783
}
(17-17/64)