Project

General

Profile

1 155 jones
/**
2 203 jones
 *  '$RCSfile$'
3 2043 sgarg
 *    Purpose: A Class that searches a relational DB for elements and
4 203 jones
 *             attributes that have free text matches a query string,
5 2043 sgarg
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7 203 jones
 *             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 155 jones
 *
12 203 jones
 *   '$Author$'
13
 *     '$Date$'
14
 * '$Revision$'
15 669 jones
 *
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 155 jones
 */
30
31 607 bojilova
package edu.ucsb.nceas.metacat;
32 155 jones
33 5752 leinfelder
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 2074 jones
import java.sql.PreparedStatement;
46
import java.sql.ResultSet;
47
import java.sql.SQLException;
48 6602 leinfelder
import java.sql.Timestamp;
49
import java.util.ArrayList;
50
import java.util.Date;
51 5752 leinfelder
import java.util.Enumeration;
52
import java.util.Hashtable;
53
import java.util.Iterator;
54 6602 leinfelder
import java.util.List;
55 5752 leinfelder
import java.util.StringTokenizer;
56
import java.util.Vector;
57
import java.util.zip.ZipEntry;
58
import java.util.zip.ZipOutputStream;
59 2074 jones
60 940 tao
import javax.servlet.ServletOutputStream;
61 2087 tao
import javax.servlet.http.HttpServletResponse;
62 155 jones
63 2663 sgarg
import org.apache.log4j.Logger;
64 2087 tao
65 5090 daigle
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
66 5015 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
67
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
68 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
69 4589 daigle
import edu.ucsb.nceas.metacat.util.AuthUtil;
70 5025 daigle
import edu.ucsb.nceas.metacat.util.DocumentUtil;
71 4698 daigle
import edu.ucsb.nceas.metacat.util.MetacatUtil;
72 4080 daigle
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
73 2074 jones
74 7403 leinfelder
import edu.ucsb.nceas.utilities.triple.Triple;
75
import edu.ucsb.nceas.utilities.triple.TripleCollection;
76 2912 harris
77 7403 leinfelder
78 2043 sgarg
/**
79 2075 jones
 * A Class that searches a relational DB for elements and attributes that have
80
 * free text matches a query string, or structured query matches to a path
81
 * specified node in the XML hierarchy. It returns a result set consisting of
82
 * the document ID for each document that satisfies the query
83 155 jones
 */
84 2075 jones
public class DBQuery
85
{
86 155 jones
87 2075 jones
    static final int ALL = 1;
88 2043 sgarg
89 2075 jones
    static final int WRITE = 2;
90 2043 sgarg
91 2075 jones
    static final int READ = 4;
92 5490 berkley
93
    private String qformat = "xml";
94 6035 leinfelder
95
    // are we combining the query with docid list and, if so, using INTERSECT or UNION?
96
    private String operator = null;
97 155 jones
98 2075 jones
    //private Connection conn = null;
99
    private String parserName = null;
100 706 bojilova
101 2663 sgarg
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
102
103 2912 harris
    /** true if the metacat spatial option is installed **/
104
    private final boolean METACAT_SPATIAL = true;
105
106 3392 tao
    /** useful if you just want to grab a list of docids. Since the docids can be very long,
107
         it is a vector of vector  **/
108 3047 perry
    Vector docidOverride = new Vector();
109 3340 tao
110
    // a hash table serves as query reuslt cache. Key of hashtable
111 3342 tao
    // is a query string and value is result xml string
112 3340 tao
    private static Hashtable queryResultCache = new Hashtable();
113
114
    // Capacity of the query result cache
115 4080 daigle
    private static final int QUERYRESULTCACHESIZE;
116
    static {
117
    	int qryRsltCacheSize = 0;
118
    	try {
119 4212 daigle
    		qryRsltCacheSize = Integer.parseInt(PropertyService.getProperty("database.queryresultCacheSize"));
120 4080 daigle
    	} catch (PropertyNotFoundException pnfe) {
121
    		System.err.println("Could not get QUERYRESULTCACHESIZE property in static block: "
122
					+ pnfe.getMessage());
123
    	}
124
    	QUERYRESULTCACHESIZE = qryRsltCacheSize;
125
    }
126
127 3047 perry
128 3368 tao
    // Size of page for non paged query
129
    private static final int NONPAGESIZE = 99999999;
130 2075 jones
    /**
131
     * the main routine used to test the DBQuery utility.
132
     * <p>
133
     * Usage: java DBQuery <xmlfile>
134 5752 leinfelder
     * NOTE: encoding should be provided for best results
135 2075 jones
     * @param xmlfile the filename of the xml file containing the query
136
     */
137
    static public void main(String[] args)
138
    {
139 706 bojilova
140 2075 jones
        if (args.length < 1) {
141
            System.err.println("Wrong number of arguments!!!");
142
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
143
            return;
144
        } else {
145
            try {
146 706 bojilova
147 2075 jones
                int i = 0;
148
                boolean showRuntime = false;
149
                boolean useXMLIndex = false;
150
                if (args[i].equals("-t")) {
151
                    showRuntime = true;
152
                    i++;
153
                }
154
                if (args[i].equals("-index")) {
155
                    useXMLIndex = true;
156
                    i++;
157
                }
158
                String xmlfile = args[i];
159 706 bojilova
160 2075 jones
                // Time the request if asked for
161
                double startTime = System.currentTimeMillis();
162 2043 sgarg
163 2075 jones
                // Open a connection to the database
164
                //Connection dbconn = util.openDBConnection();
165 2043 sgarg
166 2075 jones
                double connTime = System.currentTimeMillis();
167 2043 sgarg
168 2075 jones
                // Execute the query
169 2752 jones
                DBQuery queryobj = new DBQuery();
170 5752 leinfelder
                Reader xml = new InputStreamReader(new FileInputStream(new File(xmlfile)));
171 2075 jones
                Hashtable nodelist = null;
172 2087 tao
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
173 2043 sgarg
174 2075 jones
                // Print the reulting document listing
175
                StringBuffer result = new StringBuffer();
176
                String document = null;
177
                String docid = null;
178
                result.append("<?xml version=\"1.0\"?>\n");
179
                result.append("<resultset>\n");
180 2043 sgarg
181 2075 jones
                if (!showRuntime) {
182
                    Enumeration doclist = nodelist.keys();
183
                    while (doclist.hasMoreElements()) {
184
                        docid = (String) doclist.nextElement();
185
                        document = (String) nodelist.get(docid);
186
                        result.append("  <document>\n    " + document
187
                                + "\n  </document>\n");
188
                    }
189 706 bojilova
190 2075 jones
                    result.append("</resultset>\n");
191
                }
192
                // Time the request if asked for
193
                double stopTime = System.currentTimeMillis();
194
                double dbOpenTime = (connTime - startTime) / 1000;
195
                double readTime = (stopTime - connTime) / 1000;
196
                double executionTime = (stopTime - startTime) / 1000;
197
                if (showRuntime) {
198
                    System.out.print("  " + executionTime);
199
                    System.out.print("  " + dbOpenTime);
200
                    System.out.print("  " + readTime);
201
                    System.out.print("  " + nodelist.size());
202
                    System.out.println();
203
                }
204
                //System.out.println(result);
205
                //write into a file "result.txt"
206
                if (!showRuntime) {
207
                    File f = new File("./result.txt");
208 5752 leinfelder
                    Writer fw = new OutputStreamWriter(new FileOutputStream(f));
209 2075 jones
                    BufferedWriter out = new BufferedWriter(fw);
210
                    out.write(result.toString());
211
                    out.flush();
212
                    out.close();
213
                    fw.close();
214
                }
215 2043 sgarg
216 2075 jones
            } catch (Exception e) {
217
                System.err.println("Error in DBQuery.main");
218
                System.err.println(e.getMessage());
219
                e.printStackTrace(System.err);
220
            }
221
        }
222
    }
223 2043 sgarg
224 2075 jones
    /**
225
     * construct an instance of the DBQuery class
226 2087 tao
     *
227 2075 jones
     * <p>
228
     * Generally, one would call the findDocuments() routine after creating an
229
     * instance to specify the search query
230
     * </p>
231 2087 tao
     *
232
233 2075 jones
     * @param parserName the fully qualified name of a Java class implementing
234
     *            the org.xml.sax.XMLReader interface
235
     */
236 4080 daigle
    public DBQuery() throws PropertyNotFoundException
237 2075 jones
    {
238 4213 daigle
        String parserName = PropertyService.getProperty("xml.saxparser");
239 2752 jones
        this.parserName = parserName;
240 2075 jones
    }
241 2043 sgarg
242 3047 perry
    /**
243
     *
244
     * Construct an instance of DBQuery Class
245
     * BUT accept a docid Vector that will supersede
246
     * the query.printSQL() method
247
     *
248
     * If a docid Vector is passed in,
249
     * the docids will be used to create a simple IN query
250
     * without the multiple subselects of the printSQL() method
251
     *
252
     * Using this constructor, we just check for
253
     * a docidOverride Vector in the findResultDoclist() method
254
     *
255
     * @param docids List of docids to display in the resultset
256
     */
257 4080 daigle
    public DBQuery(Vector docids) throws PropertyNotFoundException
258 3047 perry
    {
259 3392 tao
    	// since the query will be too long to be handled, so we divided the
260
    	// docids vector into couple vectors.
261 4212 daigle
    	int size = (new Integer(PropertyService.getProperty("database.appResultsetSize"))).intValue();
262 5165 daigle
    	logMetacat.info("DBQuery.DBQuery - The size of select doicds is "+docids.size());
263
    	logMetacat.info("DBQuery.DBQuery - The application result size in metacat.properties is "+size);
264 3392 tao
    	Vector subset = new Vector();
265
    	if (docids != null && docids.size() > size)
266
    	{
267
    		int index = 0;
268
    		for (int i=0; i< docids.size(); i++)
269
    		{
270
271
    			if (index < size)
272
    			{
273
    				subset.add(docids.elementAt(i));
274
    				index ++;
275
    			}
276
    			else
277
    			{
278
    				docidOverride.add(subset);
279
    				subset = new Vector();
280
    				subset.add(docids.elementAt(i));
281
    			    index = 1;
282
    			}
283
    		}
284
    		if (!subset.isEmpty())
285
    		{
286
    			docidOverride.add(subset);
287
    		}
288
289
    	}
290
    	else
291
    	{
292
    		this.docidOverride.add(docids);
293
    	}
294
295 4213 daigle
        String parserName = PropertyService.getProperty("xml.saxparser");
296 3047 perry
        this.parserName = parserName;
297
    }
298 2087 tao
299
  /**
300
   * Method put the search result set into out printerwriter
301
   * @param resoponse the return response
302
   * @param out the output printer
303
   * @param params the paratermer hashtable
304
   * @param user the user name (it maybe different to the one in param)
305
   * @param groups the group array
306
   * @param sessionid  the sessionid
307
   */
308
  public void findDocuments(HttpServletResponse response,
309 5752 leinfelder
                                       Writer out, Hashtable params,
310 2087 tao
                                       String user, String[] groups,
311 4080 daigle
                                       String sessionid) throws PropertyNotFoundException
312 2087 tao
  {
313 4173 daigle
    boolean useXMLIndex = (new Boolean(PropertyService.getProperty("database.usexmlindex")))
314 2087 tao
               .booleanValue();
315
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
316
317
  }
318
319
320 2075 jones
    /**
321 2087 tao
     * Method put the search result set into out printerwriter
322
     * @param resoponse the return response
323
     * @param out the output printer
324
     * @param params the paratermer hashtable
325
     * @param user the user name (it maybe different to the one in param)
326
     * @param groups the group array
327
     * @param sessionid  the sessionid
328 2075 jones
     */
329 2087 tao
    public void findDocuments(HttpServletResponse response,
330 5752 leinfelder
                                         Writer out, Hashtable params,
331 2087 tao
                                         String user, String[] groups,
332
                                         String sessionid, boolean useXMLIndex)
333 2075 jones
    {
334 3211 berkley
      int pagesize = 0;
335
      int pagestart = 0;
336 5165 daigle
      long transferWarnLimit = 0;
337 3211 berkley
338
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
339
      {
340
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
341
        String pagestartStr = ((String[])params.get("pagestart"))[0];
342
        if(pagesizeStr != null && pagestartStr != null)
343
        {
344
          pagesize = (new Integer(pagesizeStr)).intValue();
345
          pagestart = (new Integer(pagestartStr)).intValue();
346
        }
347
      }
348
349 3780 daigle
      String xmlquery = null;
350
      String qformat = null;
351 2087 tao
      // get query and qformat
352 3780 daigle
      try {
353
    	xmlquery = ((String[])params.get("query"))[0];
354 2168 tao
355 5165 daigle
        logMetacat.info("DBQuery.findDocuments - SESSIONID: " + sessionid);
356
        logMetacat.info("DBQuery.findDocuments - xmlquery: " + xmlquery);
357 3780 daigle
        qformat = ((String[])params.get("qformat"))[0];
358 5165 daigle
        logMetacat.info("DBQuery.findDocuments - qformat: " + qformat);
359 3780 daigle
      }
360
      catch (Exception ee)
361
      {
362 5165 daigle
        logMetacat.error("DBQuery.findDocuments - Couldn't retrieve xmlquery or qformat value from "
363 3780 daigle
                  +"params hashtable in DBQuery.findDocuments: "
364
                  + ee.getMessage());
365
      }
366 2168 tao
      // Get the XML query and covert it into a SQL statment
367
      QuerySpecification qspec = null;
368
      if ( xmlquery != null)
369
      {
370
         xmlquery = transformQuery(xmlquery);
371
         try
372
         {
373
           qspec = new QuerySpecification(xmlquery,
374
                                          parserName,
375 4212 daigle
                                          PropertyService.getProperty("document.accNumSeparator"));
376 2168 tao
         }
377
         catch (Exception ee)
378
         {
379 5165 daigle
           logMetacat.error("DBQuery.findDocuments - error generating QuerySpecification object: "
380 2663 sgarg
                                    + ee.getMessage());
381 2168 tao
         }
382
      }
383 2087 tao
384 2168 tao
385
386 5025 daigle
      if (qformat != null && qformat.equals(MetacatUtil.XMLFORMAT))
387 2087 tao
      {
388
        //xml format
389 5491 berkley
        if(response != null)
390
        {
391
            response.setContentType("text/xml");
392
        }
393 5490 berkley
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex,
394
          pagesize, pagestart, sessionid, qformat);
395 2087 tao
      }//if
396
      else
397
      {
398
        //knb format, in this case we will get whole result and sent it out
399 3257 berkley
        response.setContentType("text/html");
400 5752 leinfelder
        Writer nonout = null;
401 2168 tao
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
402 3211 berkley
                                                groups, useXMLIndex, pagesize,
403 5490 berkley
                                                pagestart, sessionid, qformat);
404 2658 sgarg
405 2087 tao
        //transfer the xml to html
406
        try
407
        {
408 5165 daigle
         long startHTMLTransform = System.currentTimeMillis();
409 2087 tao
         DBTransform trans = new DBTransform();
410
         response.setContentType("text/html");
411 2787 sgarg
412 3219 berkley
         // if the user is a moderator, then pass a param to the
413 2787 sgarg
         // xsl specifying the fact
414 4589 daigle
         if(AuthUtil.isModerator(user, groups)){
415 2787 sgarg
        	 params.put("isModerator", new String[] {"true"});
416
         }
417
418 2087 tao
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
419
                                 "-//W3C//HTML//EN", qformat, out, params,
420
                                 sessionid);
421 5165 daigle
         long transformRunTime = System.currentTimeMillis() - startHTMLTransform;
422
423
         transferWarnLimit = Long.parseLong(PropertyService.getProperty("dbquery.transformTimeWarnLimit"));
424
425
         if (transformRunTime > transferWarnLimit) {
426
         	logMetacat.warn("DBQuery.findDocuments - The time to transfrom resultset from xml to html format is "
427
                  		                             + transformRunTime);
428
         }
429 4698 daigle
          MetacatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Transfrom xml to html  "
430 5165 daigle
                             + transformRunTime);
