Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *
12
 *   '$Author: leinfelder $'
13
 *     '$Date: 2011-11-04 12:32:37 -0700 (Fri, 04 Nov 2011) $'
14
 * '$Revision: 6602 $'
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
    	  StringBuffer docidCondition = new StringBuffer();
641
    	  docidCondition.append( " docid IN (" );
642
          for (int i = 0; i < givenDocids.size(); i++) {  
643
        	  docidCondition.append("'");
644
        	  docidCondition.append( (String)givenDocids.elementAt(i) );
645
        	  docidCondition.append("'");
646
        	  if (i < givenDocids.size()-1) {
647
        		  docidCondition.append(",");
648
        	  }
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
    	  } else {
657
    		  // start with the keyword query, but add conditions
658
              query = qspec.printSQL(useXMLIndex, docidValues);
659
              parameterValues.addAll(docidValues);
660
              String myOperator = "";
661
              if (!query.endsWith("WHERE")) {
662
	              if (operator.equalsIgnoreCase(QueryGroup.UNION)) {
663
	            	  myOperator =  " OR ";
664
	              }
665
	              else {
666
	            	  myOperator =  " AND ";
667
	              }
668
              }
669
              query = query + myOperator + docidCondition.toString();
670

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

    
723
      double queryExecuteTime = System.currentTimeMillis() / 1000;
724
      logMetacat.debug("DBQuery.findResultDoclist - Time to execute select docid query is "
725
                    + (queryExecuteTime - startTime));
726
      MetacatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
727
              + (queryExecuteTime - startTime));
728
      MetacatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
729

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

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

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

    
868

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

    
887
     // get value of database.xmlReturnfieldCount
888
     int count = (new Integer(PropertyService
889
                            .getProperty("database.xmlReturnfieldCount")))
890
                            .intValue();
891

    
892
     // set enterRecords to true if usage_count is more than the offset
893
     // specified in metacat.properties
894
     if(usage_count > count){
895
         enterRecords = true;
896
     }
897

    
898
     if(returnfield_id < 0){
899
         logMetacat.warn("DBQuery.handleSubsetResult - Error in getting returnfield id from"
900
                                  + "xml_returnfield table");
901
         enterRecords = false;
902
     }
903

    
904
     // get the hashtable containing the docids that already in the
905
     // xml_queryresult table
906
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist before"
907
                             + " docidsInQueryresultTable(): "
908
                             + partOfDoclist.size());
909
     long startGetReturnValueFromQueryresultable = System.currentTimeMillis();
910
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
911
                                                        partOfDoclist, dbconn);
912

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

    
941
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist after"
942
                             + " docidsInQueryresultTable(): "
943
                             + partOfDoclist.size());
944

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

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

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

    
1009
         //send single element to output
1010
         if (out != null)
1011
         {
1012
             out.write(xmlElement);
1013
         }
1014
         resultset.append(xmlElement);
1015
     }//while
1016
     
1017
     double storeReturnFieldTime = System.currentTimeMillis() - startStoreReturnField;
1018
     long storeReturnFieldWarnLimit = 
1019
    	 Long.parseLong(PropertyService.getProperty("dbquery.storeReturnFieldTimeWarnLimit"));
1020

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

    
1047
     if (returnFieldTime > totalReturnFieldWarnLimit) {
1048
    	 logMetacat.warn("DBQuery.handleSubsetResult - Total time to get return fields is: "
1049
                           + returnFieldTime);
1050
     }
1051
     MetacatUtil.writeDebugToFile("DBQuery.handleSubsetResult - ---------------------------------------------------------------------------------------------------------------"+
1052
    		 "Total to get return fields  " + returnFieldTime);
1053
     MetacatUtil.writeDebugToDelimiteredFile("DBQuery.handleSubsetResult - "+ returnFieldTime, false);
1054
     return resultset;
1055
 }
1056

    
1057
   /**
1058
    * Get the docids already in xml_queryresult table and corresponding
1059
    * queryresultstring as a hashtable
1060
    */
1061
   private Hashtable docidsInQueryresultTable(int returnfield_id,
1062
                                              ResultDocumentSet partOfDoclist,
1063
                                              DBConnection dbconn){
1064

    
1065
         Hashtable returnValue = new Hashtable();
1066
         PreparedStatement pstmt = null;
1067
         ResultSet rs = null;
1068

    
1069
         // get partOfDoclist as string for the query
1070
         Iterator keylist = partOfDoclist.getDocids();
1071
         StringBuffer doclist = new StringBuffer();
1072
         while (keylist.hasNext())
1073
         {
1074
             doclist.append("'");
1075
             doclist.append((String) keylist.next());
1076
             doclist.append("',");
1077
         }//while
1078

    
1079

    
1080
         if (doclist.length() > 0)
1081
         {
1082
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1083

    
1084
             // the query to find out docids from xml_queryresult
1085
             String query = "select docid, queryresult_string from "
1086
                          + "xml_queryresult where returnfield_id = " +
1087
                          returnfield_id +" and docid in ("+ doclist + ")";
1088
             logMetacat.info("DBQuery.docidsInQueryresultTable - Query to get docids from xml_queryresult:"
1089
                                      + query);
1090

    
1091
             try {
1092
                 // prepare and execute the query
1093
                 pstmt = dbconn.prepareStatement(query);
1094
                 dbconn.increaseUsageCount(1);
1095
                 pstmt.execute();
1096
                 rs = pstmt.getResultSet();
1097
                 boolean tableHasRows = rs.next();
1098
                 while (tableHasRows) {
1099
                     // store the returned results in the returnValue hashtable
1100
                     String key = rs.getString(1);
1101
                     String element = rs.getString(2);
1102

    
1103
                     if(element != null){
1104
                         returnValue.put(key, element);
1105
                     } else {
1106
                         logMetacat.info("DBQuery.docidsInQueryresultTable - Null elment found ("
1107
                         + "DBQuery.docidsInQueryresultTable)");
1108
                     }
1109
                     tableHasRows = rs.next();
1110
                 }
1111
                 rs.close();
1112
                 pstmt.close();
1113
             } catch (Exception e){
1114
                 logMetacat.error("DBQuery.docidsInQueryresultTable - Error getting docids from "
1115
                                          + "queryresult: " + e.getMessage());
1116
              }
1117
         }
1118
         return returnValue;
1119
     }
