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