431
          MetacatUtil.writeDebugToDelimiteredFile(" " + transformRunTime, false);
432 2087 tao
        }
433
        catch(Exception e)
434
        {
435 5165 daigle
         logMetacat.error("DBQuery.findDocuments - Error in MetaCatServlet.transformResultset:"
436 2663 sgarg
                                +e.getMessage());
437 2087 tao
         }
438
439
      }//else
440
441 3219 berkley
  }
442 5490 berkley
443
444 3220 tao
445
  /**
446
   * Transforms a hashtable of documents to an xml or html result and sent
447
   * the content to outputstream. Keep going untill hastable is empty. stop it.
448
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
449
   * to xmlquery String
450
   * @param xmlquery
451
   * @param qspec
452
   * @param out
453
   * @param user
454
   * @param groups
455
   * @param useXMLIndex
456
   * @param sessionid
457
   * @return
458
   */
459
    public StringBuffer createResultDocument(String xmlquery,
460
                                              QuerySpecification qspec,
461 5752 leinfelder
                                              Writer out,
462 3220 tao
                                              String user, String[] groups,
463
                                              boolean useXMLIndex)
464
    {
465 5490 berkley
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"", qformat);
466 3220 tao
    }
467 2043 sgarg
468 2087 tao
  /*
469
   * Transforms a hashtable of documents to an xml or html result and sent
470 2168 tao
   * the content to outputstream. Keep going untill hastable is empty. stop it.
471
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
472
   * to xmlquery String
473 2087 tao
   */
474 2168 tao
  public StringBuffer createResultDocument(String xmlquery,
475
                                            QuerySpecification qspec,
476 5752 leinfelder
                                            Writer out,
477 2087 tao
                                            String user, String[] groups,
478 3211 berkley
                                            boolean useXMLIndex, int pagesize,
479 5490 berkley
                                            int pagestart, String sessionid,
480
                                            String qformat)
481 2087 tao
  {
482
    DBConnection dbconn = null;
483
    int serialNumber = -1;
484
    StringBuffer resultset = new StringBuffer();
485 3219 berkley
486
    //try to get the cached version first
487 4080 daigle
    // Hashtable sessionHash = MetaCatServlet.getSessionHash();
488
    // HttpSession sess = (HttpSession)sessionHash.get(sessionid);
489 3219 berkley
490 3220 tao
491 2087 tao
    resultset.append("<?xml version=\"1.0\"?>\n");
492
    resultset.append("<resultset>\n");
493 3257 berkley
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
494
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
495
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
496
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
497
498 2087 tao
    resultset.append("  <query>" + xmlquery + "</query>");
499 3219 berkley
    //send out a new query
500 2087 tao
    if (out != null)
501 2075 jones
    {
502 5752 leinfelder
    	try {
503
    	  out.write(resultset.toString());
504
		} catch (IOException e) {
505
			logMetacat.error(e.getMessage(), e);
506
		}
507 2075 jones
    }
508 2168 tao
    if (qspec != null)
509 2087 tao
    {
510 2168 tao
      try
511
      {
512 2043 sgarg
513 2168 tao
        //checkout the dbconnection
514
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
515
        serialNumber = dbconn.getCheckOutSerialNumber();
516 2087 tao
517 2168 tao
        //print out the search result
518
        // search the doc list
519 3392 tao
        Vector givenDocids = new Vector();
520
        StringBuffer resultContent = new StringBuffer();
521
        if (docidOverride == null || docidOverride.size() == 0)
522
        {
523 5165 daigle
        	logMetacat.debug("DBQuery.createResultDocument - Not in map query");
524 3392 tao
        	resultContent = findResultDoclist(qspec, out, user, groups,
525
                    dbconn, useXMLIndex, pagesize, pagestart,
526 5490 berkley
                    sessionid, givenDocids, qformat);
527 3392 tao
        }
528
        else
529
        {
530 5165 daigle
        	logMetacat.debug("DBQuery.createResultDocument - In map query");
531 3392 tao
        	// since docid can be too long to be handled. We divide it into several parts
532
        	for (int i= 0; i<docidOverride.size(); i++)
533
        	{
534 5165 daigle
        	   logMetacat.debug("DBQuery.createResultDocument - in loop===== "+i);
535 3392 tao
        		givenDocids = (Vector)docidOverride.elementAt(i);
536
        		StringBuffer subset = findResultDoclist(qspec, out, user, groups,
537
                        dbconn, useXMLIndex, pagesize, pagestart,
538 5490 berkley
                        sessionid, givenDocids, qformat);
539 3392 tao
        		resultContent.append(subset);
540
        	}
541
        }
542
543 3342 tao
        resultset.append(resultContent);
544 2168 tao
      } //try
545
      catch (IOException ioe)
546
      {
547 5165 daigle
        logMetacat.error("DBQuery.createResultDocument - IO error: " + ioe.getMessage());
548 2168 tao
      }
549
      catch (SQLException e)
550
      {
551 5165 daigle
        logMetacat.error("DBQuery.createResultDocument - SQL Error: " + e.getMessage());
552 2168 tao
      }
553
      catch (Exception ee)
554
      {
555 5165 daigle
        logMetacat.error("DBQuery.createResultDocument - General exception: "
556 2663 sgarg
                                 + ee.getMessage());
557 3219 berkley
        ee.printStackTrace();
558 2168 tao
      }
559
      finally
560
      {
561
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
562
      } //finally
563
    }//if
564 2087 tao
    String closeRestultset = "</resultset>";
565
    resultset.append(closeRestultset);
566
    if (out != null)
567
    {
568 5752 leinfelder
      try {
569
		out.write(closeRestultset);
570
		} catch (IOException e) {
571
			logMetacat.error(e.getMessage(), e);
572
		}
573 2087 tao
    }
574 2168 tao
575 3221 berkley
    //default to returning the whole resultset
576 2087 tao
    return resultset;
577
  }//createResultDocuments
578 2043 sgarg
579 2087 tao
    /*
580
     * Find the doc list which match the query
581
     */
582
    private StringBuffer findResultDoclist(QuerySpecification qspec,
583 5752 leinfelder
                                      Writer out,
584 2087 tao
                                      String user, String[]groups,
585 3211 berkley
                                      DBConnection dbconn, boolean useXMLIndex,
586 5490 berkley
                                      int pagesize, int pagestart, String sessionid,
587
                                      Vector givenDocids, String qformat)
588 2087 tao
                                      throws Exception