1120

    
1121

    
1122
   /**
1123
    * Method to get id from xml_returnfield table
1124
    * for a given query specification
1125
    */
1126
   private int returnfield_id;
1127
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1128
                                           DBConnection dbconn){
1129
       int id = -1;
1130
       int count = 1;
1131
       PreparedStatement pstmt = null;
1132
       ResultSet rs = null;
1133
       String returnfield = qspec.getSortedReturnFieldString();
1134

    
1135
       // query for finding the id from xml_returnfield
1136
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1137
            + "WHERE returnfield_string LIKE ?";
1138
       logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Query:" + query);
1139

    
1140
       try {
1141
           // prepare and run the query
1142
           pstmt = dbconn.prepareStatement(query);
1143
           pstmt.setString(1,returnfield);
1144
           dbconn.increaseUsageCount(1);
1145
           pstmt.execute();
1146
           rs = pstmt.getResultSet();
1147
           boolean tableHasRows = rs.next();
1148

    
1149
           // if record found then increase the usage count
1150
           // else insert a new record and get the id of the new record
1151
           if(tableHasRows){
1152
               // get the id
1153
               id = rs.getInt(1);
1154
               count = rs.getInt(2) + 1;
1155
               rs.close();
1156
               pstmt.close();
1157

    
1158
               // increase the usage count
1159
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1160
                   + "' WHERE returnfield_id ='"+ id +"'";
1161
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Update:"+ query);
1162

    
1163
               pstmt = dbconn.prepareStatement(query);
1164
               dbconn.increaseUsageCount(1);
1165
               pstmt.execute();
1166
               pstmt.close();
1167

    
1168
           } else {
1169
               rs.close();
1170
               pstmt.close();
1171

    
1172
               // insert a new record
1173
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1174
                   + "VALUES (?, '1')";
1175
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Insert:"+ query);
1176
               pstmt = dbconn.prepareStatement(query);
1177
               pstmt.setString(1, returnfield);
1178
               dbconn.increaseUsageCount(1);
1179
               pstmt.execute();
1180
               pstmt.close();
1181

    
1182
               // get the id of the new record
1183
               query = "SELECT returnfield_id FROM xml_returnfield "
1184
                   + "WHERE returnfield_string LIKE ?";
1185
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField query after Insert:" + query);
1186
               pstmt = dbconn.prepareStatement(query);
1187
               pstmt.setString(1, returnfield);
1188

    
1189
               dbconn.increaseUsageCount(1);
1190
               pstmt.execute();
1191
               rs = pstmt.getResultSet();
1192
               if(rs.next()){
1193
                   id = rs.getInt(1);
1194
               } else {
1195
                   id = -1;
1196
               }
1197
               rs.close();
1198
               pstmt.close();
1199
           }
1200

    
1201
       } catch (Exception e){
1202
           logMetacat.error("DBQuery.getXmlReturnfieldsTableId - Error getting id from xml_returnfield in "
1203
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1204
                                     + e.getMessage());
1205
           id = -1;
1206
       }
1207

    
1208
       returnfield_id = id;
1209
       return count;
1210
   }
1211

    
1212

    
1213
    /*
1214
     * A method to add return field to return doclist hash table
1215
     */
1216
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1217
                                      QuerySpecification qspec,
1218
                                      String user, String[]groups,
1219
                                      DBConnection dbconn, boolean useXMLIndex,
1220
                                      String qformat)
1221
                                      throws Exception