589
    {
590 6602 leinfelder
    	// keep track of the values we add as prepared statement question marks (?)
591
  	  List<Object> parameterValues = new ArrayList<Object>();
592
593 3342 tao
      StringBuffer resultsetBuffer = new StringBuffer();
594 3219 berkley
      String query = null;
595
      int count = 0;
596
      int index = 0;
597 3246 berkley
      ResultDocumentSet docListResult = new ResultDocumentSet();
598 3219 berkley
      PreparedStatement pstmt = null;
599
      String docid = null;
600
      String docname = null;
601
      String doctype = null;
602
      String createDate = null;
603
      String updateDate = null;
604
      StringBuffer document = null;
605 3262 berkley
      boolean lastpage = false;
606 3219 berkley
      int rev = 0;
607
      double startTime = 0;
608 3368 tao
      int offset = 1;
609 5165 daigle
      long startSelectionTime = System.currentTimeMillis();
610 3219 berkley
      ResultSet rs = null;
611 3368 tao
612
613
      // this is a hack for offset. in postgresql 7, if the returned docid list is too long,
614
      //the extend query which base on the docid will be too long to be run. So we
615
      // have to cut them into different parts. Page query don't need it somehow.
616
      if (out == null)
617 2091 tao
      {
618
        // for html page, we put everything into one page
619 2421 sgarg
        offset =
620 4212 daigle
            (new Integer(PropertyService.getProperty("database.webResultsetSize"))).intValue();
621 2091 tao
      }
622
      else
623
      {
624
          offset =
625 4212 daigle
              (new Integer(PropertyService.getProperty("database.appResultsetSize"))).intValue();
626 3368 tao
      }
627 2421 sgarg
628 3047 perry
      /*
629
       * Check the docidOverride Vector
630
       * if defined, we bypass the qspec.printSQL() method
631
       * and contruct a simpler query based on a
632
       * list of docids rather than a bunch of subselects
633
       */
634 6602 leinfelder
      // keep track of the values we add as prepared statement question marks (?)
635
	  List<Object> docidValues = new ArrayList<Object>();
636 3392 tao
      if ( givenDocids == null || givenDocids.size() == 0 ) {
637 6602 leinfelder
          query = qspec.printSQL(useXMLIndex, docidValues);
638
          parameterValues.addAll(docidValues);
639 3047 perry
      } else {
640 6035 leinfelder
    	  // condition for the docids
641 6629 leinfelder
    	  List<Object> docidConditionValues = new ArrayList<Object>();
642 6035 leinfelder
    	  StringBuffer docidCondition = new StringBuffer();
643
    	  docidCondition.append( " docid IN (" );
644 3392 tao
          for (int i = 0; i < givenDocids.size(); i++) {
645 6629 leinfelder
        	  docidCondition.append("?");
646 6035 leinfelder
        	  if (i < givenDocids.size()-1) {
647
        		  docidCondition.append(",");
648
        	  }
649 6629 leinfelder
        	  docidConditionValues.add((String)givenDocids.elementAt(i));
650 3047 perry
          }
651 6035 leinfelder
          docidCondition.append( ") " );
652
653
    	  // include the docids, either exclusively, or in conjuction with the query
654
    	  if (operator == null) {
655
    		  query = "SELECT docid, docname, doctype, date_created, date_updated, rev FROM xml_documents WHERE";
656
              query = query + docidCondition.toString();
657 6629 leinfelder
              parameterValues.addAll(docidConditionValues);
658 6035 leinfelder
    	  } else {
659
    		  // start with the keyword query, but add conditions
660 6602 leinfelder
              query = qspec.printSQL(useXMLIndex, docidValues);
661
              parameterValues.addAll(docidValues);
662 6035 leinfelder
              String myOperator = "";
663
              if (!query.endsWith("WHERE")) {
664
	              if (operator.equalsIgnoreCase(QueryGroup.UNION)) {
665
	            	  myOperator =  " OR ";
666
	              }
667
	              else {
668
	            	  myOperator =  " AND ";
669
	              }
670
              }
671
              query = query + myOperator + docidCondition.toString();
672 6629 leinfelder
              parameterValues.addAll(docidConditionValues);
673 6035 leinfelder
674
    	  }
675 3047 perry
      }
676 6629 leinfelder
      // we don't actually use this query for anything
677
      List<Object> ownerValues = new ArrayList<Object>();
678
      String ownerQuery = getOwnerQuery(user, ownerValues);
679 4574 daigle
      //logMetacat.debug("query: " + query);
680 5165 daigle
      logMetacat.debug("DBQuery.findResultDoclist - owner query: " + ownerQuery);
681 2087 tao
      // if query is not the owner query, we need to check the permission
682
      // otherwise we don't need (owner has all permission by default)
683
      if (!query.equals(ownerQuery))
684
      {
685
        // set user name and group
686
        qspec.setUserName(user);
687
        qspec.setGroup(groups);
688
        // Get access query
689
        String accessQuery = qspec.getAccessQuery();
690 2366 sgarg
        if(!query.endsWith("WHERE")){
691
            query = query + accessQuery;
692
        } else {
693
            query = query + accessQuery.substring(4, accessQuery.length());
694
        }
695 3309 tao
696 2087 tao
      }
697 5165 daigle
      logMetacat.debug("DBQuery.findResultDoclist - final selection query: " + query);
698 6774 tao
699
700
      pstmt = dbconn.prepareStatement(query);
701
      // set all the values we have collected
702
      pstmt = setPreparedStatementValues(parameterValues, pstmt);
703
704
      String queryCacheKey = null;
705 3342 tao
      // we only get cache for public
706
      if (user != null && user.equalsIgnoreCase("public")
707 6774 tao
         && pagesize == 0 && PropertyService.getProperty("database.queryCacheOn").equals("true"))
708 3342 tao
      {
709 6774 tao
          queryCacheKey = pstmt.toString() +qspec.getReturnDocList()+qspec.getReturnFieldList();
710
          String cachedResult = getResultXMLFromCache(queryCacheKey);
711
          logMetacat.debug("=======DBQuery.findResultDoclist - The key of query cache is " + queryCacheKey);
712
          //System.out.println("==========the string from cache is "+cachedResult);
713
          if (cachedResult != null)
714
          {
715
          logMetacat.info("DBQuery.findResultDoclist - result from cache !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
716
           if (out != null)
717
             {
718
                 out.write(cachedResult);
719
             }
720
           resultsetBuffer.append(cachedResult);
721
           pstmt.close();
722
           return resultsetBuffer;
723
          }
724 3342 tao
      }
725
726 3219 berkley
      startTime = System.currentTimeMillis() / 1000;
727 6602 leinfelder
      logMetacat.debug("Prepared statement after setting parameter values: " + pstmt.toString());
728 3219 berkley
      rs = pstmt.executeQuery();
729 3246 berkley
730 2087 tao
      double queryExecuteTime = System.currentTimeMillis() / 1000;
731 5165 daigle
      logMetacat.debug("DBQuery.findResultDoclist - Time to execute select docid query is "
732 2663 sgarg
                    + (queryExecuteTime - startTime));
733 4698 daigle
      MetacatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
734 3271 tao
              + (queryExecuteTime - startTime));
735 4698 daigle
      MetacatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
736 3246 berkley
737 3247 berkley
      boolean tableHasRows = rs.next();
738 3246 berkley
739
      if(pagesize == 0)
740
      { //this makes sure we get all results if there is no paging
741 3368 tao
        pagesize = NONPAGESIZE;
742
        pagestart = NONPAGESIZE;
743 3246 berkley
      }
744
745
      int currentIndex = 0;
746 2087 tao
      while (tableHasRows)
747
      {
748 5165 daigle
        logMetacat.debug("DBQuery.findResultDoclist - getting result: " + currentIndex);
749 2087 tao
        docid = rs.getString(1).trim();
750 5165 daigle
        logMetacat.debug("DBQuery.findResultDoclist -  processing: " + docid);
751 2087 tao
        docname = rs.getString(2);
752
        doctype = rs.getString(3);
753 5165 daigle
        logMetacat.debug("DBQuery.findResultDoclist - processing: " + doctype);
754 2087 tao
        createDate = rs.getString(4);
755
        updateDate = rs.getString(5);
756
        rev = rs.getInt(6);
757 3246 berkley
758 3307 tao
         Vector returndocVec = qspec.getReturnDocList();
759
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
760 2087 tao
        {
761 5165 daigle
          logMetacat.debug("DBQuery.findResultDoclist - NOT Back tracing now...");
762 2087 tao
           document = new StringBuffer();
763 2043 sgarg
764 2087 tao
           String completeDocid = docid
765 4212 daigle
                            + PropertyService.getProperty("document.accNumSeparator");
766 2087 tao
           completeDocid += rev;
767
           document.append("<docid>").append(completeDocid).append("</docid>");
768
           if (docname != null)
769
           {
770
               document.append("<docname>" + docname + "</docname>");
771 3219 berkley
           }
772
           if (doctype != null)
773
           {
774
              document.append("<doctype>" + doctype + "</doctype>");
775
           }
776
           if (createDate != null)
777
           {
778
               document.append("<createdate>" + createDate + "</createdate>");
779
           }
780
           if (updateDate != null)
781
           {
782
             document.append("<updatedate>" + updateDate + "</updatedate>");
783
           }
784
           // Store the document id and the root node id
785 3246 berkley
786
           docListResult.addResultDocument(
787
             new ResultDocument(docid, (String) document.toString()));
788 5165 daigle
           logMetacat.info("DBQuery.findResultDoclist - real result: " + docid);
789 3246 berkley
           currentIndex++;
790 3219 berkley
           count++;
791 2087 tao
        }//else
792 3246 berkley
793 2087 tao
        // when doclist reached the offset number, send out doc list and empty
794
        // the hash table
795 3368 tao
        if (count == offset && pagesize == NONPAGESIZE)
796 3246 berkley
        { //if pagesize is not 0, do this later.
797 2087 tao
          //reset count
798 3262 berkley
          //logMetacat.warn("############doing subset cache");
799 2087 tao
          count = 0;
800 3246 berkley
          handleSubsetResult(qspec, resultsetBuffer, out, docListResult,
801 5490 berkley
                              user, groups,dbconn, useXMLIndex, qformat);
802 3246 berkley
          //reset docListResult
803
          docListResult = new ResultDocumentSet();
804 3368 tao
        }
805 3246 berkley
806 5165 daigle
       logMetacat.debug("DBQuery.findResultDoclist - currentIndex: " + currentIndex);
807
       logMetacat.debug("DBQuery.findResultDoclist - page comparator: " + (pagesize * pagestart) + pagesize);
808 3246 berkley
       if(currentIndex >= ((pagesize * pagestart) + pagesize))
809
       {
810
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
811
         for(int i=pagesize*pagestart; i<docListResult.size(); i++)
812
         {
813
           pagedResultsHash.put(docListResult.get(i));
814
         }
815
816
         docListResult = pagedResultsHash;
817
         break;
818
       }
819 2087 tao
       // Advance to the next record in the cursor
820
       tableHasRows = rs.next();
821 3246 berkley
       if(!tableHasRows)
822
       {
823 3262 berkley
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
824
         //get the last page of information then break
825 3368 tao
         if(pagesize != NONPAGESIZE)
826 3262 berkley
         {
827
           for(int i=pagesize*pagestart; i<docListResult.size(); i++)
828
           {
829
             pagedResultsHash.put(docListResult.get(i));
830
           }
831
           docListResult = pagedResultsHash;
832
         }
833
834
         lastpage = true;
835 3246 berkley
         break;
836
       }
837 2087 tao
     }//while
838 3246 berkley
839 2087 tao
     rs.close();
840
     pstmt.close();
841 5165 daigle
     long docListTime = System.currentTimeMillis() - startSelectionTime;
842
     long docListWarnLimit = Long.parseLong(PropertyService.getProperty("dbquery.findDocListTimeWarnLimit"));
843
     if (docListTime > docListWarnLimit) {
844
    	 logMetacat.warn("DBQuery.findResultDoclist - Total time to get docid list is: "
845
                          + docListTime);
846
     }
847 4698 daigle
     MetacatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Total selection: "
848 5165 daigle
             + docListTime);
849
     MetacatUtil.writeDebugToDelimiteredFile(" "+ docListTime, false);
850 2087 tao
     //if docListResult is not empty, it need to be sent.
851 3246 berkley
     if (docListResult.size() != 0)
852 2087 tao
     {
853 3342 tao
854 2087 tao
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
855 5490 berkley
                              user, groups,dbconn, useXMLIndex, qformat);
856 2087 tao
     }
857 2091 tao
858 3262 berkley
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
859
     if (out != null)
860
     {
861 5752 leinfelder
         out.write("\n<lastpage>" + lastpage + "</lastpage>\n");
862 3262 berkley
     }
863 3342 tao
864
     // now we only cached none-paged query and user is public
865
     if (user != null && user.equalsIgnoreCase("public")
866 4212 daigle
    		 && pagesize == NONPAGESIZE && PropertyService.getProperty("database.queryCacheOn").equals("true"))
867 3342 tao
     {
868
       //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
869 6774 tao
  	   storeQueryResultIntoCache(queryCacheKey, resultsetBuffer.toString());
870 3342 tao
     }
871 3262 berkley
872 2087 tao
     return resultsetBuffer;
873
    }//findReturnDoclist
874 2043 sgarg
875
876 2087 tao
    /*
877
     * Send completed search hashtable(part of reulst)to output stream
878
     * and buffer into a buffer stream
879
     */
880
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
881
                                           StringBuffer resultset,
882 5752 leinfelder
                                           Writer out, ResultDocumentSet partOfDoclist,
883 2087 tao
                                           String user, String[]groups,
884 5490 berkley
                                       DBConnection dbconn, boolean useXMLIndex,
885
                                       String qformat)
886 2087 tao
                                       throws Exception
887
   {
888 5165 daigle
     double startReturnFieldTime = System.currentTimeMillis();
889 2424 sgarg
     // check if there is a record in xml_returnfield
890
     // and get the returnfield_id and usage count
891
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
892
     boolean enterRecords = false;
893
894 4212 daigle
     // get value of database.xmlReturnfieldCount
895 4080 daigle
     int count = (new Integer(PropertyService
896 4212 daigle
                            .getProperty("database.xmlReturnfieldCount")))
897 2424 sgarg
                            .intValue();
898 2430 sgarg
899 2446 sgarg
     // set enterRecords to true if usage_count is more than the offset
900 2430 sgarg
     // specified in metacat.properties
901 2424 sgarg
     if(usage_count > count){
902
         enterRecords = true;
903
     }
904 3257 berkley
905 2421 sgarg
     if(returnfield_id < 0){
906 5165 daigle
         logMetacat.warn("DBQuery.handleSubsetResult - Error in getting returnfield id from"
907 2663 sgarg
                                  + "xml_returnfield table");
908 3227 berkley
         enterRecords = false;
909 2421 sgarg
     }
910
911
     // get the hashtable containing the docids that already in the
912
     // xml_queryresult table
913 5165 daigle
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist before"
914 2421 sgarg
                             + " docidsInQueryresultTable(): "
915 2663 sgarg
                             + partOfDoclist.size());
916 5165 daigle
     long startGetReturnValueFromQueryresultable = System.currentTimeMillis();
917 2421 sgarg
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
918
                                                        partOfDoclist, dbconn);
919
920
     // remove the keys in queryresultDocList from partOfDoclist
921
     Enumeration _keys = queryresultDocList.keys();
922
     while (_keys.hasMoreElements()){
923 3246 berkley
         partOfDoclist.remove((String)_keys.nextElement());
924 2421 sgarg
     }
925 5165 daigle
926
     long queryResultReturnValuetime = System.currentTimeMillis() - startGetReturnValueFromQueryresultable;
927
     long queryResultWarnLimit =
928
    	 Long.parseLong(PropertyService.getProperty("dbquery.findQueryResultsTimeWarnLimit"));
929
930
     if (queryResultReturnValuetime > queryResultWarnLimit) {
931
    	 logMetacat.warn("DBQuery.handleSubsetResult - Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
932
    		 queryResultReturnValuetime);
933
     }
934 4698 daigle
     MetacatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
935 5165 daigle
    		 queryResultReturnValuetime);
936
     MetacatUtil.writeDebugToDelimiteredFile(" " + queryResultReturnValuetime,false);
937
938
     long startExtendedQuery = System.currentTimeMillis();
939 2425 sgarg
     // backup the keys-elements in partOfDoclist to check later
940
     // if the doc entry is indexed yet
941
     Hashtable partOfDoclistBackup = new Hashtable();
942 3246 berkley
     Iterator itt = partOfDoclist.getDocids();
943
     while (itt.hasNext()){
944
       Object key = itt.next();
945 2425 sgarg
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
946
     }
947
948 5165 daigle
     logMetacat.info("DBQuery.handleSubsetResult - size of partOfDoclist after"
949 2421 sgarg
                             + " docidsInQueryresultTable(): "
950 2663 sgarg
                             + partOfDoclist.size());
951 2421 sgarg
952
     //add return fields for the documents in partOfDoclist
953
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
954 5490 berkley
                                        dbconn, useXMLIndex, qformat);
955 5165 daigle
     long extendedQueryRunTime = startExtendedQuery - System.currentTimeMillis();
956
     long extendedQueryWarnLimit =
957
    	 Long.parseLong(PropertyService.getProperty("dbquery.extendedQueryRunTimeWarnLimit"));
958
959
     if (extendedQueryRunTime > extendedQueryWarnLimit) {
960
    	 logMetacat.warn("DBQuery.handleSubsetResult - Get fields from index and node table (Part2 in return fields) "
961
        		                                          + extendedQueryRunTime);
962
     }
963 4698 daigle
     MetacatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
964 5165 daigle
             + extendedQueryRunTime);
965 4698 daigle
     MetacatUtil.writeDebugToDelimiteredFile(" "
966 5165 daigle
             + extendedQueryRunTime, false);
967 2421 sgarg
     //add relationship part part docid list for the documents in partOfDocList
968 3730 tao
     //partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
969 2421 sgarg
970 5165 daigle
     long startStoreReturnField = System.currentTimeMillis();
971 3246 berkley
     Iterator keys = partOfDoclist.getDocids();
972 2087 tao
     String key = null;
973
     String element = null;
974 2421 sgarg
     String query = null;
975 4080 daigle
     int offset = (new Integer(PropertyService
976 4212 daigle
                               .getProperty("database.queryresultStringLength")))
977 2421 sgarg
                               .intValue();
978 3246 berkley
     while (keys.hasNext())
979 2087 tao
     {
980 3246 berkley
         key = (String) keys.next();
981 2421 sgarg
         element = (String)partOfDoclist.get(key);
982 3350 tao
983 2446 sgarg
	 // check if the enterRecords is true, elements is not null, element's
984
         // length is less than the limit of table column and if the document
985 2425 sgarg
         // has been indexed already
986 2446 sgarg
         if(enterRecords && element != null
987 2425 sgarg
		&& element.length() < offset
988
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
989 2421 sgarg
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
990 2446 sgarg
                 + "queryresult_string) VALUES (?, ?, ?)";
991
992 2421 sgarg
             PreparedStatement pstmt = null;
993
             pstmt = dbconn.prepareStatement(query);
994 2446 sgarg
             pstmt.setInt(1, returnfield_id);
995
             pstmt.setString(2, key);
996
             pstmt.setString(3, element);
997 3350 tao
998 2421 sgarg
             dbconn.increaseUsageCount(1);
999 3350 tao
             try
1000
             {
1001
            	 pstmt.execute();
1002
             }
1003
             catch(Exception e)
1004
             {
1005 5165 daigle
            	 logMetacat.warn("DBQuery.handleSubsetResult - couldn't insert the element to xml_queryresult table "+e.getLocalizedMessage());
1006 3350 tao
             }
1007
             finally
1008
             {
1009
                pstmt.close();
1010
             }
1011 2421 sgarg
         }
1012 3263 tao
1013 2421 sgarg
         // A string with element
1014
         String xmlElement = "  <document>" + element + "</document>";
1015 3257 berkley
1016 2421 sgarg
         //send single element to output
1017
         if (out != null)
1018
         {
1019 5752 leinfelder
             out.write(xmlElement);
1020 2421 sgarg
         }
1021
         resultset.append(xmlElement);
1022
     }//while