1222
    {
1223
      PreparedStatement pstmt = null;
1224
      ResultSet rs = null;
1225
      String docid = null;
1226
      String fieldname = null;
1227
      String fieldtype = null;
1228
      String fielddata = null;
1229
      String relation = null;
1230

    
1231
      if (qspec.containsExtendedSQL())
1232
      {
1233
        qspec.setUserName(user);
1234
        qspec.setGroup(groups);
1235
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1236
        Vector results = new Vector();
1237
        Iterator keylist = docListResult.getDocids();
1238
        StringBuffer doclist = new StringBuffer();
1239
        Vector parentidList = new Vector();
1240
        Hashtable returnFieldValue = new Hashtable();
1241
        while (keylist.hasNext())
1242
        {
1243
          String key = (String)keylist.next();
1244
          doclist.append("'");
1245
          doclist.append(key);
1246
          doclist.append("',");
1247
        }
1248
        if (doclist.length() > 0)
1249
        {
1250
          Hashtable controlPairs = new Hashtable();
1251
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1252
          boolean tableHasRows = false;
1253
        
1254

    
1255
          // keep track of parameter values
1256
          List<Object> parameterValues = new ArrayList<Object>();
1257
           String extendedQuery =
1258
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex, parameterValues);
1259
           logMetacat.info("DBQuery.addReturnfield - Extended query: " + extendedQuery);
1260

    
1261
           if(extendedQuery != null){
1262
//        	   long extendedQueryStart = System.currentTimeMillis();
1263
               pstmt = dbconn.prepareStatement(extendedQuery);
1264
               // set the parameter values
1265
               pstmt = DBQuery.setPreparedStatementValues(parameterValues, pstmt);
1266
               //increase dbconnection usage count
1267
               dbconn.increaseUsageCount(1);
1268
               pstmt.execute();
1269
               rs = pstmt.getResultSet();
1270
               tableHasRows = rs.next();
1271
               while (tableHasRows) {
1272
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1273
                   docid = rs.getString(1).trim();
1274
                   fieldname = rs.getString(2);
1275
                   
1276
                   if(qformat.toLowerCase().trim().equals("xml"))
1277
                   {
1278
                       byte[] b = rs.getBytes(3);
1279
                       fielddata = new String(b, 0, b.length, MetaCatServlet.DEFAULT_ENCODING);
1280
                   }
1281
                   else
1282
                   {
1283
                       fielddata = rs.getString(3);
1284
                   }
1285
                   
1286
                   //System.out.println("raw fielddata: " + fielddata);
1287
                   fielddata = MetacatUtil.normalize(fielddata);
1288
                   //System.out.println("normalized fielddata: " + fielddata);
1289
                   String parentId = rs.getString(4);
1290
                   fieldtype = rs.getString(5);
1291
                   StringBuffer value = new StringBuffer();
1292

    
1293
                   //handle case when usexmlindex is true differently
1294
                   //at one point merging the nodedata (for large text elements) was 
1295
                   //deemed unnecessary - but now it is needed.  but not for attribute nodes
1296
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1297
                	   //merge node data only for non-ATTRIBUTEs
1298
                	   if (fieldtype != null && !fieldtype.equals("ATTRIBUTE")) {
1299
	                	   //try merging the data
1300
	                	   ReturnFieldValue existingRFV =
1301
	                		   getArrayValue(parentidList, parentId);
1302
	                	   if (existingRFV != null && !existingRFV.getFieldType().equals("ATTRIBUTE")) {
1303
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1304
	                	   }
1305
                	   }
1306
                	   //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1307

    
1308
                       value.append("<param name=\"");
1309
                       value.append(fieldname);
1310
                       value.append("\">");
1311
                       value.append(fielddata);
1312
                       value.append("</param>");
1313
                       //set returnvalue
1314
                       returnValue.setDocid(docid);
1315
                       returnValue.setFieldValue(fielddata);
1316
                       returnValue.setFieldType(fieldtype);
1317
                       returnValue.setXMLFieldValue(value.toString());
1318
                       // Store it in hastable
1319
                       putInArray(parentidList, parentId, returnValue);
1320
                   }
1321
                   else {
1322
                       
1323
                       // need to merge nodedata if they have same parent id and
1324
                       // node type is text
1325
                       fielddata = (String) ( (ReturnFieldValue)
1326
                                             getArrayValue(
1327
                           parentidList, parentId)).getFieldValue()
1328
                           + fielddata;
1329
                       //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1330
                       value.append("<param name=\"");
1331
                       value.append(fieldname);
1332
                       value.append("\">");
1333
                       value.append(fielddata);
1334
                       value.append("</param>");
1335
                       returnValue.setDocid(docid);
1336
                       returnValue.setFieldValue(fielddata);
1337
                       returnValue.setFieldType(fieldtype);
1338
                       returnValue.setXMLFieldValue(value.toString());
1339
                       // remove the old return value from paretnidList
1340
                       parentidList.remove(parentId);
1341
                       // store the new return value in parentidlit
1342
                       putInArray(parentidList, parentId, returnValue);
1343
                   }
1344
                   tableHasRows = rs.next();
1345
               } //while
1346
               rs.close();
1347
               pstmt.close();
1348

    
1349
               // put the merger node data info into doclistReult
1350
               Enumeration xmlFieldValue = (getElements(parentidList)).
1351
                   elements();
1352
               while (xmlFieldValue.hasMoreElements()) {
1353
                   ReturnFieldValue object =
1354
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1355
                   docid = object.getDocid();
1356
                   if (docListResult.containsDocid(docid)) {
1357
                       String removedelement = (String) docListResult.
1358
                           remove(docid);
1359
                       docListResult.
1360
                           addResultDocument(new ResultDocument(docid,
1361
                               removedelement + object.getXMLFieldValue()));
1362
                   }
1363
                   else {
1364
                       docListResult.addResultDocument(
1365
                         new ResultDocument(docid, object.getXMLFieldValue()));
1366
                   }
1367
               } //while
1368
//               double docListResultEnd = System.currentTimeMillis() / 1000;
1369
//               logMetacat.warn(
1370
//                   "Time to prepare ResultDocumentSet after"
1371
//                   + " execute extended query: "
1372
//                   + (docListResultEnd - extendedQueryEnd));
1373
           }
1374
       }//if doclist lenght is great than zero
1375
     }//if has extended query
1376

    
1377
      return docListResult;
1378
    }//addReturnfield
1379

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

    
1489

    
1490
    /*
1491
     * A method to search if Vector contains a particular key string
1492
     */
1493
    private boolean containsKey(Vector parentidList, String parentId)
1494
    {
1495

    
1496
        Vector tempVector = null;
1497

    
1498
        for (int count = 0; count < parentidList.size(); count++) {
1499
            tempVector = (Vector) parentidList.get(count);
1500
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1501
        }
1502
        return false;
1503
    }
1504
    
1505
    /*
1506
     * A method to put key and value in Vector
1507
     */
1508
    private void putInArray(Vector parentidList, String key,
1509
            ReturnFieldValue value)
1510
    {
1511

    
1512
        Vector tempVector = null;
1513
        //only filter if the field type is NOT an attribute (say, for text)
1514
        String fieldType = value.getFieldType();
1515
        if (fieldType != null && !fieldType.equals("ATTRIBUTE")) {
1516
        
1517
	        for (int count = 0; count < parentidList.size(); count++) {
1518
	            tempVector = (Vector) parentidList.get(count);
1519
	
1520
	            if (key.compareTo((String) tempVector.get(0)) == 0) {
1521
	                tempVector.remove(1);
1522
	                tempVector.add(1, value);
1523
	                return;
1524
	            }
1525
	        }
1526
        }
1527

    
1528
        tempVector = new Vector();
1529
        tempVector.add(0, key);
1530
        tempVector.add(1, value);
1531
        parentidList.add(tempVector);
1532
        return;
1533
    }
1534

    
1535
    /*
1536
     * A method to get value in Vector given a key
1537
     */
1538
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1539
    {
1540

    
1541
        Vector tempVector = null;
1542

    
1543
        for (int count = 0; count < parentidList.size(); count++) {
1544
            tempVector = (Vector) parentidList.get(count);
1545

    
1546
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1547
                    .get(1); }
1548
        }
1549
        return null;
1550
    }
1551

    
1552
    /*
1553
     * A method to get enumeration of all values in Vector
1554
     */
1555
    private Vector getElements(Vector parentidList)
1556
    {
1557
        Vector enumVector = new Vector();
1558
        Vector tempVector = null;
1559

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

    
1563
            enumVector.add(tempVector.get(1));
1564
        }
1565
        return enumVector;
1566
    }
1567

    
1568
  
1569

    
1570
    /*
1571
     * A method to create a query to get owner's docid list
1572
     */
1573
    private String getOwnerQuery(String owner)