1023 3263 tao
1024 5165 daigle
     double storeReturnFieldTime = System.currentTimeMillis() - startStoreReturnField;
1025
     long storeReturnFieldWarnLimit =
1026
    	 Long.parseLong(PropertyService.getProperty("dbquery.storeReturnFieldTimeWarnLimit"));
1027
1028
     if (storeReturnFieldTime > storeReturnFieldWarnLimit) {
1029
    	 logMetacat.warn("DBQuery.handleSubsetResult - Time to store new return fields into xml_queryresult table (Part4 in return fields) "
1030
                   + storeReturnFieldTime);
1031
     }
1032 4698 daigle
     MetacatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
1033 5165 daigle
             + storeReturnFieldTime);
1034
     MetacatUtil.writeDebugToDelimiteredFile(" " + storeReturnFieldTime, false);
1035 3263 tao
1036 3246 berkley
     Enumeration keysE = queryresultDocList.keys();
1037
     while (keysE.hasMoreElements())
1038 2421 sgarg
     {
1039 3246 berkley
         key = (String) keysE.nextElement();
1040 2421 sgarg
         element = (String)queryresultDocList.get(key);
1041
         // A string with element
1042
         String xmlElement = "  <document>" + element + "</document>";
1043
         //send single element to output
1044
         if (out != null)
1045
         {
1046 5752 leinfelder
             out.write(xmlElement);
1047 2421 sgarg
         }
1048
         resultset.append(xmlElement);
1049
     }//while
1050 5165 daigle
     double returnFieldTime = System.currentTimeMillis() - startReturnFieldTime;
1051
     long totalReturnFieldWarnLimit =
1052
    	 Long.parseLong(PropertyService.getProperty("dbquery.totalReturnFieldTimeWarnLimit"));
1053
1054
     if (returnFieldTime > totalReturnFieldWarnLimit) {
1055
    	 logMetacat.warn("DBQuery.handleSubsetResult - Total time to get return fields is: "
1056
                           + returnFieldTime);
1057
     }
1058
     MetacatUtil.writeDebugToFile("DBQuery.handleSubsetResult - ---------------------------------------------------------------------------------------------------------------"+
1059
    		 "Total to get return fields  " + returnFieldTime);
1060
     MetacatUtil.writeDebugToDelimiteredFile("DBQuery.handleSubsetResult - "+ returnFieldTime, false);
1061 2421 sgarg
     return resultset;
1062
 }
1063
1064
   /**
1065
    * Get the docids already in xml_queryresult table and corresponding
1066
    * queryresultstring as a hashtable
1067
    */
1068
   private Hashtable docidsInQueryresultTable(int returnfield_id,
1069 3246 berkley
                                              ResultDocumentSet partOfDoclist,
1070 2421 sgarg
                                              DBConnection dbconn){
1071
1072
         Hashtable returnValue = new Hashtable();
1073
         PreparedStatement pstmt = null;
1074
         ResultSet rs = null;
1075 6629 leinfelder
1076
         // keep track of parameter values
1077
         List<Object> parameterValues = new ArrayList<Object>();
1078 2421 sgarg
1079
         // get partOfDoclist as string for the query
1080 3246 berkley
         Iterator keylist = partOfDoclist.getDocids();
1081 2421 sgarg
         StringBuffer doclist = new StringBuffer();
1082 3246 berkley
         while (keylist.hasNext())
1083 2421 sgarg
         {
1084 6629 leinfelder
             doclist.append("?,");
1085
             parameterValues.add((String) keylist.next());
1086 2421 sgarg
         }//while
1087
1088
         if (doclist.length() > 0)
1089
         {
1090
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1091
1092
             // the query to find out docids from xml_queryresult
1093
             String query = "select docid, queryresult_string from "
1094
                          + "xml_queryresult where returnfield_id = " +
1095
                          returnfield_id +" and docid in ("+ doclist + ")";
1096 5165 daigle
             logMetacat.info("DBQuery.docidsInQueryresultTable - Query to get docids from xml_queryresult:"
1097 2663 sgarg
                                      + query);
1098 2421 sgarg
1099
             try {
1100
                 // prepare and execute the query
1101
                 pstmt = dbconn.prepareStatement(query);
1102 6629 leinfelder
                 // bind parameter values
1103
                 pstmt = setPreparedStatementValues(parameterValues, pstmt);
1104
1105 2421 sgarg
                 dbconn.increaseUsageCount(1);
1106
                 pstmt.execute();
1107
                 rs = pstmt.getResultSet();
1108
                 boolean tableHasRows = rs.next();
1109
                 while (tableHasRows) {
1110
                     // store the returned results in the returnValue hashtable
1111
                     String key = rs.getString(1);
1112
                     String element = rs.getString(2);
1113
1114
                     if(element != null){
1115
                         returnValue.put(key, element);
1116
                     } else {
1117 5165 daigle
                         logMetacat.info("DBQuery.docidsInQueryresultTable - Null elment found ("
1118 2663 sgarg
                         + "DBQuery.docidsInQueryresultTable)");
1119 2421 sgarg
                     }
1120
                     tableHasRows = rs.next();
1121
                 }
1122
                 rs.close();
1123
                 pstmt.close();
1124
             } catch (Exception e){
1125 5165 daigle
                 logMetacat.error("DBQuery.docidsInQueryresultTable - Error getting docids from "
1126
                                          + "queryresult: " + e.getMessage());
1127 2421 sgarg
              }
1128
         }
1129
         return returnValue;
1130
     }
1131
1132
1133
   /**
1134
    * Method to get id from xml_returnfield table
1135
    * for a given query specification
1136
    */
1137 2424 sgarg
   private int returnfield_id;
1138 2421 sgarg
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1139
                                           DBConnection dbconn){
1140
       int id = -1;
1141 2424 sgarg
       int count = 1;
1142 2421 sgarg
       PreparedStatement pstmt = null;
1143
       ResultSet rs = null;
1144
       String returnfield = qspec.getSortedReturnFieldString();
1145
1146
       // query for finding the id from xml_returnfield
1147 2446 sgarg
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1148
            + "WHERE returnfield_string LIKE ?";
1149 5165 daigle
       logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Query:" + query);
1150 2421 sgarg
1151
       try {
1152
           // prepare and run the query
1153
           pstmt = dbconn.prepareStatement(query);
1154 2446 sgarg
           pstmt.setString(1,returnfield);
1155 2421 sgarg
           dbconn.increaseUsageCount(1);
1156
           pstmt.execute();
1157
           rs = pstmt.getResultSet();
1158
           boolean tableHasRows = rs.next();
1159
1160
           // if record found then increase the usage count
1161
           // else insert a new record and get the id of the new record
1162
           if(tableHasRows){
1163
               // get the id
1164
               id = rs.getInt(1);
1165 2424 sgarg
               count = rs.getInt(2) + 1;
1166 2421 sgarg
               rs.close();
1167
               pstmt.close();
1168
1169
               // increase the usage count
1170 6629 leinfelder
               query = "UPDATE xml_returnfield SET usage_count = ?"
1171
                   + " WHERE returnfield_id = ?";
1172 5165 daigle
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Update:"+ query);
1173 2421 sgarg
1174
               pstmt = dbconn.prepareStatement(query);
1175 6629 leinfelder
               pstmt.setInt(1, count);
1176
               pstmt.setInt(2, id);
1177 2421 sgarg
               dbconn.increaseUsageCount(1);
1178
               pstmt.execute();
1179
               pstmt.close();
1180
1181
           } else {
1182
               rs.close();
1183
               pstmt.close();
1184
1185
               // insert a new record
1186
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1187 2446 sgarg
                   + "VALUES (?, '1')";
1188 5165 daigle
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField Table Insert:"+ query);
1189 2421 sgarg
               pstmt = dbconn.prepareStatement(query);
1190 2446 sgarg
               pstmt.setString(1, returnfield);
1191 2421 sgarg
               dbconn.increaseUsageCount(1);
1192
               pstmt.execute();
1193
               pstmt.close();
1194
1195
               // get the id of the new record
1196 2446 sgarg
               query = "SELECT returnfield_id FROM xml_returnfield "
1197
                   + "WHERE returnfield_string LIKE ?";
1198 5165 daigle
               logMetacat.info("DBQuery.getXmlReturnfieldsTableId - ReturnField query after Insert:" + query);
1199 2421 sgarg
               pstmt = dbconn.prepareStatement(query);
1200 2446 sgarg
               pstmt.setString(1, returnfield);
1201
1202 2421 sgarg
               dbconn.increaseUsageCount(1);
1203
               pstmt.execute();
1204
               rs = pstmt.getResultSet();
1205
               if(rs.next()){
1206
                   id = rs.getInt(1);
1207
               } else {
1208
                   id = -1;
1209
               }
1210
               rs.close();
1211
               pstmt.close();
1212 2087 tao
           }
1213 2091 tao
1214 2421 sgarg
       } catch (Exception e){
1215 5165 daigle
           logMetacat.error("DBQuery.getXmlReturnfieldsTableId - Error getting id from xml_returnfield in "
1216 2421 sgarg
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1217 2663 sgarg
                                     + e.getMessage());
1218 2421 sgarg
           id = -1;
1219
       }
1220 2424 sgarg
1221
       returnfield_id = id;
1222
       return count;
1223 2087 tao
   }
1224 2043 sgarg
1225
1226 2087 tao
    /*
1227
     * A method to add return field to return doclist hash table
1228
     */
1229 3246 berkley
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1230 2087 tao
                                      QuerySpecification qspec,
1231
                                      String user, String[]groups,
1232 5490 berkley
                                      DBConnection dbconn, boolean useXMLIndex,
1233
                                      String qformat)
1234 2087 tao
                                      throws Exception