1574
    {
1575
        if (owner != null) {
1576
            owner = owner.toLowerCase();
1577
        }
1578
        StringBuffer self = new StringBuffer();
1579

    
1580
        self.append("SELECT docid,docname,doctype,");
1581
        self.append("date_created, date_updated, rev ");
1582
        self.append("FROM xml_documents WHERE docid IN (");
1583
        self.append("(");
1584
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1585
        self.append("nodedata LIKE '%%%' ");
1586
        self.append(") \n");
1587
        self.append(") ");
1588
        self.append(" AND (");
1589
        self.append(" lower(user_owner) = '" + owner + "'");
1590
        self.append(") ");
1591
        return self.toString();
1592
    }
1593

    
1594
    /**
1595
     * format a structured query as an XML document that conforms to the
1596
     * pathquery.dtd and is appropriate for submission to the DBQuery
1597
     * structured query engine
1598
     *
1599
     * @param params The list of parameters that should be included in the
1600
     *            query
1601
     */
1602
    public static String createSQuery(Hashtable params) throws PropertyNotFoundException
1603
    {
1604
        StringBuffer query = new StringBuffer();
1605
        Enumeration elements;
1606
        Enumeration keys;
1607
        String filterDoctype = null;
1608
        String casesensitive = null;
1609
        String searchmode = null;
1610
        Object nextkey;
1611
        Object nextelement;
1612
        //add the xml headers
1613
        query.append("<?xml version=\"1.0\"?>\n");
1614
        query.append("<pathquery version=\"1.2\">\n");
1615

    
1616

    
1617

    
1618
        if (params.containsKey("meta_file_id")) {
1619
            query.append("<meta_file_id>");
1620
            query.append(((String[]) params.get("meta_file_id"))[0]);
1621
            query.append("</meta_file_id>");
1622
        }
1623

    
1624
        if (params.containsKey("returndoctype")) {
1625
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1626
            for (int i = 0; i < returnDoctypes.length; i++) {
1627
                String doctype = (String) returnDoctypes[i];
1628

    
1629
                if (!doctype.equals("any") && !doctype.equals("ANY")
1630
                        && !doctype.equals("")) {
1631
                    query.append("<returndoctype>").append(doctype);
1632
                    query.append("</returndoctype>");
1633
                }
1634
            }
1635
        }
1636

    
1637
        if (params.containsKey("filterdoctype")) {
1638
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1639
            for (int i = 0; i < filterDoctypes.length; i++) {
1640
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1641
                query.append("</filterdoctype>");
1642
            }
1643
        }
1644

    
1645
        if (params.containsKey("returnfield")) {
1646
            String[] returnfield = ((String[]) params.get("returnfield"));
1647
            for (int i = 0; i < returnfield.length; i++) {
1648
                query.append("<returnfield>").append(returnfield[i]);
1649
                query.append("</returnfield>");
1650
            }
1651
        }
1652

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

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

    
1669
        //allows the dynamic switching of boolean operators
1670
        if (params.containsKey("operator")) {
1671
            query.append("<querygroup operator=\""
1672
                    + ((String[]) params.get("operator"))[0] + "\">");
1673
        } else { //the default operator is UNION
1674
            query.append("<querygroup operator=\"UNION\">");
1675
        }
1676

    
1677
        if (params.containsKey("casesensitive")) {
1678
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1679
        } else {
1680
            casesensitive = "false";
1681
        }
1682

    
1683
        if (params.containsKey("searchmode")) {
1684
            searchmode = ((String[]) params.get("searchmode"))[0];
1685
        } else {
1686
            searchmode = "contains";
1687
        }
1688

    
1689
        //anyfield is a special case because it does a
1690
        //free text search. It does not have a <pathexpr>
1691
        //tag. This allows for a free text search within the structured
1692
        //query. This is useful if the INTERSECT operator is used.
1693
        if (params.containsKey("anyfield")) {
1694
            String[] anyfield = ((String[]) params.get("anyfield"));
1695
            //allow for more than one value for anyfield
1696
            for (int i = 0; i < anyfield.length; i++) {
1697
                if (anyfield[i] != null && !anyfield[i].equals("")) {
1698
                    query.append("<queryterm casesensitive=\"" + casesensitive
1699
                            + "\" " + "searchmode=\"" + searchmode
1700
                            + "\"><value>" + anyfield[i]
1701
                            + "</value></queryterm>");
1702
                }
1703
            }
1704
        }
1705

    
1706
        //this while loop finds the rest of the parameters
1707
        //and attempts to query for the field specified
1708
        //by the parameter.
1709
        elements = params.elements();
1710
        keys = params.keys();
1711
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1712
            nextkey = keys.nextElement();
1713
            nextelement = elements.nextElement();
1714

    
1715
            //make sure we aren't querying for any of these
1716
            //parameters since the are already in the query
1717
            //in one form or another.
1718
            Vector ignoredParams = new Vector();
1719
            ignoredParams.add("returndoctype");
1720
            ignoredParams.add("filterdoctype");
1721
            ignoredParams.add("action");
1722
            ignoredParams.add("qformat");
1723
            ignoredParams.add("anyfield");
1724
            ignoredParams.add("returnfield");
1725
            ignoredParams.add("owner");
1726
            ignoredParams.add("site");
1727
            ignoredParams.add("operator");
1728
            ignoredParams.add("sessionid");
1729
            ignoredParams.add("pagesize");
1730
            ignoredParams.add("pagestart");
1731
            ignoredParams.add("searchmode");
1732

    
1733
            // Also ignore parameters listed in the properties file
1734
            // so that they can be passed through to stylesheets
1735
            String paramsToIgnore = PropertyService
1736
                    .getProperty("database.queryignoredparams");
1737
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1738
            while (st.hasMoreTokens()) {
1739
                ignoredParams.add(st.nextToken());
1740
            }
1741
            if (!ignoredParams.contains(nextkey.toString())) {
1742
                //allow for more than value per field name
1743
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1744
                    if (!((String[]) nextelement)[i].equals("")) {
1745
                        query.append("<queryterm casesensitive=\""
1746
                                + casesensitive + "\" " + "searchmode=\""
1747
                                + searchmode + "\">" + "<value>" +
1748
                                //add the query value
1749
                                ((String[]) nextelement)[i]
1750
                                + "</value><pathexpr>" +
1751
                                //add the path to query by
1752
                                nextkey.toString() + "</pathexpr></queryterm>");
1753
                    }
1754
                }
1755
            }