1235
    {
1236
      PreparedStatement pstmt = null;
1237
      ResultSet rs = null;
1238
      String docid = null;
1239
      String fieldname = null;
1240 3635 leinfelder
      String fieldtype = null;
1241 2087 tao
      String fielddata = null;
1242
      String relation = null;
1243 6629 leinfelder
      // keep track of parameter values
1244
      List<Object> parameterValues = new ArrayList<Object>();
1245 2087 tao
1246
      if (qspec.containsExtendedSQL())
1247
      {
1248
        qspec.setUserName(user);
1249
        qspec.setGroup(groups);
1250
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1251
        Vector results = new Vector();
1252 3246 berkley
        Iterator keylist = docListResult.getDocids();
1253 2087 tao
        StringBuffer doclist = new StringBuffer();
1254 6629 leinfelder
        List<Object> doclistValues = new ArrayList<Object>();
1255 2087 tao
        Vector parentidList = new Vector();
1256
        Hashtable returnFieldValue = new Hashtable();
1257 3246 berkley
        while (keylist.hasNext())
1258 2087 tao
        {
1259 5490 berkley
          String key = (String)keylist.next();
1260 6629 leinfelder
          doclist.append("?,");
1261
          doclistValues.add(key);
1262 2087 tao
        }
1263
        if (doclist.length() > 0)
1264
        {
1265
          Hashtable controlPairs = new Hashtable();
1266
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1267 3248 tao
          boolean tableHasRows = false;
1268 3349 tao
1269 2087 tao
1270 6629 leinfelder
1271 2087 tao
           String extendedQuery =
1272 6734 leinfelder
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex, parameterValues, doclistValues);
1273
           // DO not add doclist values -- they are included in the query
1274
           //parameterValues.addAll(doclistValues);
1275 5165 daigle
           logMetacat.info("DBQuery.addReturnfield - Extended query: " + extendedQuery);
1276 2376 sgarg
1277 2474 sgarg
           if(extendedQuery != null){
1278 5165 daigle
//        	   long extendedQueryStart = System.currentTimeMillis();
1279 2474 sgarg
               pstmt = dbconn.prepareStatement(extendedQuery);
1280 6602 leinfelder
               // set the parameter values
1281
               pstmt = DBQuery.setPreparedStatementValues(parameterValues, pstmt);
1282 2474 sgarg
               //increase dbconnection usage count
1283
               dbconn.increaseUsageCount(1);
1284
               pstmt.execute();
1285
               rs = pstmt.getResultSet();
1286
               tableHasRows = rs.next();
1287
               while (tableHasRows) {
1288
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1289
                   docid = rs.getString(1).trim();
1290
                   fieldname = rs.getString(2);
1291 5490 berkley
1292
                   if(qformat.toLowerCase().trim().equals("xml"))
1293
                   {
1294
                       byte[] b = rs.getBytes(3);
1295 5756 leinfelder
                       fielddata = new String(b, 0, b.length, MetaCatServlet.DEFAULT_ENCODING);
1296 5490 berkley
                   }
1297
                   else
1298
                   {
1299
                       fielddata = rs.getString(3);
1300
                   }
1301
1302
                   //System.out.println("raw fielddata: " + fielddata);
1303 4698 daigle
                   fielddata = MetacatUtil.normalize(fielddata);
1304 5490 berkley
                   //System.out.println("normalized fielddata: " + fielddata);
1305 2474 sgarg
                   String parentId = rs.getString(4);
1306 3635 leinfelder
                   fieldtype = rs.getString(5);
1307 2474 sgarg
                   StringBuffer value = new StringBuffer();
1308 2043 sgarg
1309 3635 leinfelder
                   //handle case when usexmlindex is true differently
1310
                   //at one point merging the nodedata (for large text elements) was
1311
                   //deemed unnecessary - but now it is needed.  but not for attribute nodes
1312 2474 sgarg
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1313 3635 leinfelder
                	   //merge node data only for non-ATTRIBUTEs
1314
                	   if (fieldtype != null && !fieldtype.equals("ATTRIBUTE")) {
1315
	                	   //try merging the data
1316
	                	   ReturnFieldValue existingRFV =
1317
	                		   getArrayValue(parentidList, parentId);
1318 5387 berkley
	                	   if (existingRFV != null && !existingRFV.getFieldType().equals("ATTRIBUTE")) {
1319 3635 leinfelder
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1320
	                	   }
1321
                	   }
1322 5387 berkley
                	   //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1323 5490 berkley
1324 2474 sgarg
                       value.append("<param name=\"");
1325
                       value.append(fieldname);
1326
                       value.append("\">");
1327
                       value.append(fielddata);
1328
                       value.append("</param>");
1329
                       //set returnvalue
1330
                       returnValue.setDocid(docid);
1331
                       returnValue.setFieldValue(fielddata);
1332 3635 leinfelder
                       returnValue.setFieldType(fieldtype);
1333 2474 sgarg
                       returnValue.setXMLFieldValue(value.toString());
1334
                       // Store it in hastable
1335
                       putInArray(parentidList, parentId, returnValue);
1336
                   }
1337
                   else {
1338 5490 berkley
1339 2474 sgarg
                       // need to merge nodedata if they have same parent id and
1340
                       // node type is text
1341
                       fielddata = (String) ( (ReturnFieldValue)
1342
                                             getArrayValue(
1343
                           parentidList, parentId)).getFieldValue()
1344
                           + fielddata;
1345 5490 berkley
                       //System.out.println("fieldname: " + fieldname + " fielddata: " + fielddata);
1346 2474 sgarg
                       value.append("<param name=\"");
1347
                       value.append(fieldname);
1348
                       value.append("\">");
1349
                       value.append(fielddata);
1350
                       value.append("</param>");
1351
                       returnValue.setDocid(docid);
1352
                       returnValue.setFieldValue(fielddata);
1353 3635 leinfelder
                       returnValue.setFieldType(fieldtype);
1354 2474 sgarg
                       returnValue.setXMLFieldValue(value.toString());
1355
                       // remove the old return value from paretnidList
1356
                       parentidList.remove(parentId);
1357
                       // store the new return value in parentidlit
1358
                       putInArray(parentidList, parentId, returnValue);
1359
                   }
1360
                   tableHasRows = rs.next();
1361
               } //while
1362
               rs.close();
1363
               pstmt.close();
1364 2043 sgarg
1365 2474 sgarg
               // put the merger node data info into doclistReult
1366
               Enumeration xmlFieldValue = (getElements(parentidList)).
1367
                   elements();
1368
               while (xmlFieldValue.hasMoreElements()) {
1369
                   ReturnFieldValue object =
1370
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1371
                   docid = object.getDocid();
1372 3246 berkley
                   if (docListResult.containsDocid(docid)) {
1373 2474 sgarg
                       String removedelement = (String) docListResult.
1374
                           remove(docid);
1375
                       docListResult.
1376 3246 berkley
                           addResultDocument(new ResultDocument(docid,
1377
                               removedelement + object.getXMLFieldValue()));
1378 2474 sgarg
                   }
1379
                   else {
1380 3246 berkley
                       docListResult.addResultDocument(
1381
                         new ResultDocument(docid, object.getXMLFieldValue()));
1382 2474 sgarg
                   }
1383
               } //while
1384 5165 daigle
//               double docListResultEnd = System.currentTimeMillis() / 1000;
1385
//               logMetacat.warn(
1386
//                   "Time to prepare ResultDocumentSet after"
1387
//                   + " execute extended query: "
1388
//                   + (docListResultEnd - extendedQueryEnd));
1389 2474 sgarg
           }
1390 2087 tao
       }//if doclist lenght is great than zero
1391
     }//if has extended query
1392 2043 sgarg
1393 2087 tao
      return docListResult;
1394
    }//addReturnfield
1395 2043 sgarg
1396 3730 tao
1397 2087 tao
  /**
1398
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1399
   * string as a param instead of a hashtable.
1400
   *
1401
   * @param xmlquery a string representing a query.
1402
   */
1403
   private  String transformQuery(String xmlquery)
1404
   {
1405
     xmlquery = xmlquery.trim();
1406
     int index = xmlquery.indexOf("?>");
1407
     if (index != -1)
1408
     {
1409
       return xmlquery.substring(index + 2, xmlquery.length());
1410
     }
1411
     else
1412
     {
1413
       return xmlquery;
1414
     }
1415
   }
1416 3340 tao
1417
   /*
1418 3342 tao
    * Method to store query string and result xml string into query result
1419 3340 tao
    * cache. If the size alreay reache the limitation, the cache will be
1420
    * cleared first, then store them.
1421
    */
1422 3342 tao
   private void storeQueryResultIntoCache(String query, String resultXML)
1423 3340 tao
   {
1424
	   synchronized (queryResultCache)
1425
	   {
1426
		   if (queryResultCache.size() >= QUERYRESULTCACHESIZE)
1427
		   {
1428
			   queryResultCache.clear();
1429
		   }
1430 3342 tao
		   queryResultCache.put(query, resultXML);
1431 3340 tao
1432
	   }
1433
   }
1434
1435
   /*
1436 3342 tao
    * Method to get result xml string from query result cache.
1437
    * Note: the returned string can be null.
1438 3340 tao
    */
1439 3342 tao
   private String getResultXMLFromCache(String query)
1440 3340 tao
   {
1441 3342 tao
	   String resultSet = null;
1442 3340 tao
	   synchronized (queryResultCache)
1443
	   {
1444
          try
1445
          {
1446 5165 daigle
        	 logMetacat.info("DBQuery.getResultXMLFromCache - Get query from cache");
1447 3342 tao
		     resultSet = (String)queryResultCache.get(query);
1448 3340 tao
1449
          }
1450
          catch (Exception e)
1451
          {
1452
        	  resultSet = null;
1453
          }
1454
1455
	   }
1456
	   return resultSet;
1457
   }
1458
1459
   /**
1460
    * Method to clear the query result cache.
1461
    */
1462
   public static void clearQueryResultCache()
1463
   {
1464
	   synchronized (queryResultCache)
1465
	   {
1466
		   queryResultCache.clear();
1467
	   }
1468
   }
1469 6602 leinfelder
1470
   /**
1471
    * Set the parameter values in the prepared statement using instrospection
1472
    * of the given value objects
1473
    * @param parameterValues
1474
    * @param pstmt
1475
    * @return
1476
    * @throws SQLException
1477
    */
1478
   public static PreparedStatement setPreparedStatementValues(List<Object> parameterValues, PreparedStatement pstmt) throws SQLException {
1479
	   // set all the values we have collected
1480
      int parameterIndex = 1;
1481
      for (Object parameterValue: parameterValues) {
1482
    	  if (parameterValue instanceof String) {
1483
    		  pstmt.setString(parameterIndex, (String) parameterValue);
1484
    	  }
1485
    	  else if (parameterValue instanceof Integer) {
1486
    		  pstmt.setInt(parameterIndex, (Integer) parameterValue);
1487
    	  }
1488
    	  else if (parameterValue instanceof Float) {
1489
    		  pstmt.setFloat(parameterIndex, (Float) parameterValue);
1490
    	  }
1491
    	  else if (parameterValue instanceof Double) {
1492
    		  pstmt.setDouble(parameterIndex, (Double) parameterValue);
1493
    	  }
1494
    	  else if (parameterValue instanceof Date) {
1495
    		  pstmt.setTimestamp(parameterIndex, new Timestamp(((Date) parameterValue).getTime()));
1496
    	  }
1497
    	  else {
1498
    		  pstmt.setObject(parameterIndex, parameterValue);
1499
    	  }
1500
    	  parameterIndex++;
1501
      }
1502
      return pstmt;
1503
   }
1504 2087 tao
1505
1506 2075 jones
    /*
1507
     * A method to search if Vector contains a particular key string
1508
     */
1509
    private boolean containsKey(Vector parentidList, String parentId)
1510
    {
1511 2043 sgarg
1512 2075 jones
        Vector tempVector = null;
1513 2043 sgarg
1514 2075 jones
        for (int count = 0; count < parentidList.size(); count++) {
1515
            tempVector = (Vector) parentidList.get(count);
1516 2360 sgarg
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1517 2075 jones
        }
1518
        return false;
1519 2043 sgarg
    }
1520 3635 leinfelder
1521 2075 jones
    /*
1522
     * A method to put key and value in Vector
1523
     */
1524
    private void putInArray(Vector parentidList, String key,
1525
            ReturnFieldValue value)
1526
    {
1527 2043 sgarg
1528 2075 jones
        Vector tempVector = null;
1529 3635 leinfelder
        //only filter if the field type is NOT an attribute (say, for text)
1530
        String fieldType = value.getFieldType();
1531
        if (fieldType != null && !fieldType.equals("ATTRIBUTE")) {
1532
1533
	        for (int count = 0; count < parentidList.size(); count++) {
1534
	            tempVector = (Vector) parentidList.get(count);
1535
1536
	            if (key.compareTo((String) tempVector.get(0)) == 0) {
1537
	                tempVector.remove(1);
1538
	                tempVector.add(1, value);
1539
	                return;
1540
	            }
1541
	        }
1542 2075 jones
        }
1543 2043 sgarg
1544 2075 jones
        tempVector = new Vector();
1545
        tempVector.add(0, key);
1546
        tempVector.add(1, value);
1547
        parentidList.add(tempVector);
1548
        return;
1549 2043 sgarg
    }
1550
1551 2075 jones
    /*
1552
     * A method to get value in Vector given a key
1553
     */
1554
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1555 1353 tao
    {
1556 2043 sgarg
1557 2075 jones
        Vector tempVector = null;
1558 2043 sgarg
1559 5490 berkley
        for (int count = 0; count < parentidList.size(); count++) {
1560 2075 jones
            tempVector = (Vector) parentidList.get(count);
1561 2043 sgarg
1562 5490 berkley
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1563
                    .get(1); }
1564 2075 jones
        }
1565
        return null;
1566 2045 tao
    }
1567 436 berkley
1568 2075 jones
    /*
1569
     * A method to get enumeration of all values in Vector
1570
     */
1571
    private Vector getElements(Vector parentidList)
1572 342 berkley
    {
1573 2446 sgarg
        Vector enumVector = new Vector();
1574 2075 jones
        Vector tempVector = null;
1575 2043 sgarg
1576 2075 jones
        for (int count = 0; count < parentidList.size(); count++) {
1577
            tempVector = (Vector) parentidList.get(count);
1578 744 jones
1579 2446 sgarg
            enumVector.add(tempVector.get(1));
1580 744 jones
        }
1581 2446 sgarg
        return enumVector;
1582 372 berkley
    }
1583 2043 sgarg
1584 3308 tao
1585 2043 sgarg
1586 2075 jones
    /*
1587
     * A method to create a query to get owner's docid list
1588
     */
1589 6629 leinfelder
    private String getOwnerQuery(String owner, List<Object> parameterValues)
1590 372 berkley
    {
1591 2075 jones
        if (owner != null) {
1592
            owner = owner.toLowerCase();
1593
        }
1594
        StringBuffer self = new StringBuffer();
1595 2043 sgarg
1596 2075 jones
        self.append("SELECT docid,docname,doctype,");
1597
        self.append("date_created, date_updated, rev ");
1598
        self.append("FROM xml_documents WHERE docid IN (");
1599
        self.append("(");
1600
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1601
        self.append("nodedata LIKE '%%%' ");
1602
        self.append(") \n");
1603
        self.append(") ");
1604
        self.append(" AND (");
1605 6629 leinfelder
        self.append(" lower(user_owner) = ?");
1606 2075 jones
        self.append(") ");
1607 6629 leinfelder
        parameterValues.add(owner);
1608 2075 jones
        return self.toString();
1609 342 berkley
    }
1610 2043 sgarg
1611 2075 jones
    /**
1612
     * format a structured query as an XML document that conforms to the
1613
     * pathquery.dtd and is appropriate for submission to the DBQuery
1614
     * structured query engine
1615 2087 tao
     *
1616 2075 jones
     * @param params The list of parameters that should be included in the
1617
     *            query
1618
     */
1619 4080 daigle
    public static String createSQuery(Hashtable params) throws PropertyNotFoundException
1620 342 berkley
    {
1621 2075 jones
        StringBuffer query = new StringBuffer();
1622
        Enumeration elements;
1623
        Enumeration keys;
1624
        String filterDoctype = null;
1625
        String casesensitive = null;
1626
        String searchmode = null;
1627
        Object nextkey;
1628
        Object nextelement;
1629
        //add the xml headers
1630
        query.append("<?xml version=\"1.0\"?>\n");
1631 2091 tao
        query.append("<pathquery version=\"1.2\">\n");
1632 372 berkley
1633 2091 tao
1634
1635 2075 jones
        if (params.containsKey("meta_file_id")) {
1636
            query.append("<meta_file_id>");
1637
            query.append(((String[]) params.get("meta_file_id"))[0]);
1638
            query.append("</meta_file_id>");
1639 372 berkley
        }
1640 2043 sgarg
1641 2075 jones
        if (params.containsKey("returndoctype")) {
1642
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1643
            for (int i = 0; i < returnDoctypes.length; i++) {
1644
                String doctype = (String) returnDoctypes[i];
1645 181 jones
1646 2075 jones
                if (!doctype.equals("any") && !doctype.equals("ANY")
1647
                        && !doctype.equals("")) {
1648
                    query.append("<returndoctype>").append(doctype);
1649
                    query.append("</returndoctype>");
1650
                }
1651
            }
1652
        }
1653 181 jones
1654 2075 jones
        if (params.containsKey("filterdoctype")) {
1655
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1656
            for (int i = 0; i < filterDoctypes.length; i++) {
1657
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1658
                query.append("</filterdoctype>");
1659
            }
1660
        }
1661 181 jones
1662 2075 jones
        if (params.containsKey("returnfield")) {
1663
            String[] returnfield = ((String[]) params.get("returnfield"));
1664
            for (int i = 0; i < returnfield.length; i++) {
1665
                query.append("<returnfield>").append(returnfield[i]);
1666
                query.append("</returnfield>");
1667
            }
1668
        }
1669 2043 sgarg
1670 2075 jones
        if (params.containsKey("owner")) {
1671
            String[] owner = ((String[]) params.get("owner"));
1672
            for (int i = 0; i < owner.length; i++) {
1673
                query.append("<owner>").append(owner[i]);
1674
                query.append("</owner>");
1675
            }
1676
        }
1677 181 jones
1678 2075 jones
        if (params.containsKey("site")) {
1679
            String[] site = ((String[]) params.get("site"));
1680
            for (int i = 0; i < site.length; i++) {
1681
                query.append("<site>").append(site[i]);
1682
                query.append("</site>");
1683
            }
1684
        }
1685 2043 sgarg
1686 2075 jones
        //allows the dynamic switching of boolean operators
1687
        if (params.containsKey("operator")) {
1688
            query.append("<querygroup operator=\""
1689
                    + ((String[]) params.get("operator"))[0] + "\">");
1690
        } else { //the default operator is UNION
1691
            query.append("<querygroup operator=\"UNION\">");
1692
        }
1693 940 tao
1694 2075 jones
        if (params.containsKey("casesensitive")) {
1695
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1696
        } else {
1697
            casesensitive = "false";
1698
        }
1699 2043 sgarg
1700 2075 jones
        if (params.containsKey("searchmode")) {
1701
            searchmode = ((String[]) params.get("searchmode"))[0];
1702
        } else {
1703
            searchmode = "contains";
1704 940 tao
        }
1705
1706 2075 jones
        //anyfield is a special case because it does a
1707
        //free text search. It does not have a <pathexpr>
1708
        //tag. This allows for a free text search within the structured
1709
        //query. This is useful if the INTERSECT operator is used.
1710
        if (params.containsKey("anyfield")) {
1711
            String[] anyfield = ((String[]) params.get("anyfield"));
1712
            //allow for more than one value for anyfield
1713
            for (int i = 0; i < anyfield.length; i++) {
1714 4135 berkley
                if (anyfield[i] != null && !anyfield[i].equals("")) {
1715 2075 jones
                    query.append("<queryterm casesensitive=\"" + casesensitive
1716
                            + "\" " + "searchmode=\"" + searchmode
1717
                            + "\"><value>" + anyfield[i]
1718
                            + "</value></queryterm>");
1719
                }
1720
            }
1721 940 tao
        }
1722 2043 sgarg
1723 2075 jones
        //this while loop finds the rest of the parameters
1724
        //and attempts to query for the field specified
1725
        //by the parameter.
1726
        elements = params.elements();
1727
        keys = params.keys();
1728
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1729
            nextkey = keys.nextElement();
1730
            nextelement = elements.nextElement();
1731 2043 sgarg
1732 2075 jones
            //make sure we aren't querying for any of these
1733
            //parameters since the are already in the query
1734
            //in one form or another.
1735
            Vector ignoredParams = new Vector();
1736
            ignoredParams.add("returndoctype");
1737
            ignoredParams.add("filterdoctype");
1738
            ignoredParams.add("action");
1739
            ignoredParams.add("qformat");
1740
            ignoredParams.add("anyfield");
1741
            ignoredParams.add("returnfield");
1742
            ignoredParams.add("owner");
1743
            ignoredParams.add("site");
1744
            ignoredParams.add("operator");
1745 2091 tao
            ignoredParams.add("sessionid");
1746 3211 berkley
            ignoredParams.add("pagesize");
1747
            ignoredParams.add("pagestart");
1748 4135 berkley
            ignoredParams.add("searchmode");
1749 2043 sgarg
1750 2075 jones
            // Also ignore parameters listed in the properties file
1751
            // so that they can be passed through to stylesheets
1752 4080 daigle
            String paramsToIgnore = PropertyService
1753 4173 daigle
                    .getProperty("database.queryignoredparams");
1754 2075 jones
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1755
            while (st.hasMoreTokens()) {
1756
                ignoredParams.add(st.nextToken());
1757
            }
1758
            if (!ignoredParams.contains(nextkey.toString())) {
1759
                //allow for more than value per field name
1760
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1761
                    if (!((String[]) nextelement)[i].equals("")) {
1762
                        query.append("<queryterm casesensitive=\""
1763
                                + casesensitive + "\" " + "searchmode=\""
1764 2087 tao
                                + searchmode + "\">" + "<value>" +
1765 2075 jones
                                //add the query value
1766
                                ((String[]) nextelement)[i]
1767 2087 tao
                                + "</value><pathexpr>" +
1768 2075 jones
                                //add the path to query by
1769
                                nextkey.toString() + "</pathexpr></queryterm>");
1770
                    }
1771
                }
1772
            }
1773
        }
1774
        query.append("</querygroup></pathquery>");
1775
        //append on the end of the xml and return the result as a string
1776
        return query.toString();
1777
    }
1778 2043 sgarg
1779 2075 jones
    /**
1780
     * format a simple free-text value query as an XML document that conforms
1781
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1782
     * structured query engine
1783 2087 tao
     *
1784 2075 jones
     * @param value the text string to search for in the xml catalog
1785
     * @param doctype the type of documents to include in the result set -- use
1786
     *            "any" or "ANY" for unfiltered result sets
1787
     */
1788
    public static String createQuery(String value, String doctype)
1789 1292 tao
    {
1790 2075 jones
        StringBuffer xmlquery = new StringBuffer();
1791
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1792
        xmlquery.append("<pathquery version=\"1.0\">");
1793 2043 sgarg
1794 2075 jones
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1795
            xmlquery.append("<returndoctype>");
1796
            xmlquery.append(doctype).append("</returndoctype>");
1797
        }
1798 2043 sgarg
1799 2075 jones
        xmlquery.append("<querygroup operator=\"UNION\">");
1800
        //chad added - 8/14
1801
        //the if statement allows a query to gracefully handle a null
1802
        //query. Without this if a nullpointerException is thrown.
1803
        if (!value.equals("")) {
1804
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1805
            xmlquery.append("searchmode=\"contains\">");
1806
            xmlquery.append("<value>").append(value).append("</value>");
1807
            xmlquery.append("</queryterm>");
1808 1217 tao
        }
1809 2075 jones
        xmlquery.append("</querygroup>");
1810
        xmlquery.append("</pathquery>");
1811 2043 sgarg
1812 2075 jones
        return (xmlquery.toString());
1813
    }
1814 2043 sgarg
1815 2075 jones
    /**
1816
     * format a simple free-text value query as an XML document that conforms
1817
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1818
     * structured query engine
1819 2087 tao
     *
1820 2075 jones
     * @param value the text string to search for in the xml catalog
1821
     */
1822
    public static String createQuery(String value)
1823 940 tao
    {
1824 2075 jones
        return createQuery(value, "any");
1825 940 tao
    }
1826 2043 sgarg
1827 2075 jones
    /**
1828
     * Check for "READ" permission on @docid for @user and/or @group from DB
1829
     * connection
1830
     */
1831
    private boolean hasPermission(String user, String[] groups, String docid)
1832
            throws SQLException, Exception
1833 940 tao
    {
1834 2075 jones
        // Check for READ permission on @docid for @user and/or @groups
1835
        PermissionController controller = new PermissionController(docid);
1836
        return controller.hasPermission(user, groups,
1837
                AccessControlInterface.READSTRING);
1838
    }
1839 2043 sgarg
1840 2075 jones
    /**
1841
     * Get all docIds list for a data packadge
1842 2087 tao
     *
1843 2075 jones
     * @param dataPackageDocid, the string in docId field of xml_relation table
1844
     */
1845
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1846 940 tao
    {
1847 2075 jones
        DBConnection dbConn = null;
1848
        int serialNumber = -1;
1849
        Vector docIdList = new Vector();//return value
1850
        PreparedStatement pStmt = null;
1851
        ResultSet rs = null;
1852
        String docIdInSubjectField = null;
1853
        String docIdInObjectField = null;
1854 2043 sgarg
1855 2075 jones
        // Check the parameter
1856
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1857 940 tao
1858 2075 jones
        //the query stirng
1859
        String query = "SELECT subject, object from xml_relation where docId = ?";
1860
        try {
1861
            dbConn = DBConnectionPool
1862
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1863
            serialNumber = dbConn.getCheckOutSerialNumber();
1864
            pStmt = dbConn.prepareStatement(query);
1865
            //bind the value to query
1866
            pStmt.setString(1, dataPackageDocid);
1867 2043 sgarg
1868 2075 jones
            //excute the query
1869
            pStmt.execute();
1870
            //get the result set
1871
            rs = pStmt.getResultSet();
1872
            //process the result
1873
            while (rs.next()) {
1874
                //In order to get the whole docIds in a data packadge,
1875
                //we need to put the docIds of subject and object field in
1876
                // xml_relation
1877
                //into the return vector
1878
                docIdInSubjectField = rs.getString(1);//the result docId in
1879
                                                      // subject field
1880
                docIdInObjectField = rs.getString(2);//the result docId in
1881
                                                     // object field
1882 940 tao
1883 2075 jones
                //don't put the duplicate docId into the vector
1884
                if (!docIdList.contains(docIdInSubjectField)) {
1885
                    docIdList.add(docIdInSubjectField);
1886
                }
1887 2043 sgarg
1888 2075 jones
                //don't put the duplicate docId into the vector
1889
                if (!docIdList.contains(docIdInObjectField)) {
1890
                    docIdList.add(docIdInObjectField);
1891
                }
1892
            }//while
1893
            //close the pStmt
1894
            pStmt.close();
1895
        }//try
1896
        catch (SQLException e) {
1897 5165 daigle
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - Error in getDocidListForDataPackage: "
1898 2663 sgarg
                    + e.getMessage());
1899 2075 jones
        }//catch
1900
        finally {
1901
            try {
1902
                pStmt.close();
1903
            }//try
1904
            catch (SQLException ee) {
1905 5165 daigle
                logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - SQL Error: "
1906 2663 sgarg
                                + ee.getMessage());
1907 2075 jones
            }//catch
1908
            finally {
1909
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1910
            }//fianlly
1911
        }//finally
1912
        return docIdList;
1913
    }//getCurrentDocidListForDataPackadge()
1914 2043 sgarg
1915 2075 jones
    /**
1916
     * Get all docIds list for a data packadge
1917 2087 tao
     *
1918 2075 jones
     * @param dataPackageDocid, the string in docId field of xml_relation table
1919
     */
1920 2641 tao
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1921 940 tao
    {
1922 2043 sgarg
1923 2075 jones
        Vector docIdList = new Vector();//return value
1924
        Vector tripleList = null;
1925
        String xml = null;
1926 2043 sgarg
1927 2075 jones
        // Check the parameter
1928 2641 tao
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1929 2043 sgarg
1930 2075 jones
        try {
1931
            //initial a documentImpl object
1932 2641 tao
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1933 2075 jones
            //transfer to documentImpl object to string
1934
            xml = packageDocument.toString();
1935 2043 sgarg
1936 2075 jones
            //create a tripcollection object
1937
            TripleCollection tripleForPackage = new TripleCollection(
1938
                    new StringReader(xml));
1939
            //get the vetor of triples
1940
            tripleList = tripleForPackage.getCollection();
1941 2043 sgarg
1942 2075 jones
            for (int i = 0; i < tripleList.size(); i++) {
1943
                //put subject docid into docIdlist without duplicate
1944
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1945
                        .getSubject())) {
1946
                    //put subject docid into docIdlist
1947
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1948
                }
1949
                //put object docid into docIdlist without duplicate
1950
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1951
                        .getObject())) {
1952
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1953
                }
1954
            }//for
1955
        }//try
1956
        catch (Exception e) {
1957 5165 daigle
            logMetacat.error("DBQuery.getCurrentDocidListForDataPackage - General error: "
1958 2663 sgarg
                    + e.getMessage());
1959 2075 jones
        }//catch
1960 2043 sgarg
1961 2075 jones
        // return result
1962
        return docIdList;
1963
    }//getDocidListForPackageInXMLRevisions()
1964 2043 sgarg
1965 2075 jones
    /**
1966
     * Check if the docId is a data packadge id. If the id is a data packadage
1967
     * id, it should be store in the docId fields in xml_relation table. So we
1968
     * can use a query to get the entries which the docId equals the given
1969
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1970
     * it is.
1971 2087 tao
     *
1972 2075 jones
     * @param docId, the id need to be checked
1973
     */
1974
    private boolean isDataPackageId(String docId)
1975 940 tao
    {
1976 2075 jones
        boolean result = false;
1977
        PreparedStatement pStmt = null;
1978
        ResultSet rs = null;
1979
        String query = "SELECT docId from xml_relation where docId = ?";
1980
        DBConnection dbConn = null;
1981
        int serialNumber = -1;
1982
        try {
1983
            dbConn = DBConnectionPool
1984
                    .getDBConnection("DBQuery.isDataPackageId");
1985
            serialNumber = dbConn.getCheckOutSerialNumber();
1986
            pStmt = dbConn.prepareStatement(query);
1987
            //bind the value to query
1988
            pStmt.setString(1, docId);
1989
            //execute the query
1990
            pStmt.execute();
1991
            rs = pStmt.getResultSet();
1992
            //process the result
1993
            if (rs.next()) //There are some records for the id in docId fields
1994
            {
1995
                result = true;//It is a data packadge id
1996
            }
1997
            pStmt.close();
1998
        }//try
1999
        catch (SQLException e) {
2000 5165 daigle
            logMetacat.error("DBQuery.isDataPackageId - SQL Error: "
2001 2663 sgarg
                    + e.getMessage());
2002 2075 jones
        } finally {
2003
            try {
2004
                pStmt.close();
2005
            }//try
2006
            catch (SQLException ee) {
2007 5165 daigle
                logMetacat.error("DBQuery.isDataPackageId - SQL Error in isDataPackageId: "
2008 2663 sgarg
                        + ee.getMessage());
2009 2075 jones
            }//catch
2010
            finally {
2011
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2012
            }//finally
2013
        }//finally
2014
        return result;
2015
    }//isDataPackageId()