1756
        }
1757
        query.append("</querygroup></pathquery>");
1758
        //append on the end of the xml and return the result as a string
1759
        return query.toString();
1760
    }
1761

    
1762
    /**
1763
     * format a simple free-text value query as an XML document that conforms
1764
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1765
     * structured query engine
1766
     *
1767
     * @param value the text string to search for in the xml catalog
1768
     * @param doctype the type of documents to include in the result set -- use
1769
     *            "any" or "ANY" for unfiltered result sets
1770
     */
1771
    public static String createQuery(String value, String doctype)
1772
    {
1773
        StringBuffer xmlquery = new StringBuffer();
1774
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1775
        xmlquery.append("<pathquery version=\"1.0\">");
1776

    
1777
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1778
            xmlquery.append("<returndoctype>");
1779
            xmlquery.append(doctype).append("</returndoctype>");
1780
        }
1781

    
1782
        xmlquery.append("<querygroup operator=\"UNION\">");
1783
        //chad added - 8/14
1784
        //the if statement allows a query to gracefully handle a null
1785
        //query. Without this if a nullpointerException is thrown.
1786
        if (!value.equals("")) {
1787
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1788
            xmlquery.append("searchmode=\"contains\">");
1789
            xmlquery.append("<value>").append(value).append("</value>");
1790
            xmlquery.append("</queryterm>");
1791
        }
1792
        xmlquery.append("</querygroup>");
1793
        xmlquery.append("</pathquery>");
1794

    
1795
        return (xmlquery.toString());
1796
    }
1797

    
1798
    /**
1799
     * format a simple free-text value query as an XML document that conforms
1800
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1801
     * structured query engine
1802
     *
1803
     * @param value the text string to search for in the xml catalog
1804
     */
1805
    public static String createQuery(String value)
1806
    {
1807
        return createQuery(value, "any");
1808
    }
1809

    
1810
    /**
1811
     * Check for "READ" permission on @docid for @user and/or @group from DB
1812
     * connection
1813
     */
1814
    private boolean hasPermission(String user, String[] groups, String docid)
1815
            throws SQLException, Exception
1816
    {
1817
        // Check for READ permission on @docid for @user and/or @groups
1818
        PermissionController controller = new PermissionController(docid);
1819
        return controller.hasPermission(user, groups,
1820
                AccessControlInterface.READSTRING);
1821
    }
1822

    
1823
    /**
1824
     * Get all docIds list for a data packadge
1825
     *
1826
     * @param dataPackageDocid, the string in docId field of xml_relation table
1827
     */
1828
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1829
    {
1830
        DBConnection dbConn = null;
1831
        int serialNumber = -1;
1832
        Vector docIdList = new Vector();//return value
1833
        PreparedStatement pStmt = null;
1834
        ResultSet rs = null;
1835
        String docIdInSubjectField = null;
1836
        String docIdInObjectField = null;
1837

    
1838
        // Check the parameter
1839
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1840

    
1841
        //the query stirng
1842
        String query = "SELECT subject, object from xml_relation where docId = ?";
1843
        try {
1844
            dbConn = DBConnectionPool
1845
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1846
            serialNumber = dbConn.getCheckOutSerialNumber();
1847
            pStmt = dbConn.prepareStatement(query);
1848
            //bind the value to query
1849
            pStmt.setString(1, dataPackageDocid);
1850

    
1851
            //excute the query
1852
            pStmt.execute();
1853
            //get the result set
1854
            rs = pStmt.getResultSet();
1855
            //process the result
1856
            while (rs.next()) {
1857
                //In order to get the whole docIds in a data packadge,
1858
                //we need to put the docIds of subject and object field in
1859
                // xml_relation
1860
                //into the return vector
1861
                docIdInSubjectField = rs.getString(1);//the result docId in
1862
                                                      // subject field
1863
                docIdInObjectField = rs.getString(2);//the result docId in
1864
                                                     // object field
1865

    
1866
                //don't put the duplicate docId into the vector
1867
                if (!docIdList.contains(docIdInSubjectField)) {
1868
                    docIdList.add(docIdInSubjectField);
1869
                }
1870

    
1871
                //don't put the duplicate docId into the vector
1872
                if (!docIdList.contains(docIdInObjectField)) {
1873
                    docIdList.add(docIdInObjectField);
1874
                }
1875
            }//while
1876
            //close the pStmt
1877
            pStmt.close();
1878
        }//try
1879
        catch (SQLException e) {
1880
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - Error in getDocidListForDataPackage: "
1881
                    + e.getMessage());
1882
        }//catch
1883
        finally {
1884
            try {
1885
                pStmt.close();
1886
            }//try
1887
            catch (SQLException ee) {
1888
                logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - SQL Error: "
1889
                                + ee.getMessage());
1890
            }//catch
1891
            finally {
1892
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1893
            }//fianlly
1894
        }//finally
1895
        return docIdList;
1896
    }//getCurrentDocidListForDataPackadge()
1897

    
1898
    /**
1899
     * Get all docIds list for a data packadge
1900
     *
1901
     * @param dataPackageDocid, the string in docId field of xml_relation table
1902
     */
1903
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1904
    {
1905

    
1906
        Vector docIdList = new Vector();//return value
1907
        Vector tripleList = null;
1908
        String xml = null;
1909

    
1910
        // Check the parameter
1911
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1912

    
1913
        try {
1914
            //initial a documentImpl object
1915
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1916
            //transfer to documentImpl object to string
1917
            xml = packageDocument.toString();
1918

    
1919
            //create a tripcollection object
1920
            TripleCollection tripleForPackage = new TripleCollection(
1921
                    new StringReader(xml));
1922
            //get the vetor of triples
1923
            tripleList = tripleForPackage.getCollection();
1924

    
1925
            for (int i = 0; i < tripleList.size(); i++) {
1926
                //put subject docid into docIdlist without duplicate
1927
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1928
                        .getSubject())) {
1929
                    //put subject docid into docIdlist
1930
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1931
                }
1932
                //put object docid into docIdlist without duplicate
1933
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1934
                        .getObject())) {
1935
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1936
                }
1937
            }//for
1938
        }//try
1939
        catch (Exception e) {
1940
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - General error: "
1941
                    + e.getMessage());