2016 2043 sgarg
2017 6035 leinfelder
    public String getOperator() {
2018
		return operator;
2019
	}
2020
2021 2075 jones
    /**
2022 6035 leinfelder
     * Specifies if and how docid overrides should be included in the general query
2023
     * @param operator null, UNION, or INTERSECT (see QueryGroup)
2024
     */
2025
	public void setOperator(String operator) {
2026
		this.operator = operator;
2027
	}
2028
2029
	/**
2030 2075 jones
     * Check if the user has the permission to export data package
2031 2087 tao
     *
2032 2075 jones
     * @param conn, the connection
2033
     * @param docId, the id need to be checked
2034
     * @param user, the name of user
2035
     * @param groups, the user's group
2036
     */
2037
    private boolean hasPermissionToExportPackage(String docId, String user,
2038
            String[] groups) throws Exception
2039 940 tao
    {
2040 2075 jones
        //DocumentImpl doc=new DocumentImpl(conn,docId);
2041
        return DocumentImpl.hasReadPermission(user, groups, docId);
2042
    }
2043 2043 sgarg
2044 2075 jones
    /**
2045
     * Get the current Rev for a docid in xml_documents table
2046 2087 tao
     *
2047 2075 jones
     * @param docId, the id need to get version numb If the return value is -5,
2048
     *            means no value in rev field for this docid
2049
     */
2050
    private int getCurrentRevFromXMLDoumentsTable(String docId)
2051
            throws SQLException
2052
    {
2053
        int rev = -5;
2054
        PreparedStatement pStmt = null;
2055
        ResultSet rs = null;
2056
        String query = "SELECT rev from xml_documents where docId = ?";
2057
        DBConnection dbConn = null;
2058
        int serialNumber = -1;
2059
        try {
2060
            dbConn = DBConnectionPool
2061
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
2062
            serialNumber = dbConn.getCheckOutSerialNumber();
2063
            pStmt = dbConn.prepareStatement(query);
2064
            //bind the value to query
2065
            pStmt.setString(1, docId);
2066
            //execute the query
2067
            pStmt.execute();
2068
            rs = pStmt.getResultSet();
2069
            //process the result
2070
            if (rs.next()) //There are some records for rev
2071
            {
2072
                rev = rs.getInt(1);
2073
                ;//It is the version for given docid
2074
            } else {
2075
                rev = -5;
2076
            }
2077 2043 sgarg
2078 1292 tao
        }//try
2079 2075 jones
        catch (SQLException e) {
2080 5165 daigle
            logMetacat.error("DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
2081 2663 sgarg
                            + e.getMessage());
2082 2075 jones
            throw e;
2083 1292 tao
        }//catch
2084 2075 jones
        finally {
2085
            try {
2086
                pStmt.close();
2087
            }//try
2088
            catch (SQLException ee) {
2089 2663 sgarg
                logMetacat.error(
2090 5165 daigle
                        "DBQuery.getCurrentRevFromXMLDoumentsTable - SQL Error: "
2091 2663 sgarg
                                + ee.getMessage());
2092 2075 jones
            }//catch
2093
            finally {
2094
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2095
            }//finally
2096
        }//finally
2097
        return rev;
2098
    }//getCurrentRevFromXMLDoumentsTable
2099 2043 sgarg
2100 2075 jones
    /**
2101
     * put a doc into a zip output stream
2102 2087 tao
     *
2103 2075 jones
     * @param docImpl, docmentImpl object which will be sent to zip output
2104
     *            stream
2105
     * @param zipOut, zip output stream which the docImpl will be put
2106
     * @param packageZipEntry, the zip entry name for whole package
2107
     */
2108
    private void addDocToZipOutputStream(DocumentImpl docImpl,
2109
            ZipOutputStream zipOut, String packageZipEntry)
2110
            throws ClassNotFoundException, IOException, SQLException,
2111
            McdbException, Exception
2112
    {
2113
        byte[] byteString = null;
2114
        ZipEntry zEntry = null;
2115 2043 sgarg
2116 5760 leinfelder
        byteString = docImpl.getBytes();
2117 2075 jones
        //use docId as the zip entry's name
2118
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
2119
                + docImpl.getDocID());
2120
        zEntry.setSize(byteString.length);
2121
        zipOut.putNextEntry(zEntry);
2122
        zipOut.write(byteString, 0, byteString.length);
2123
        zipOut.closeEntry();
2124 2043 sgarg
2125 2075 jones
    }//addDocToZipOutputStream()
2126 940 tao
2127 2075 jones
    /**
2128
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
2129
     * only inlcudes current version. If a DocumentImple object couldn't find
2130
     * for a docid, then the String of this docid was added to vetor rather
2131
     * than DocumentImple object.
2132 2087 tao
     *
2133 2075 jones
     * @param docIdList, a vetor hold a docid list for a data package. In
2134
     *            docid, there is not version number in it.
2135
     */
2136 2043 sgarg
2137 2075 jones
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2138
            throws McdbException, Exception
2139 940 tao
    {
2140 2075 jones
        //Connection dbConn=null;
2141
        Vector documentImplList = new Vector();
2142
        int rev = 0;
2143 2043 sgarg
2144 2075 jones
        // Check the parameter
2145
        if (docIdList.isEmpty()) { return documentImplList; }//if
2146 2043 sgarg
2147 2075 jones
        //for every docid in vector
2148
        for (int i = 0; i < docIdList.size(); i++) {
2149
            try {
2150
                //get newest version for this docId
2151
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2152
                        .elementAt(i));
2153 940 tao
2154 2075 jones
                // There is no record for this docId in xml_documents table
2155
                if (rev == -5) {
2156
                    // Rather than put DocumentImple object, put a String
2157
                    // Object(docid)
2158
                    // into the documentImplList
2159
                    documentImplList.add((String) docIdList.elementAt(i));
2160
                    // Skip other code
2161
                    continue;
2162
                }
2163 2043 sgarg
2164 2075 jones
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2165 4212 daigle
                        + PropertyService.getProperty("document.accNumSeparator") + rev;
2166 2043 sgarg
2167 2075 jones
                //create new documentImpl object
2168
                DocumentImpl documentImplObject = new DocumentImpl(
2169
                        docidPlusVersion);
2170
                //add them to vector
2171
                documentImplList.add(documentImplObject);
2172
            }//try
2173
            catch (Exception e) {
2174 5165 daigle
                logMetacat.error("DBQuery.getCurrentAllDocumentImpl - General error: "
2175 2663 sgarg
                        + e.getMessage());
2176 2075 jones
                // continue the for loop
2177
                continue;
2178
            }
2179
        }//for
2180
        return documentImplList;
2181
    }
2182 2043 sgarg
2183 2075 jones
    /**
2184
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2185
     * object couldn't find for a docid, then the String of this docid was
2186
     * added to vetor rather than DocumentImple object.
2187 2087 tao
     *
2188 2075 jones
     * @param docIdList, a vetor hold a docid list for a data package. In
2189
     *            docid, t here is version number in it.
2190
     */
2191
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2192
    {
2193
        //Connection dbConn=null;
2194
        Vector documentImplList = new Vector();
2195
        String siteCode = null;
2196
        String uniqueId = null;
2197
        int rev = 0;
2198 2043 sgarg
2199 2075 jones
        // Check the parameter
2200
        if (docIdList.isEmpty()) { return documentImplList; }//if
2201 2043 sgarg
2202 2075 jones
        //for every docid in vector
2203
        for (int i = 0; i < docIdList.size(); i++) {
2204 2043 sgarg
2205 2075 jones
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2206
2207
            try {
2208
                //create new documentImpl object
2209
                DocumentImpl documentImplObject = new DocumentImpl(
2210
                        docidPlusVersion);
2211
                //add them to vector
2212
                documentImplList.add(documentImplObject);
2213
            }//try
2214
            catch (McdbDocNotFoundException notFoundE) {
2215 5165 daigle
                logMetacat.error("DBQuery.getOldVersionAllDocument - Error finding doc "
2216
                		+ docidPlusVersion + " : " + notFoundE.getMessage());
2217 2075 jones
                // Rather than add a DocumentImple object into vetor, a String
2218
                // object
2219
                // - the doicd was added to the vector
2220
                documentImplList.add(docidPlusVersion);
2221
                // Continue the for loop
2222
                continue;
2223
            }//catch
2224
            catch (Exception e) {
2225 2663 sgarg
                logMetacat.error(
2226 5165 daigle
                        "DBQuery.getOldVersionAllDocument - General error: "
2227 2663 sgarg
                                + e.getMessage());
2228 2075 jones
                // Continue the for loop
2229
                continue;
2230
            }//catch
2231
2232
        }//for
2233
        return documentImplList;
2234
    }//getOldVersionAllDocumentImple
2235
2236
    /**
2237
     * put a data file into a zip output stream
2238 2087 tao
     *
2239 2075 jones
     * @param docImpl, docmentImpl object which will be sent to zip output
2240
     *            stream
2241
     * @param zipOut, the zip output stream which the docImpl will be put
2242
     * @param packageZipEntry, the zip entry name for whole package
2243
     */
2244
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2245
            ZipOutputStream zipOut, String packageZipEntry)
2246
            throws ClassNotFoundException, IOException, SQLException,
2247
            McdbException, Exception
2248 940 tao
    {
2249 2075 jones
        byte[] byteString = null;
2250
        ZipEntry zEntry = null;
2251
        // this is data file; add file to zip
2252 4080 daigle
        String filePath = PropertyService.getProperty("application.datafilepath");
2253 2075 jones
        if (!filePath.endsWith("/")) {
2254
            filePath += "/";
2255
        }
2256
        String fileName = filePath + docImpl.getDocID();
2257
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2258
        zipOut.putNextEntry(zEntry);
2259
        FileInputStream fin = null;
2260
        try {
2261
            fin = new FileInputStream(fileName);
2262
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2263
            int b = fin.read(buf);
2264
            while (b != -1) {
2265
                zipOut.write(buf, 0, b);
2266
                b = fin.read(buf);
2267
            }//while
2268
            zipOut.closeEntry();
2269
        }//try
2270
        catch (IOException ioe) {
2271 5165 daigle
            logMetacat.error("DBQuery.addDataFileToZipOutputStream - I/O error: "
2272 2663 sgarg
                    + ioe.getMessage());
2273 2075 jones
        }//catch
2274
    }//addDataFileToZipOutputStream()
2275 2043 sgarg
2276 2075 jones
    /**
2277
     * create a html summary for data package and put it into zip output stream
2278 2087 tao
     *
2279 2075 jones
     * @param docImplList, the documentImpl ojbects in data package
2280
     * @param zipOut, the zip output stream which the html should be put
2281
     * @param packageZipEntry, the zip entry name for whole package
2282
     */
2283
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2284
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2285
    {
2286
        StringBuffer htmlDoc = new StringBuffer();
2287
        ZipEntry zEntry = null;
2288
        byte[] byteString = null;
2289
        InputStream source;
2290
        DBTransform xmlToHtml;
2291 2043 sgarg
2292 2075 jones
        //create a DBTransform ojbect
2293
        xmlToHtml = new DBTransform();
2294
        //head of html
2295
        htmlDoc.append("<html><head></head><body>");
2296
        for (int i = 0; i < docImplList.size(); i++) {
2297
            // If this String object, this means it is missed data file
2298
            if ((((docImplList.elementAt(i)).getClass()).toString())
2299
                    .equals("class java.lang.String")) {
2300 2043 sgarg
2301 2075 jones
                htmlDoc.append("<a href=\"");
2302
                String dataFileid = (String) docImplList.elementAt(i);
2303
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2304
                htmlDoc.append("Data File: ");
2305
                htmlDoc.append(dataFileid).append("</a><br>");
2306
                htmlDoc.append("<br><hr><br>");
2307 1356 tao
2308 2075 jones
            }//if
2309
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2310
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2311
                                              // transform it.
2312
                //transform each file individually then concatenate all of the
2313
                //transformations together.
2314 1356 tao
2315 2075 jones
                //for metadata xml title
2316
                htmlDoc.append("<h2>");
2317
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2318
                        .getDocID());
2319
                //htmlDoc.append(".");
2320
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2321
                htmlDoc.append("</h2>");
2322
                //do the actual transform
2323
                StringWriter docString = new StringWriter();
2324
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2325
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2326 5025 daigle
                        "-//W3C//HTML//EN", "html", docString, null, null);
2327 2075 jones
                htmlDoc.append(docString.toString());
2328
                htmlDoc.append("<br><br><hr><br><br>");
2329
            }//if
2330
            else { //this is a data file so we should link to it in the html
2331
                htmlDoc.append("<a href=\"");
2332
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2333
                        .getDocID();
2334
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2335
                htmlDoc.append("Data File: ");
2336
                htmlDoc.append(dataFileid).append("</a><br>");
2337
                htmlDoc.append("<br><hr><br>");
2338
            }//else
2339
        }//for
2340
        htmlDoc.append("</body></html>");
2341 5760 leinfelder
        // use standard encoding even though the different docs might have use different encodings,
2342
        // the String objects in java should be correct and able to be encoded as the same Metacat default
2343
        byteString = htmlDoc.toString().getBytes(MetaCatServlet.DEFAULT_ENCODING);
2344 2075 jones
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2345
        zEntry.setSize(byteString.length);
2346
        zipOut.putNextEntry(zEntry);
2347
        zipOut.write(byteString, 0, byteString.length);
2348
        zipOut.closeEntry();
2349
        //dbConn.close();
2350 1356 tao
2351 2075 jones
    }//addHtmlSummaryToZipOutputStream