1942
        }//catch
1943

    
1944
        // return result
1945
        return docIdList;
1946
    }//getDocidListForPackageInXMLRevisions()
1947

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

    
2000
    public String getOperator() {
2001
		return operator;
2002
	}
2003

    
2004
    /**
2005
     * Specifies if and how docid overrides should be included in the general query
2006
     * @param operator null, UNION, or INTERSECT (see QueryGroup)
2007
     */
2008
	public void setOperator(String operator) {
2009
		this.operator = operator;
2010
	}
2011

    
2012
	/**
2013
     * Check if the user has the permission to export data package
2014
     *
2015
     * @param conn, the connection
2016
     * @param docId, the id need to be checked
2017
     * @param user, the name of user
2018
     * @param groups, the user's group
2019
     */
2020
    private boolean hasPermissionToExportPackage(String docId, String user,
2021
            String[] groups) throws Exception
2022
    {
2023
        //DocumentImpl doc=new DocumentImpl(conn,docId);
2024
        return DocumentImpl.hasReadPermission(user, groups, docId);
2025
    }
2026

    
2027
    /**
2028
     * Get the current Rev for a docid in xml_documents table
2029
     *
2030
     * @param docId, the id need to get version numb If the return value is -5,
2031
     *            means no value in rev field for this docid
2032
     */
2033
    private int getCurrentRevFromXMLDoumentsTable(String docId)
2034
            throws SQLException
2035
    {
2036
        int rev = -5;
2037
        PreparedStatement pStmt = null;
2038
        ResultSet rs = null;
2039
        String query = "SELECT rev from xml_documents where docId = ?";
2040
        DBConnection dbConn = null;
2041
        int serialNumber = -1;
2042
        try {
2043
            dbConn = DBConnectionPool
2044
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
2045
            serialNumber = dbConn.getCheckOutSerialNumber();
2046
            pStmt = dbConn.prepareStatement(query);
2047
            //bind the value to query
2048
            pStmt.setString(1, docId);
2049
            //execute the query
2050
            pStmt.execute();
2051
            rs = pStmt.getResultSet();
2052
            //process the result
2053
            if (rs.next()) //There are some records for rev
2054
            {
2055
                rev = rs.getInt(1);
2056
                ;//It is the version for given docid
2057
            } else {
2058
                rev = -5;
2059
            }
2060

    
2061
        }//try
2062
        catch (SQLException e) {
2063
            logMetacat.error("DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
2064
                            + e.getMessage());
2065
            throw e;
2066
        }//catch
2067
        finally {
2068
            try {
2069
                pStmt.close();
2070
            }//try
2071
            catch (SQLException ee) {
2072
                logMetacat.error(
2073
                        "DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
2074
                                + ee.getMessage());
2075
            }//catch
2076
            finally {
2077
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2078
            }//finally
2079
        }//finally
2080
        return rev;
2081
    }//getCurrentRevFromXMLDoumentsTable
2082

    
2083
    /**
2084
     * put a doc into a zip output stream
2085
     *
2086
     * @param docImpl, docmentImpl object which will be sent to zip output
2087
     *            stream
2088
     * @param zipOut, zip output stream which the docImpl will be put
2089
     * @param packageZipEntry, the zip entry name for whole package
2090
     */
2091
    private void addDocToZipOutputStream(DocumentImpl docImpl,
2092
            ZipOutputStream zipOut, String packageZipEntry)
2093
            throws ClassNotFoundException, IOException, SQLException,
2094
            McdbException, Exception
2095
    {
2096
        byte[] byteString = null;
2097
        ZipEntry zEntry = null;
2098

    
2099
        byteString = docImpl.getBytes();
2100
        //use docId as the zip entry's name
2101
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
2102
                + docImpl.getDocID());
2103
        zEntry.setSize(byteString.length);
2104
        zipOut.putNextEntry(zEntry);
2105
        zipOut.write(byteString, 0, byteString.length);
2106
        zipOut.closeEntry();
2107

    
2108
    }//addDocToZipOutputStream()
2109

    
2110
    /**
2111
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
2112
     * only inlcudes current version. If a DocumentImple object couldn't find
2113
     * for a docid, then the String of this docid was added to vetor rather
2114
     * than DocumentImple object.
2115
     *
2116
     * @param docIdList, a vetor hold a docid list for a data package. In
2117
     *            docid, there is not version number in it.
2118
     */
2119

    
2120
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2121
            throws McdbException, Exception
2122
    {
2123
        //Connection dbConn=null;
2124
        Vector documentImplList = new Vector();
2125
        int rev = 0;
2126

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

    
2130
        //for every docid in vector
2131
        for (int i = 0; i < docIdList.size(); i++) {
2132
            try {
2133
                //get newest version for this docId
2134
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2135
                        .elementAt(i));
2136

    
2137
                // There is no record for this docId in xml_documents table
2138
                if (rev == -5) {
2139
                    // Rather than put DocumentImple object, put a String
2140
                    // Object(docid)
2141
                    // into the documentImplList
2142
                    documentImplList.add((String) docIdList.elementAt(i));
2143
                    // Skip other code
2144
                    continue;
2145
                }
2146

    
2147
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2148
                        + PropertyService.getProperty("document.accNumSeparator") + rev;
2149

    
2150
                //create new documentImpl object
2151
                DocumentImpl documentImplObject = new DocumentImpl(
2152
                        docidPlusVersion);
2153
                //add them to vector
2154
                documentImplList.add(documentImplObject);
2155
            }//try
2156
            catch (Exception e) {
2157
                logMetacat.error("DBQuery.getCurrentAllDocumentImpl - General error: "
2158
                        + e.getMessage());
2159
                // continue the for loop
2160
                continue;
2161
            }
2162
        }//for
2163
        return documentImplList;
2164
    }
2165

    
2166
    /**
2167
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2168
     * object couldn't find for a docid, then the String of this docid was
2169
     * added to vetor rather than DocumentImple object.
2170
     *
2171
     * @param docIdList, a vetor hold a docid list for a data package. In
2172
     *            docid, t here is version number in it.
2173
     */
2174
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2175
    {
2176
        //Connection dbConn=null;
2177
        Vector documentImplList = new Vector();
2178
        String siteCode = null;
2179
        String uniqueId = null;
2180
        int rev = 0;
2181

    
2182
        // Check the parameter
2183
        if (docIdList.isEmpty()) { return documentImplList; }//if
2184

    
2185
        //for every docid in vector
2186
        for (int i = 0; i < docIdList.size(); i++) {
2187

    
2188
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2189

    
2190
            try {
2191
                //create new documentImpl object
2192
                DocumentImpl documentImplObject = new DocumentImpl(
2193
                        docidPlusVersion);
2194
                //add them to vector
2195
                documentImplList.add(documentImplObject);
2196
            }//try
2197
            catch (McdbDocNotFoundException notFoundE) {
2198
                logMetacat.error("DBQuery.getOldVersionAllDocument - Error finding doc " 
2199
                		+ docidPlusVersion + " : " + notFoundE.getMessage());
2200
                // Rather than add a DocumentImple object into vetor, a String
2201
                // object
2202
                // - the doicd was added to the vector
2203
                documentImplList.add(docidPlusVersion);
2204
                // Continue the for loop
2205
                continue;
2206
            }//catch
2207
            catch (Exception e) {
2208
                logMetacat.error(
2209
                        "DBQuery.getOldVersionAllDocument - General error: "
2210
                                + e.getMessage());
2211
                // Continue the for loop
2212
                continue;
2213
            }//catch
2214

    
2215
        }//for
2216
        return documentImplList;
2217
    }//getOldVersionAllDocumentImple
2218

    
2219
    /**
2220
     * put a data file into a zip output stream
2221
     *
2222
     * @param docImpl, docmentImpl object which will be sent to zip output
2223
     *            stream
2224
     * @param zipOut, the zip output stream which the docImpl will be put
2225
     * @param packageZipEntry, the zip entry name for whole package
2226
     */
2227
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2228
            ZipOutputStream zipOut, String packageZipEntry)
2229
            throws ClassNotFoundException, IOException, SQLException,
2230
            McdbException, Exception
2231
    {
2232
        byte[] byteString = null;
2233
        ZipEntry zEntry = null;
2234
        // this is data file; add file to zip
2235
        String filePath = PropertyService.getProperty("application.datafilepath");
2236
        if (!filePath.endsWith("/")) {
2237
            filePath += "/";
2238
        }
2239
        String fileName = filePath + docImpl.getDocID();
2240
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2241
        zipOut.putNextEntry(zEntry);
2242
        FileInputStream fin = null;
2243
        try {
2244
            fin = new FileInputStream(fileName);
2245
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2246
            int b = fin.read(buf);
2247
            while (b != -1) {
2248
                zipOut.write(buf, 0, b);
2249
                b = fin.read(buf);
2250
            }//while
2251
            zipOut.closeEntry();
2252
        }//try
2253
        catch (IOException ioe) {
2254
            logMetacat.error("DBQuery.addDataFileToZipOutputStream - I/O error: "
2255
                    + ioe.getMessage());
2256
        }//catch
2257
    }//addDataFileToZipOutputStream()
2258

    
2259
    /**
2260
     * create a html summary for data package and put it into zip output stream
2261
     *
2262
     * @param docImplList, the documentImpl ojbects in data package
2263
     * @param zipOut, the zip output stream which the html should be put
2264
     * @param packageZipEntry, the zip entry name for whole package
2265
     */
2266
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2267
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2268
    {
2269
        StringBuffer htmlDoc = new StringBuffer();
2270
        ZipEntry zEntry = null;
2271
        byte[] byteString = null;
2272
        InputStream source;
2273
        DBTransform xmlToHtml;
2274

    
2275
        //create a DBTransform ojbect
2276
        xmlToHtml = new DBTransform();
2277
        //head of html
2278
        htmlDoc.append("<html><head></head><body>");
2279
        for (int i = 0; i < docImplList.size(); i++) {
2280
            // If this String object, this means it is missed data file
2281
            if ((((docImplList.elementAt(i)).getClass()).toString())
2282
                    .equals("class java.lang.String")) {
2283

    
2284
                htmlDoc.append("<a href=\"");
2285
                String dataFileid = (String) docImplList.elementAt(i);
2286
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2287
                htmlDoc.append("Data File: ");
2288
                htmlDoc.append(dataFileid).append("</a><br>");
2289
                htmlDoc.append("<br><hr><br>");
2290

    
2291
            }//if
2292
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2293
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2294
                                              // transform it.
2295
                //transform each file individually then concatenate all of the
2296
                //transformations together.
2297

    
2298
                //for metadata xml title
2299
                htmlDoc.append("<h2>");
2300
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2301
                        .getDocID());
2302
                //htmlDoc.append(".");
2303
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2304
                htmlDoc.append("</h2>");
2305
                //do the actual transform
2306
                StringWriter docString = new StringWriter();
2307
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2308
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2309
                        "-//W3C//HTML//EN", "html", docString, null, null);
2310
                htmlDoc.append(docString.toString());
2311
                htmlDoc.append("<br><br><hr><br><br>");
2312
            }//if
2313
            else { //this is a data file so we should link to it in the html
2314
                htmlDoc.append("<a href=\"");
2315
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2316
                        .getDocID();
2317
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2318
                htmlDoc.append("Data File: ");
2319
                htmlDoc.append(dataFileid).append("</a><br>");
2320
                htmlDoc.append("<br><hr><br>");
2321
            }//else
2322
        }//for
2323
        htmlDoc.append("</body></html>");
2324
        // use standard encoding even though the different docs might have use different encodings,
2325
        // the String objects in java should be correct and able to be encoded as the same Metacat default
2326
        byteString = htmlDoc.toString().getBytes(MetaCatServlet.DEFAULT_ENCODING);
2327
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2328
        zEntry.setSize(byteString.length);
2329
        zipOut.putNextEntry(zEntry);
2330
        zipOut.write(byteString, 0, byteString.length);
2331
        zipOut.closeEntry();
2332
        //dbConn.close();
2333

    
2334
    }//addHtmlSummaryToZipOutputStream
2335

    
2336
    /**
2337
     * put a data packadge into a zip output stream
2338
     *
2339
     * @param docId, which the user want to put into zip output stream,it has version
2340
     * @param out, a servletoutput stream which the zip output stream will be
2341
     *            put
2342
     * @param user, the username of the user
2343
     * @param groups, the group of the user
2344
     */