2352 1356 tao
2353 2075 jones
    /**
2354
     * put a data packadge into a zip output stream
2355 2087 tao
     *
2356 2641 tao
     * @param docId, which the user want to put into zip output stream,it has version
2357 2075 jones
     * @param out, a servletoutput stream which the zip output stream will be
2358
     *            put
2359
     * @param user, the username of the user
2360
     * @param groups, the group of the user
2361
     */
2362
    public ZipOutputStream getZippedPackage(String docIdString,
2363
            ServletOutputStream out, String user, String[] groups,
2364
            String passWord) throws ClassNotFoundException, IOException,
2365
            SQLException, McdbException, NumberFormatException, Exception
2366 945 tao
    {
2367 2075 jones
        ZipOutputStream zOut = null;
2368
        String elementDocid = null;
2369
        DocumentImpl docImpls = null;
2370
        //Connection dbConn = null;
2371
        Vector docIdList = new Vector();
2372
        Vector documentImplList = new Vector();
2373
        Vector htmlDocumentImplList = new Vector();
2374
        String packageId = null;
2375
        String rootName = "package";//the package zip entry name
2376 2043 sgarg
2377 2075 jones
        String docId = null;
2378
        int version = -5;
2379
        // Docid without revision
2380 5025 daigle
        docId = DocumentUtil.getDocIdFromString(docIdString);
2381 2075 jones
        // revision number
2382 5025 daigle
        version = DocumentUtil.getVersionFromString(docIdString);
2383 2043 sgarg
2384 2075 jones
        //check if the reqused docId is a data package id
2385
        if (!isDataPackageId(docId)) {
2386 2043 sgarg
2387 2075 jones
            /*
2388
             * Exception e = new Exception("The request the doc id "
2389
             * +docIdString+ " is not a data package id");
2390
             */
2391 940 tao
2392 2075 jones
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2393
            // zip
2394
            //up the single document and return the zip file.
2395
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2396 2043 sgarg
2397 2075 jones
                Exception e = new Exception("User " + user
2398
                        + " does not have permission"
2399
                        + " to export the data package " + docIdString);
2400
                throw e;
2401
            }
2402 2043 sgarg
2403 2641 tao
            docImpls = new DocumentImpl(docIdString);
2404 2075 jones
            //checking if the user has the permission to read the documents
2405
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2406
                    .getDocID())) {
2407
                zOut = new ZipOutputStream(out);
2408
                //if the docImpls is metadata
2409
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2410
                    //add metadata into zip output stream
2411
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2412
                }//if
2413
                else {
2414
                    //it is data file
2415
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2416
                    htmlDocumentImplList.add(docImpls);
2417
                }//else
2418 1292 tao
            }//if
2419 2043 sgarg
2420 2075 jones
            zOut.finish(); //terminate the zip file
2421
            return zOut;
2422
        }
2423
        // Check the permission of user
2424
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2425
2426
            Exception e = new Exception("User " + user
2427
                    + " does not have permission"
2428
                    + " to export the data package " + docIdString);
2429
            throw e;
2430
        } else //it is a packadge id
2431 1292 tao
        {
2432 2075 jones
            //store the package id
2433
            packageId = docId;
2434
            //get current version in database
2435
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2436
            //If it is for current version (-1 means user didn't specify
2437
            // revision)
2438
            if ((version == -1) || version == currentVersion) {
2439
                //get current version number
2440
                version = currentVersion;
2441
                //get package zip entry name
2442
                //it should be docId.revsion.package
2443 4212 daigle
                rootName = packageId + PropertyService.getProperty("document.accNumSeparator")
2444
                        + version + PropertyService.getProperty("document.accNumSeparator")
2445 2075 jones
                        + "package";
2446
                //get the whole id list for data packadge
2447
                docIdList = getCurrentDocidListForDataPackage(packageId);
2448
                //get the whole documentImple object
2449
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2450 2043 sgarg
2451 1292 tao
            }//if
2452 2075 jones
            else if (version > currentVersion || version < -1) {
2453
                throw new Exception("The user specified docid: " + docId + "."
2454
                        + version + " doesn't exist");
2455
            }//else if
2456
            else //for an old version
2457 1292 tao
            {
2458 2075 jones
2459
                rootName = docIdString
2460 4212 daigle
                        + PropertyService.getProperty("document.accNumSeparator") + "package";
2461 2075 jones
                //get the whole id list for data packadge
2462
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2463
2464
                //get the whole documentImple object
2465
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2466 1292 tao
            }//else
2467 940 tao
2468 2075 jones
            // Make sure documentImplist is not empty
2469
            if (documentImplList.isEmpty()) { throw new Exception(
2470
                    "Couldn't find component for data package: " + packageId); }//if
2471 2043 sgarg
2472 2075 jones
            zOut = new ZipOutputStream(out);
2473
            //put every element into zip output stream
2474
            for (int i = 0; i < documentImplList.size(); i++) {
2475
                // if the object in the vetor is String, this means we couldn't
2476
                // find
2477
                // the document locally, we need find it remote
2478
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2479
                        .equals("class java.lang.String")) {
2480
                    // Get String object from vetor
2481
                    String documentId = (String) documentImplList.elementAt(i);
2482 5165 daigle
                    logMetacat.info("DBQuery.getZippedPackage - docid: " + documentId);
2483 2075 jones
                    // Get doicd without revision
2484 5025 daigle
                    String docidWithoutRevision =
2485
                    	DocumentUtil.getDocIdFromString(documentId);
2486 5165 daigle
                    logMetacat.info("DBQuery.getZippedPackage - docidWithoutRevsion: "
2487 2663 sgarg
                            + docidWithoutRevision);
2488 2075 jones
                    // Get revision
2489 5025 daigle
                    String revision =
2490
                    	DocumentUtil.getRevisionStringFromString(documentId);
2491 5165 daigle
                    logMetacat.info("DBQuery.getZippedPackage - revision from docIdentifier: "
2492 2663 sgarg
                            + revision);
2493 2075 jones
                    // Zip entry string
2494
                    String zipEntryPath = rootName + "/data/";
2495
                    // Create a RemoteDocument object
2496
                    RemoteDocument remoteDoc = new RemoteDocument(
2497
                            docidWithoutRevision, revision, user, passWord,
2498
                            zipEntryPath);
2499
                    // Here we only read data file from remote metacat
2500
                    String docType = remoteDoc.getDocType();
2501
                    if (docType != null) {
2502
                        if (docType.equals("BIN")) {
2503
                            // Put remote document to zip output
2504
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2505
                            // Add String object to htmlDocumentImplList
2506
                            String elementInHtmlList = remoteDoc
2507
                                    .getDocIdWithoutRevsion()
2508 4212 daigle
                                    + PropertyService.getProperty("document.accNumSeparator")
2509 2075 jones
                                    + remoteDoc.getRevision();
2510
                            htmlDocumentImplList.add(elementInHtmlList);
2511
                        }//if
2512
                    }//if
2513 1361 tao
2514 2075 jones
                }//if
2515
                else {
2516
                    //create a docmentImpls object (represent xml doc) base on
2517
                    // the docId
2518
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2519
                    //checking if the user has the permission to read the
2520
                    // documents
2521
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2522
                            .getDocID())) {
2523
                        //if the docImpls is metadata
2524
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2525
                            //add metadata into zip output stream
2526
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2527
                            //add the documentImpl into the vetor which will
2528
                            // be used in html
2529
                            htmlDocumentImplList.add(docImpls);
2530 2043 sgarg
2531 2075 jones
                        }//if
2532
                        else {
2533
                            //it is data file
2534
                            addDataFileToZipOutputStream(docImpls, zOut,
2535
                                    rootName);
2536
                            htmlDocumentImplList.add(docImpls);
2537
                        }//else
2538
                    }//if
2539
                }//else
2540
            }//for
2541 2043 sgarg
2542 2075 jones
            //add html summary file
2543
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2544
                    rootName);
2545
            zOut.finish(); //terminate the zip file
2546
            //dbConn.close();
2547
            return zOut;
2548
        }//else
2549
    }//getZippedPackage()
2550 2043 sgarg
2551 2075 jones
    private class ReturnFieldValue
2552 1361 tao
    {
2553 2043 sgarg
2554 2075 jones
        private String docid = null; //return field value for this docid
2555 2043 sgarg
2556 2075 jones
        private String fieldValue = null;
2557 2043 sgarg
2558 2075 jones
        private String xmlFieldValue = null; //return field value in xml
2559
                                             // format
2560 3635 leinfelder
        private String fieldType = null; //ATTRIBUTE, TEXT...
2561 2075 jones
2562
        public void setDocid(String myDocid)
2563
        {
2564
            docid = myDocid;
2565
        }
2566
2567
        public String getDocid()
2568
        {
2569
            return docid;
2570
        }
2571
2572
        public void setFieldValue(String myValue)
2573
        {
2574
            fieldValue = myValue;
2575
        }
2576
2577
        public String getFieldValue()
2578
        {
2579
            return fieldValue;
2580
        }
2581
2582
        public void setXMLFieldValue(String xml)
2583
        {
2584
            xmlFieldValue = xml;
2585
        }
2586
2587
        public String getXMLFieldValue()
2588
        {
2589
            return xmlFieldValue;
2590
        }
2591 3635 leinfelder
2592
        public void setFieldType(String myType)
2593
        {
2594
            fieldType = myType;
2595
        }
2596 2075 jones
2597 3635 leinfelder
        public String getFieldType()
2598
        {
2599
            return fieldType;
2600
        }
2601
2602 1361 tao
    }
2603 3246 berkley
2604
    /**
2605
     * a class to store one result document consisting of a docid and a document
2606
     */
2607
    private class ResultDocument
2608
    {
2609
      public String docid;
2610
      public String document;
2611
2612
      public ResultDocument(String docid, String document)
2613
      {
2614
        this.docid = docid;
2615
        this.document = document;
2616
      }
2617
    }
2618
2619
    /**
2620
     * a private class to handle a set of resultDocuments
2621
     */
2622
    private class ResultDocumentSet
2623
    {
2624
      private Vector docids;
2625
      private Vector documents;
2626
2627
      public ResultDocumentSet()
2628
      {
2629
        docids = new Vector();
2630
        documents = new Vector();
2631
      }
2632
2633
      /**
2634
       * adds a result document to the set
2635
       */
2636
      public void addResultDocument(ResultDocument rd)
2637
      {
2638
        if(rd.docid == null)
2639 3263 tao
          return;
2640 3246 berkley
        if(rd.document == null)
2641
          rd.document = "";
2642 3349 tao
2643 3263 tao
           docids.addElement(rd.docid);
2644
           documents.addElement(rd.document);
2645 3349 tao
2646 3246 berkley
      }
2647
2648
      /**
2649
       * gets an iterator of docids
2650
       */
2651
      public Iterator getDocids()
2652
      {
2653
        return docids.iterator();
2654
      }
2655
2656
      /**
2657
       * gets an iterator of documents
2658
       */
2659
      public Iterator getDocuments()
2660
      {
2661
        return documents.iterator();
2662
      }
2663
2664
      /**
2665
       * returns the size of the set
2666
       */
2667
      public int size()
2668
      {
2669
        return docids.size();
2670
      }
2671
2672
      /**
2673
       * tests to see if this set contains the given docid
2674
       */
2675 3337 tao
      private boolean containsDocid(String docid)
2676 3246 berkley
      {
2677
        for(int i=0; i<docids.size(); i++)
2678
        {
2679
          String docid0 = (String)docids.elementAt(i);
2680
          if(docid0.trim().equals(docid.trim()))
2681
          {
2682
            return true;
2683
          }
2684
        }
2685
        return false;
2686
      }
2687
2688
      /**
2689
       * removes the element with the given docid
2690
       */
2691
      public String remove(String docid)
2692
      {
2693
        for(int i=0; i<docids.size(); i++)
2694
        {
2695
          String docid0 = (String)docids.elementAt(i);
2696
          if(docid0.trim().equals(docid.trim()))
2697
          {
2698
            String returnDoc = (String)documents.elementAt(i);
2699
            documents.remove(i);
2700
            docids.remove(i);
2701
            return returnDoc;
2702
          }
2703
        }
2704
        return null;
2705
      }
2706
2707
      /**
2708
       * add a result document
2709
       */
2710
      public void put(ResultDocument rd)
2711
      {
2712
        addResultDocument(rd);
2713
      }
2714
2715
      /**
2716
       * add a result document by components
2717
       */
2718
      public void put(String docid, String document)
2719
      {
2720
        addResultDocument(new ResultDocument(docid, document));
2721
      }
2722
2723
      /**
2724
       * get the document part of the result document by docid
2725
       */
2726
      public Object get(String docid)
2727
      {
2728
        for(int i=0; i<docids.size(); i++)
2729
        {
2730
          String docid0 = (String)docids.elementAt(i);
2731
          if(docid0.trim().equals(docid.trim()))
2732
          {
2733
            return documents.elementAt(i);
2734
          }
2735
        }
2736
        return null;
2737
      }
2738
2739
      /**
2740
       * get the document part of the result document by an object
2741
       */
2742
      public Object get(Object o)
2743
      {
2744
        return get((String)o);
2745
      }
2746
2747
      /**
2748
       * get an entire result document by index number
2749
       */
2750
      public ResultDocument get(int index)
2751
      {
2752
        return new ResultDocument((String)docids.elementAt(index),
2753
          (String)documents.elementAt(index));
2754
      }
2755
2756
      /**
2757
       * return a string representation of this object
2758
       */
2759
      public String toString()
2760
      {
2761
        String s = "";
2762
        for(int i=0; i<docids.size(); i++)
2763
        {
2764
          s += (String)docids.elementAt(i) + "\n";
2765
        }
2766
        return s;
2767
      }
2768 3263 tao
      /*
2769
       * Set a new document value for a given docid
2770
       */
2771
      public void set(String docid, String document)
2772
      {
2773
    	   for(int i=0; i<docids.size(); i++)
2774
           {
2775
             String docid0 = (String)docids.elementAt(i);
2776
             if(docid0.trim().equals(docid.trim()))
2777
             {
2778
                 documents.set(i, document);
2779
             }
2780
           }
2781
2782
      }
2783 3246 berkley
    }
2784 155 jones
}