2345
    public ZipOutputStream getZippedPackage(String docIdString,
2346
            ServletOutputStream out, String user, String[] groups,
2347
            String passWord) throws ClassNotFoundException, IOException,
2348
            SQLException, McdbException, NumberFormatException, Exception
2349
    {
2350
        ZipOutputStream zOut = null;
2351
        String elementDocid = null;
2352
        DocumentImpl docImpls = null;
2353
        //Connection dbConn = null;
2354
        Vector docIdList = new Vector();
2355
        Vector documentImplList = new Vector();
2356
        Vector htmlDocumentImplList = new Vector();
2357
        String packageId = null;
2358
        String rootName = "package";//the package zip entry name
2359

    
2360
        String docId = null;
2361
        int version = -5;
2362
        // Docid without revision
2363
        docId = DocumentUtil.getDocIdFromString(docIdString);
2364
        // revision number
2365
        version = DocumentUtil.getVersionFromString(docIdString);
2366

    
2367
        //check if the reqused docId is a data package id
2368
        if (!isDataPackageId(docId)) {
2369

    
2370
            /*
2371
             * Exception e = new Exception("The request the doc id "
2372
             * +docIdString+ " is not a data package id");
2373
             */
2374

    
2375
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2376
            // zip
2377
            //up the single document and return the zip file.
2378
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2379

    
2380
                Exception e = new Exception("User " + user
2381
                        + " does not have permission"
2382
                        + " to export the data package " + docIdString);
2383
                throw e;
2384
            }
2385

    
2386
            docImpls = new DocumentImpl(docIdString);
2387
            //checking if the user has the permission to read the documents
2388
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2389
                    .getDocID())) {
2390
                zOut = new ZipOutputStream(out);
2391
                //if the docImpls is metadata
2392
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2393
                    //add metadata into zip output stream
2394
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2395
                }//if
2396
                else {
2397
                    //it is data file
2398
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2399
                    htmlDocumentImplList.add(docImpls);
2400
                }//else
2401
            }//if
2402

    
2403
            zOut.finish(); //terminate the zip file
2404
            return zOut;
2405
        }
2406
        // Check the permission of user
2407
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2408

    
2409
            Exception e = new Exception("User " + user
2410
                    + " does not have permission"
2411
                    + " to export the data package " + docIdString);
2412
            throw e;
2413
        } else //it is a packadge id
2414
        {
2415
            //store the package id
2416
            packageId = docId;
2417
            //get current version in database
2418
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2419
            //If it is for current version (-1 means user didn't specify
2420
            // revision)
2421
            if ((version == -1) || version == currentVersion) {
2422
                //get current version number
2423
                version = currentVersion;
2424
                //get package zip entry name
2425
                //it should be docId.revsion.package
2426
                rootName = packageId + PropertyService.getProperty("document.accNumSeparator")
2427
                        + version + PropertyService.getProperty("document.accNumSeparator")
2428
                        + "package";
2429
                //get the whole id list for data packadge
2430
                docIdList = getCurrentDocidListForDataPackage(packageId);
2431
                //get the whole documentImple object
2432
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2433

    
2434
            }//if
2435
            else if (version > currentVersion || version < -1) {
2436
                throw new Exception("The user specified docid: " + docId + "."
2437
                        + version + " doesn't exist");
2438
            }//else if
2439
            else //for an old version
2440
            {
2441

    
2442
                rootName = docIdString
2443
                        + PropertyService.getProperty("document.accNumSeparator") + "package";
2444
                //get the whole id list for data packadge
2445
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2446

    
2447
                //get the whole documentImple object
2448
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2449
            }//else
2450

    
2451
            // Make sure documentImplist is not empty
2452
            if (documentImplList.isEmpty()) { throw new Exception(
2453
                    "Couldn't find component for data package: " + packageId); }//if
2454

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

    
2497
                }//if
2498
                else {
2499
                    //create a docmentImpls object (represent xml doc) base on
2500
                    // the docId
2501
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2502
                    //checking if the user has the permission to read the
2503
                    // documents
2504
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2505
                            .getDocID())) {
2506
                        //if the docImpls is metadata
2507
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2508
                            //add metadata into zip output stream
2509
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2510
                            //add the documentImpl into the vetor which will
2511
                            // be used in html
2512
                            htmlDocumentImplList.add(docImpls);
2513

    
2514
                        }//if
2515
                        else {
2516
                            //it is data file
2517
                            addDataFileToZipOutputStream(docImpls, zOut,
2518
                                    rootName);
2519
                            htmlDocumentImplList.add(docImpls);
2520
                        }//else
2521
                    }//if
2522
                }//else
2523
            }//for
2524

    
2525
            //add html summary file
2526
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2527
                    rootName);
2528
            zOut.finish(); //terminate the zip file
2529
            //dbConn.close();
2530
            return zOut;
2531
        }//else
2532
    }//getZippedPackage()
2533

    
2534
    private class ReturnFieldValue
2535
    {
2536

    
2537
        private String docid = null; //return field value for this docid
2538

    
2539
        private String fieldValue = null;
2540

    
2541
        private String xmlFieldValue = null; //return field value in xml
2542
                                             // format
2543
        private String fieldType = null; //ATTRIBUTE, TEXT...
2544

    
2545
        public void setDocid(String myDocid)
2546
        {
2547
            docid = myDocid;
2548
        }
2549

    
2550
        public String getDocid()
2551
        {
2552
            return docid;
2553
        }
2554

    
2555
        public void setFieldValue(String myValue)
2556
        {
2557
            fieldValue = myValue;
2558
        }
2559

    
2560
        public String getFieldValue()
2561
        {
2562
            return fieldValue;
2563
        }
2564

    
2565
        public void setXMLFieldValue(String xml)
2566
        {
2567
            xmlFieldValue = xml;
2568
        }
2569

    
2570
        public String getXMLFieldValue()
2571
        {
2572
            return xmlFieldValue;
2573
        }
2574
        
2575
        public void setFieldType(String myType)
2576
        {
2577
            fieldType = myType;
2578
        }
2579

    
2580
        public String getFieldType()
2581
        {
2582
            return fieldType;
2583
        }
2584

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