Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *
12
 *   '$Author: tao $'
13
 *     '$Date: 2008-02-22 15:16:28 -0800 (Fri, 22 Feb 2008) $'
14
 * '$Revision: 3730 $'
15
 *
16
 * This program is free software; you can redistribute it and/or modify
17
 * it under the terms of the GNU General Public License as published by
18
 * the Free Software Foundation; either version 2 of the License, or
19
 * (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU General Public License
27
 * along with this program; if not, write to the Free Software
28
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29
 */
30

    
31
package edu.ucsb.nceas.metacat;
32

    
33
import java.io.*;
34
import java.util.zip.*;
35
import java.sql.PreparedStatement;
36
import java.sql.ResultSet;
37
import java.sql.SQLException;
38
import java.util.*;
39

    
40
import javax.servlet.ServletOutputStream;
41
import javax.servlet.http.HttpServletResponse;
42
import javax.servlet.http.HttpSession;
43

    
44
import org.apache.log4j.Logger;
45

    
46
import org.w3c.dom.*;
47
import javax.xml.parsers.DocumentBuilderFactory;
48
import org.xml.sax.InputSource;
49
import org.w3c.dom.ls.*;
50

    
51
import edu.ucsb.nceas.morpho.datapackage.Triple;
52
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
53

    
54

    
55
/**
56
 * A Class that searches a relational DB for elements and attributes that have
57
 * free text matches a query string, or structured query matches to a path
58
 * specified node in the XML hierarchy. It returns a result set consisting of
59
 * the document ID for each document that satisfies the query
60
 */
61
public class DBQuery
62
{
63

    
64
    static final int ALL = 1;
65

    
66
    static final int WRITE = 2;
67

    
68
    static final int READ = 4;
69

    
70
    //private Connection conn = null;
71
    private String parserName = null;
72

    
73
    private MetaCatUtil util = new MetaCatUtil();
74

    
75
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
76

    
77
    /** true if the metacat spatial option is installed **/
78
    private final boolean METACAT_SPATIAL = true;
79

    
80
    /** useful if you just want to grab a list of docids. Since the docids can be very long,
81
         it is a vector of vector  **/
82
    Vector docidOverride = new Vector();
83
    
84
    // a hash table serves as query reuslt cache. Key of hashtable
85
    // is a query string and value is result xml string
86
    private static Hashtable queryResultCache = new Hashtable();
87
    
88
    // Capacity of the query result cache
89
    private static final int QUERYRESULTCACHESIZE = Integer.parseInt(MetaCatUtil.getOption("queryresult_cache_size"));
90

    
91
    // Size of page for non paged query
92
    private static final int NONPAGESIZE = 99999999;
93
    /**
94
     * the main routine used to test the DBQuery utility.
95
     * <p>
96
     * Usage: java DBQuery <xmlfile>
97
     *
98
     * @param xmlfile the filename of the xml file containing the query
99
     */
100
    static public void main(String[] args)
101
    {
102

    
103
        if (args.length < 1) {
104
            System.err.println("Wrong number of arguments!!!");
105
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
106
            return;
107
        } else {
108
            try {
109

    
110
                int i = 0;
111
                boolean showRuntime = false;
112
                boolean useXMLIndex = false;
113
                if (args[i].equals("-t")) {
114
                    showRuntime = true;
115
                    i++;
116
                }
117
                if (args[i].equals("-index")) {
118
                    useXMLIndex = true;
119
                    i++;
120
                }
121
                String xmlfile = args[i];
122

    
123
                // Time the request if asked for
124
                double startTime = System.currentTimeMillis();
125

    
126
                // Open a connection to the database
127
                MetaCatUtil util = new MetaCatUtil();
128
                //Connection dbconn = util.openDBConnection();
129

    
130
                double connTime = System.currentTimeMillis();
131

    
132
                // Execute the query
133
                DBQuery queryobj = new DBQuery();
134
                FileReader xml = new FileReader(new File(xmlfile));
135
                Hashtable nodelist = null;
136
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
137

    
138
                // Print the reulting document listing
139
                StringBuffer result = new StringBuffer();
140
                String document = null;
141
                String docid = null;
142
                result.append("<?xml version=\"1.0\"?>\n");
143
                result.append("<resultset>\n");
144

    
145
                if (!showRuntime) {
146
                    Enumeration doclist = nodelist.keys();
147
                    while (doclist.hasMoreElements()) {
148
                        docid = (String) doclist.nextElement();
149
                        document = (String) nodelist.get(docid);
150
                        result.append("  <document>\n    " + document
151
                                + "\n  </document>\n");
152
                    }
153

    
154
                    result.append("</resultset>\n");
155
                }
156
                // Time the request if asked for
157
                double stopTime = System.currentTimeMillis();
158
                double dbOpenTime = (connTime - startTime) / 1000;
159
                double readTime = (stopTime - connTime) / 1000;
160
                double executionTime = (stopTime - startTime) / 1000;
161
                if (showRuntime) {
162
                    System.out.print("  " + executionTime);
163
                    System.out.print("  " + dbOpenTime);
164
                    System.out.print("  " + readTime);
165
                    System.out.print("  " + nodelist.size());
166
                    System.out.println();
167
                }
168
                //System.out.println(result);
169
                //write into a file "result.txt"
170
                if (!showRuntime) {
171
                    File f = new File("./result.txt");
172
                    FileWriter fw = new FileWriter(f);
173
                    BufferedWriter out = new BufferedWriter(fw);
174
                    out.write(result.toString());
175
                    out.flush();
176
                    out.close();
177
                    fw.close();
178
                }
179

    
180
            } catch (Exception e) {
181
                System.err.println("Error in DBQuery.main");
182
                System.err.println(e.getMessage());
183
                e.printStackTrace(System.err);
184
            }
185
        }
186
    }
187

    
188
    /**
189
     * construct an instance of the DBQuery class
190
     *
191
     * <p>
192
     * Generally, one would call the findDocuments() routine after creating an
193
     * instance to specify the search query
194
     * </p>
195
     *
196

    
197
     * @param parserName the fully qualified name of a Java class implementing
198
     *            the org.xml.sax.XMLReader interface
199
     */
200
    public DBQuery()
201
    {
202
        String parserName = MetaCatUtil.getOption("saxparser");
203
        this.parserName = parserName;
204
    }
205

    
206
    /**
207
     * 
208
     * Construct an instance of DBQuery Class
209
     * BUT accept a docid Vector that will supersede
210
     * the query.printSQL() method
211
     *
212
     * If a docid Vector is passed in,
213
     * the docids will be used to create a simple IN query 
214
     * without the multiple subselects of the printSQL() method
215
     *
216
     * Using this constructor, we just check for 
217
     * a docidOverride Vector in the findResultDoclist() method
218
     *
219
     * @param docids List of docids to display in the resultset
220
     */
221
    public DBQuery(Vector docids)
222
    {
223
    	// since the query will be too long to be handled, so we divided the 
224
    	// docids vector into couple vectors.
225
    	int size = (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
226
    	logMetacat.info("The size of select doicds is "+docids.size());
227
    	logMetacat.info("The application result size in metacat.properties is "+size);
228
    	Vector subset = new Vector();
229
    	if (docids != null && docids.size() > size)
230
    	{
231
    		int index = 0;
232
    		for (int i=0; i< docids.size(); i++)
233
    		{
234
    			
235
    			if (index < size)
236
    			{  	
237
    				subset.add(docids.elementAt(i));
238
    				index ++;
239
    			}
240
    			else
241
    			{
242
    				docidOverride.add(subset);
243
    				subset = new Vector();
244
    				subset.add(docids.elementAt(i));
245
    			    index = 1;
246
    			}
247
    		}
248
    		if (!subset.isEmpty())
249
    		{
250
    			docidOverride.add(subset);
251
    		}
252
    		
253
    	}
254
    	else
255
    	{
256
    		this.docidOverride.add(docids);
257
    	}
258
        
259
        String parserName = MetaCatUtil.getOption("saxparser");
260
        this.parserName = parserName;
261
    }
262

    
263
  /**
264
   * Method put the search result set into out printerwriter
265
   * @param resoponse the return response
266
   * @param out the output printer
267
   * @param params the paratermer hashtable
268
   * @param user the user name (it maybe different to the one in param)
269
   * @param groups the group array
270
   * @param sessionid  the sessionid
271
   */
272
  public void findDocuments(HttpServletResponse response,
273
                                       PrintWriter out, Hashtable params,
274
                                       String user, String[] groups,
275
                                       String sessionid)
276
  {
277
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
278
               .booleanValue();
279
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
280

    
281
  }
282

    
283

    
284
    /**
285
     * Method put the search result set into out printerwriter
286
     * @param resoponse the return response
287
     * @param out the output printer
288
     * @param params the paratermer hashtable
289
     * @param user the user name (it maybe different to the one in param)
290
     * @param groups the group array
291
     * @param sessionid  the sessionid
292
     */
293
    public void findDocuments(HttpServletResponse response,
294
                                         PrintWriter out, Hashtable params,
295
                                         String user, String[] groups,
296
                                         String sessionid, boolean useXMLIndex)
297
    {
298
      int pagesize = 0;
299
      int pagestart = 0;
300
      
301
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
302
      {
303
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
304
        String pagestartStr = ((String[])params.get("pagestart"))[0];
305
        if(pagesizeStr != null && pagestartStr != null)
306
        {
307
          pagesize = (new Integer(pagesizeStr)).intValue();
308
          pagestart = (new Integer(pagestartStr)).intValue();
309
        }
310
      }
311
      
312
      // get query and qformat
313
      String xmlquery = ((String[])params.get("query"))[0];
314

    
315
      logMetacat.info("SESSIONID: " + sessionid);
316
      logMetacat.info("xmlquery: " + xmlquery);
317
      String qformat = ((String[])params.get("qformat"))[0];
318
      logMetacat.info("qformat: " + qformat);
319
      // Get the XML query and covert it into a SQL statment
320
      QuerySpecification qspec = null;
321
      if ( xmlquery != null)
322
      {
323
         xmlquery = transformQuery(xmlquery);
324
         try
325
         {
326
           qspec = new QuerySpecification(xmlquery,
327
                                          parserName,
328
                                          MetaCatUtil.getOption("accNumSeparator"));
329
         }
330
         catch (Exception ee)
331
         {
332
           logMetacat.error("error generating QuerySpecification object"
333
                                    +" in DBQuery.findDocuments"
334
                                    + ee.getMessage());
335
         }
336
      }
337

    
338

    
339

    
340
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
341
      {
342
        //xml format
343
        response.setContentType("text/xml");
344
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex, 
345
          pagesize, pagestart, sessionid);
346
      }//if
347
      else
348
      {
349
        //knb format, in this case we will get whole result and sent it out
350
        response.setContentType("text/html");
351
        PrintWriter nonout = null;
352
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
353
                                                groups, useXMLIndex, pagesize, 
354
                                                pagestart, sessionid);
355
        
356
        //transfer the xml to html
357
        try
358
        {
359
         double startHTMLTransform = System.currentTimeMillis()/1000;
360
         DBTransform trans = new DBTransform();
361
         response.setContentType("text/html");
362

    
363
         // if the user is a moderator, then pass a param to the 
364
         // xsl specifying the fact
365
         if(MetaCatUtil.isModerator(user, groups)){
366
        	 params.put("isModerator", new String[] {"true"});
367
         }
368

    
369
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
370
                                 "-//W3C//HTML//EN", qformat, out, params,
371
                                 sessionid);
372
         double endHTMLTransform = System.currentTimeMillis()/1000;
373
          logMetacat.warn("The time to transfrom resultset from xml to html format is "
374
                  		                             +(endHTMLTransform -startHTMLTransform));
375
          MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Transfrom xml to html  "
376
                             +(endHTMLTransform -startHTMLTransform));
377
          MetaCatUtil.writeDebugToDelimiteredFile(" "+(endHTMLTransform -startHTMLTransform), false);
378
        }
379
        catch(Exception e)
380
        {
381
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
382
                                +e.getMessage());
383
         }
384

    
385
      }//else
386

    
387
  }
388
  
389
  /**
390
   * Transforms a hashtable of documents to an xml or html result and sent
391
   * the content to outputstream. Keep going untill hastable is empty. stop it.
392
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
393
   * to xmlquery String
394
   * @param xmlquery
395
   * @param qspec
396
   * @param out
397
   * @param user
398
   * @param groups
399
   * @param useXMLIndex
400
   * @param sessionid
401
   * @return
402
   */
403
    public StringBuffer createResultDocument(String xmlquery,
404
                                              QuerySpecification qspec,
405
                                              PrintWriter out,
406
                                              String user, String[] groups,
407
                                              boolean useXMLIndex)
408
    {
409
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"");
410
    }
411

    
412
  /*
413
   * Transforms a hashtable of documents to an xml or html result and sent
414
   * the content to outputstream. Keep going untill hastable is empty. stop it.
415
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
416
   * to xmlquery String
417
   */
418
  public StringBuffer createResultDocument(String xmlquery,
419
                                            QuerySpecification qspec,
420
                                            PrintWriter out,
421
                                            String user, String[] groups,
422
                                            boolean useXMLIndex, int pagesize,
423
                                            int pagestart, String sessionid)
424
  {
425
    DBConnection dbconn = null;
426
    int serialNumber = -1;
427
    StringBuffer resultset = new StringBuffer();
428

    
429
    //try to get the cached version first    
430
    Hashtable sessionHash = MetaCatServlet.getSessionHash();
431
    HttpSession sess = (HttpSession)sessionHash.get(sessionid);
432

    
433
    
434
    resultset.append("<?xml version=\"1.0\"?>\n");
435
    resultset.append("<resultset>\n");
436
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
437
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
438
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
439
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
440

    
441
    resultset.append("  <query>" + xmlquery + "</query>");
442
    //send out a new query
443
    if (out != null)
444
    {
445
      out.println(resultset.toString());
446
    }
447
    if (qspec != null)
448
    {
449
      try
450
      {
451

    
452
        //checkout the dbconnection
453
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
454
        serialNumber = dbconn.getCheckOutSerialNumber();
455

    
456
        //print out the search result
457
        // search the doc list
458
        Vector givenDocids = new Vector();
459
        StringBuffer resultContent = new StringBuffer();
460
        if (docidOverride == null || docidOverride.size() == 0)
461
        {
462
        	logMetacat.info("Not in map query");
463
        	resultContent = findResultDoclist(qspec, out, user, groups,
464
                    dbconn, useXMLIndex, pagesize, pagestart, 
465
                    sessionid, givenDocids);
466
        }
467
        else
468
        {
469
        	logMetacat.info("In map query");
470
        	// since docid can be too long to be handled. We divide it into several parts
471
        	for (int i= 0; i<docidOverride.size(); i++)
472
        	{
473
        	   logMetacat.info("in loop===== "+i);
474
        		givenDocids = (Vector)docidOverride.elementAt(i);
475
        		StringBuffer subset = findResultDoclist(qspec, out, user, groups,
476
                        dbconn, useXMLIndex, pagesize, pagestart, 
477
                        sessionid, givenDocids);
478
        		resultContent.append(subset);
479
        	}
480
        }
481
           
482
        resultset.append(resultContent);
483
      } //try
484
      catch (IOException ioe)
485
      {
486
        logMetacat.error("IO error in DBQuery.findDocuments:");
487
        logMetacat.error(ioe.getMessage());
488

    
489
      }
490
      catch (SQLException e)
491
      {
492
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
493
                                 + e.getMessage());
494
      }
495
      catch (Exception ee)
496
      {
497
        logMetacat.error("Exception in DBQuery.findDocuments: "
498
                                 + ee.getMessage());
499
        ee.printStackTrace();
500
      }
501
      finally
502
      {
503
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
504
      } //finally
505
    }//if
506
    String closeRestultset = "</resultset>";
507
    resultset.append(closeRestultset);
508
    if (out != null)
509
    {
510
      out.println(closeRestultset);
511
    }
512

    
513
    //default to returning the whole resultset
514
    return resultset;
515
  }//createResultDocuments
516

    
517
    /*
518
     * Find the doc list which match the query
519
     */
520
    private StringBuffer findResultDoclist(QuerySpecification qspec,
521
                                      PrintWriter out,
522
                                      String user, String[]groups,
523
                                      DBConnection dbconn, boolean useXMLIndex,
524
                                      int pagesize, int pagestart, String sessionid, Vector givenDocids)
525
                                      throws Exception
526
    {
527
      StringBuffer resultsetBuffer = new StringBuffer();
528
      String query = null;
529
      int count = 0;
530
      int index = 0;
531
      ResultDocumentSet docListResult = new ResultDocumentSet();
532
      PreparedStatement pstmt = null;
533
      String docid = null;
534
      String docname = null;
535
      String doctype = null;
536
      String createDate = null;
537
      String updateDate = null;
538
      StringBuffer document = null;
539
      boolean lastpage = false;
540
      int rev = 0;
541
      double startTime = 0;
542
      int offset = 1;
543
      double startSelectionTime = System.currentTimeMillis()/1000;
544
      ResultSet rs = null;
545
           
546
   
547
      // this is a hack for offset. in postgresql 7, if the returned docid list is too long,
548
      //the extend query which base on the docid will be too long to be run. So we 
549
      // have to cut them into different parts. Page query don't need it somehow.
550
      if (out == null)
551
      {
552
        // for html page, we put everything into one page
553
        offset =
554
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
555
      }
556
      else
557
      {
558
          offset =
559
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
560
      }
561

    
562
      /*
563
       * Check the docidOverride Vector
564
       * if defined, we bypass the qspec.printSQL() method
565
       * and contruct a simpler query based on a 
566
       * list of docids rather than a bunch of subselects
567
       */
568
      if ( givenDocids == null || givenDocids.size() == 0 ) {
569
          query = qspec.printSQL(useXMLIndex);
570
      } else {
571
          logMetacat.info("*** docid override " + givenDocids.size());
572
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
573
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
574
          for (int i = 0; i < givenDocids.size(); i++) {  
575
              queryBuffer.append("'");
576
              queryBuffer.append( (String)givenDocids.elementAt(i) );
577
              queryBuffer.append("',");
578
          }
579
          // empty string hack 
580
          queryBuffer.append( "'') " );
581
          query = queryBuffer.toString();
582
      } 
583
      String ownerQuery = getOwnerQuery(user);
584
      logMetacat.info("\n\n\n query: " + query);
585
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
586
      // if query is not the owner query, we need to check the permission
587
      // otherwise we don't need (owner has all permission by default)
588
      if (!query.equals(ownerQuery))
589
      {
590
        // set user name and group
591
        qspec.setUserName(user);
592
        qspec.setGroup(groups);
593
        // Get access query
594
        String accessQuery = qspec.getAccessQuery();
595
        if(!query.endsWith("WHERE")){
596
            query = query + accessQuery;
597
        } else {
598
            query = query + accessQuery.substring(4, accessQuery.length());
599
        }
600
        
601
      }
602
      logMetacat.warn("============ final selection query: " + query);
603
      String selectionAndExtendedQuery = null;
604
      // we only get cache for public
605
      if (user != null && user.equalsIgnoreCase("public") 
606
     		 && pagesize == 0 && MetaCatUtil.getOption("query_cache_on").equals("true"))
607
      {
608
    	  selectionAndExtendedQuery = query +qspec.getReturnDocList()+qspec.getReturnFieldList();
609
   	      String cachedResult = getResultXMLFromCache(selectionAndExtendedQuery);
610
   	      logMetacat.debug("The key of query cache is "+selectionAndExtendedQuery);
611
   	      //System.out.println("==========the string from cache is "+cachedResult);
612
   	      if (cachedResult != null)
613
   	      {
614
   	    	logMetacat.info("resutl from cache !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
615
   	    	 if (out != null)
616
   	         {
617
   	             out.println(cachedResult);
618
   	         }
619
   	    	 resultsetBuffer.append(cachedResult);
620
   	    	 return resultsetBuffer;
621
   	      }
622
      }
623
      
624
      startTime = System.currentTimeMillis() / 1000;
625
      pstmt = dbconn.prepareStatement(query);
626
      rs = pstmt.executeQuery();
627

    
628
      double queryExecuteTime = System.currentTimeMillis() / 1000;
629
      logMetacat.warn("Time to execute select docid query is "
630
                    + (queryExecuteTime - startTime));
631
      MetaCatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
632
              + (queryExecuteTime - startTime));
633
      MetaCatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
634

    
635
      boolean tableHasRows = rs.next();
636
      
637
      if(pagesize == 0)
638
      { //this makes sure we get all results if there is no paging
639
        pagesize = NONPAGESIZE;
640
        pagestart = NONPAGESIZE;
641
      } 
642
      
643
      int currentIndex = 0;
644
      while (tableHasRows)
645
      {
646
        logMetacat.info("############getting result: " + currentIndex);
647
        docid = rs.getString(1).trim();
648
        logMetacat.info("############processing: " + docid);
649
        docname = rs.getString(2);
650
        doctype = rs.getString(3);
651
        logMetacat.info("############processing: " + doctype);
652
        createDate = rs.getString(4);
653
        updateDate = rs.getString(5);
654
        rev = rs.getInt(6);
655
        
656
         Vector returndocVec = qspec.getReturnDocList();
657
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
658
        {
659
          logMetacat.info("NOT Back tracing now...");
660
           document = new StringBuffer();
661

    
662
           String completeDocid = docid
663
                            + MetaCatUtil.getOption("accNumSeparator");
664
           completeDocid += rev;
665
           document.append("<docid>").append(completeDocid).append("</docid>");
666
           if (docname != null)
667
           {
668
               document.append("<docname>" + docname + "</docname>");
669
           }
670
           if (doctype != null)
671
           {
672
              document.append("<doctype>" + doctype + "</doctype>");
673
           }
674
           if (createDate != null)
675
           {
676
               document.append("<createdate>" + createDate + "</createdate>");
677
           }
678
           if (updateDate != null)
679
           {
680
             document.append("<updatedate>" + updateDate + "</updatedate>");
681
           }
682
           // Store the document id and the root node id
683
           
684
           docListResult.addResultDocument(
685
             new ResultDocument(docid, (String) document.toString()));
686
           logMetacat.info("$$$$$$$real result: " + docid);
687
           currentIndex++;
688
           count++;
689
        }//else
690
        
691
        // when doclist reached the offset number, send out doc list and empty
692
        // the hash table
693
        if (count == offset && pagesize == NONPAGESIZE)
694
        { //if pagesize is not 0, do this later.
695
          //reset count
696
          //logMetacat.warn("############doing subset cache");
697
          count = 0;
698
          handleSubsetResult(qspec, resultsetBuffer, out, docListResult,
699
                              user, groups,dbconn, useXMLIndex);
700
          //reset docListResult
701
          docListResult = new ResultDocumentSet();
702
        }
703
       
704
       logMetacat.info("currentIndex: " + currentIndex);
705
       logMetacat.info("page comparator: " + (pagesize * pagestart) + pagesize);
706
       if(currentIndex >= ((pagesize * pagestart) + pagesize))
707
       {
708
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
709
         for(int i=pagesize*pagestart; i<docListResult.size(); i++)
710
         {
711
           pagedResultsHash.put(docListResult.get(i));
712
         }
713
         
714
         docListResult = pagedResultsHash;
715
         break;
716
       }
717
       // Advance to the next record in the cursor
718
       tableHasRows = rs.next();
719
       if(!tableHasRows)
720
       {
721
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
722
         //get the last page of information then break
723
         if(pagesize != NONPAGESIZE)
724
         {
725
           for(int i=pagesize*pagestart; i<docListResult.size(); i++)
726
           {
727
             pagedResultsHash.put(docListResult.get(i));
728
           }
729
           docListResult = pagedResultsHash;
730
         }
731
         
732
         lastpage = true;
733
         break;
734
       }
735
     }//while
736
     
737
     rs.close();
738
     pstmt.close();
739
     double docListTime = System.currentTimeMillis() / 1000;
740
     logMetacat.warn("======Total time to get docid list is: "
741
                          + (docListTime - startSelectionTime ));
742
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Total selection: "
743
             + (docListTime - startSelectionTime ));
744
     MetaCatUtil.writeDebugToDelimiteredFile(" "+ (docListTime - startSelectionTime ), false);
745
     //if docListResult is not empty, it need to be sent.
746
     if (docListResult.size() != 0)
747
     {
748
      
749
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
750
                              user, groups,dbconn, useXMLIndex);
751
     }
752

    
753
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
754
     if (out != null)
755
     {
756
         out.println("\n<lastpage>" + lastpage + "</lastpage>\n");
757
     }
758
     
759
     // now we only cached none-paged query and user is public
760
     if (user != null && user.equalsIgnoreCase("public") 
761
    		 && pagesize == NONPAGESIZE && MetaCatUtil.getOption("query_cache_on").equals("true"))
762
     {
763
       //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
764
  	   storeQueryResultIntoCache(selectionAndExtendedQuery, resultsetBuffer.toString());
765
     }
766
          
767
     return resultsetBuffer;
768
    }//findReturnDoclist
769

    
770

    
771
    /*
772
     * Send completed search hashtable(part of reulst)to output stream
773
     * and buffer into a buffer stream
774
     */
775
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
776
                                           StringBuffer resultset,
777
                                           PrintWriter out, ResultDocumentSet partOfDoclist,
778
                                           String user, String[]groups,
779
                                       DBConnection dbconn, boolean useXMLIndex)
780
                                       throws Exception
781
   {
782
     double startReturnField = System.currentTimeMillis()/1000;
783
     // check if there is a record in xml_returnfield
784
     // and get the returnfield_id and usage count
785
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
786
     boolean enterRecords = false;
787

    
788
     // get value of xml_returnfield_count
789
     int count = (new Integer(MetaCatUtil
790
                            .getOption("xml_returnfield_count")))
791
                            .intValue();
792

    
793
     // set enterRecords to true if usage_count is more than the offset
794
     // specified in metacat.properties
795
     if(usage_count > count){
796
         enterRecords = true;
797
     }
798

    
799
     if(returnfield_id < 0){
800
         logMetacat.warn("Error in getting returnfield id from"
801
                                  + "xml_returnfield table");
802
         enterRecords = false;
803
     }
804

    
805
     // get the hashtable containing the docids that already in the
806
     // xml_queryresult table
807
     logMetacat.info("size of partOfDoclist before"
808
                             + " docidsInQueryresultTable(): "
809
                             + partOfDoclist.size());
810
     double startGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
811
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
812
                                                        partOfDoclist, dbconn);
813

    
814
     // remove the keys in queryresultDocList from partOfDoclist
815
     Enumeration _keys = queryresultDocList.keys();
816
     while (_keys.hasMoreElements()){
817
         partOfDoclist.remove((String)_keys.nextElement());
818
     }
819
     double endGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
820
     logMetacat.warn("Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
821
          		               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
822
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
823
               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
824
     MetaCatUtil.writeDebugToDelimiteredFile(" " +
825
             (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable),false);
826
     // backup the keys-elements in partOfDoclist to check later
827
     // if the doc entry is indexed yet
828
     Hashtable partOfDoclistBackup = new Hashtable();
829
     Iterator itt = partOfDoclist.getDocids();
830
     while (itt.hasNext()){
831
       Object key = itt.next();
832
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
833
     }
834

    
835
     logMetacat.info("size of partOfDoclist after"
836
                             + " docidsInQueryresultTable(): "
837
                             + partOfDoclist.size());
838

    
839
     //add return fields for the documents in partOfDoclist
840
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
841
                                        dbconn, useXMLIndex);
842
     double endExtendedQuery = System.currentTimeMillis()/1000;
843
     logMetacat.warn("Get fields from index and node table (Part2 in return fields) "
844
        		                                          + (endExtendedQuery - endGetReturnValueFromQueryresultable));
845
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
846
             + (endExtendedQuery - endGetReturnValueFromQueryresultable));
847
     MetaCatUtil.writeDebugToDelimiteredFile(" "
848
             + (endExtendedQuery - endGetReturnValueFromQueryresultable), false);
849
     //add relationship part part docid list for the documents in partOfDocList
850
     //partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
851

    
852
     double startStoreReturnField = System.currentTimeMillis()/1000;
853
     Iterator keys = partOfDoclist.getDocids();
854
     String key = null;
855
     String element = null;
856
     String query = null;
857
     int offset = (new Integer(MetaCatUtil
858
                               .getOption("queryresult_string_length")))
859
                               .intValue();
860
     while (keys.hasNext())
861
     {
862
         key = (String) keys.next();
863
         element = (String)partOfDoclist.get(key);
864
         
865
	 // check if the enterRecords is true, elements is not null, element's
866
         // length is less than the limit of table column and if the document
867
         // has been indexed already
868
         if(enterRecords && element != null
869
		&& element.length() < offset
870
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
871
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
872
                 + "queryresult_string) VALUES (?, ?, ?)";
873

    
874
             PreparedStatement pstmt = null;
875
             pstmt = dbconn.prepareStatement(query);
876
             pstmt.setInt(1, returnfield_id);
877
             pstmt.setString(2, key);
878
             pstmt.setString(3, element);
879
            
880
             dbconn.increaseUsageCount(1);
881
             try
882
             {
883
            	 pstmt.execute();
884
             }
885
             catch(Exception e)
886
             {
887
            	 logMetacat.warn("couldn't insert the element to xml_queryresult table "+e.getLocalizedMessage());
888
             }
889
             finally
890
             {
891
                pstmt.close();
892
             }
893
         }
894
        
895
         // A string with element
896
         String xmlElement = "  <document>" + element + "</document>";
897

    
898
         //send single element to output
899
         if (out != null)
900
         {
901
             out.println(xmlElement);
902
         }
903
         resultset.append(xmlElement);
904
     }//while
905
     
906
     double endStoreReturnField = System.currentTimeMillis()/1000;
907
     logMetacat.warn("Time to store new return fields into xml_queryresult table (Part4 in return fields) "
908
                   + (endStoreReturnField -startStoreReturnField));
909
     MetaCatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
910
             + (endStoreReturnField -startStoreReturnField));
911
     MetaCatUtil.writeDebugToDelimiteredFile(" "
912
             + (endStoreReturnField -startStoreReturnField), false);
913
     
914
     Enumeration keysE = queryresultDocList.keys();
915
     while (keysE.hasMoreElements())
916
     {
917
         key = (String) keysE.nextElement();
918
         element = (String)queryresultDocList.get(key);
919
         // A string with element
920
         String xmlElement = "  <document>" + element + "</document>";
921
         //send single element to output
922
         if (out != null)
923
         {
924
             out.println(xmlElement);
925
         }
926
         resultset.append(xmlElement);
927
     }//while
928
     double returnFieldTime = System.currentTimeMillis() / 1000;
929
     logMetacat.warn("======Total time to get return fields is: "
930
                           + (returnFieldTime - startReturnField));
931
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------"+
932
    		 "Total to get return fields  "
933
                                   + (returnFieldTime - startReturnField));
934
     MetaCatUtil.writeDebugToDelimiteredFile(" "+ (returnFieldTime - startReturnField), false);
935
     return resultset;
936
 }
937

    
938
   /**
939
    * Get the docids already in xml_queryresult table and corresponding
940
    * queryresultstring as a hashtable
941
    */
942
   private Hashtable docidsInQueryresultTable(int returnfield_id,
943
                                              ResultDocumentSet partOfDoclist,
944
                                              DBConnection dbconn){
945

    
946
         Hashtable returnValue = new Hashtable();
947
         PreparedStatement pstmt = null;
948
         ResultSet rs = null;
949

    
950
         // get partOfDoclist as string for the query
951
         Iterator keylist = partOfDoclist.getDocids();
952
         StringBuffer doclist = new StringBuffer();
953
         while (keylist.hasNext())
954
         {
955
             doclist.append("'");
956
             doclist.append((String) keylist.next());
957
             doclist.append("',");
958
         }//while
959

    
960

    
961
         if (doclist.length() > 0)
962
         {
963
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
964

    
965
             // the query to find out docids from xml_queryresult
966
             String query = "select docid, queryresult_string from "
967
                          + "xml_queryresult where returnfield_id = " +
968
                          returnfield_id +" and docid in ("+ doclist + ")";
969
             logMetacat.info("Query to get docids from xml_queryresult:"
970
                                      + query);
971

    
972
             try {
973
                 // prepare and execute the query
974
                 pstmt = dbconn.prepareStatement(query);
975
                 dbconn.increaseUsageCount(1);
976
                 pstmt.execute();
977
                 rs = pstmt.getResultSet();
978
                 boolean tableHasRows = rs.next();
979
                 while (tableHasRows) {
980
                     // store the returned results in the returnValue hashtable
981
                     String key = rs.getString(1);
982
                     String element = rs.getString(2);
983

    
984
                     if(element != null){
985
                         returnValue.put(key, element);
986
                     } else {
987
                         logMetacat.info("Null elment found ("
988
                         + "DBQuery.docidsInQueryresultTable)");
989
                     }
990
                     tableHasRows = rs.next();
991
                 }
992
                 rs.close();
993
                 pstmt.close();
994
             } catch (Exception e){
995
                 logMetacat.error("Error getting docids from "
996
                                          + "queryresult in "
997
                                          + "DBQuery.docidsInQueryresultTable: "
998
                                          + e.getMessage());
999
              }
1000
         }
1001
         return returnValue;
1002
     }
1003

    
1004

    
1005
   /**
1006
    * Method to get id from xml_returnfield table
1007
    * for a given query specification
1008
    */
1009
   private int returnfield_id;
1010
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1011
                                           DBConnection dbconn){
1012
       int id = -1;
1013
       int count = 1;
1014
       PreparedStatement pstmt = null;
1015
       ResultSet rs = null;
1016
       String returnfield = qspec.getSortedReturnFieldString();
1017

    
1018
       // query for finding the id from xml_returnfield
1019
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1020
            + "WHERE returnfield_string LIKE ?";
1021
       logMetacat.info("ReturnField Query:" + query);
1022

    
1023
       try {
1024
           // prepare and run the query
1025
           pstmt = dbconn.prepareStatement(query);
1026
           pstmt.setString(1,returnfield);
1027
           dbconn.increaseUsageCount(1);
1028
           pstmt.execute();
1029
           rs = pstmt.getResultSet();
1030
           boolean tableHasRows = rs.next();
1031

    
1032
           // if record found then increase the usage count
1033
           // else insert a new record and get the id of the new record
1034
           if(tableHasRows){
1035
               // get the id
1036
               id = rs.getInt(1);
1037
               count = rs.getInt(2) + 1;
1038
               rs.close();
1039
               pstmt.close();
1040

    
1041
               // increase the usage count
1042
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1043
                   + "' WHERE returnfield_id ='"+ id +"'";
1044
               logMetacat.info("ReturnField Table Update:"+ query);
1045

    
1046
               pstmt = dbconn.prepareStatement(query);
1047
               dbconn.increaseUsageCount(1);
1048
               pstmt.execute();
1049
               pstmt.close();
1050

    
1051
           } else {
1052
               rs.close();
1053
               pstmt.close();
1054

    
1055
               // insert a new record
1056
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1057
                   + "VALUES (?, '1')";
1058
               logMetacat.info("ReturnField Table Insert:"+ query);
1059
               pstmt = dbconn.prepareStatement(query);
1060
               pstmt.setString(1, returnfield);
1061
               dbconn.increaseUsageCount(1);
1062
               pstmt.execute();
1063
               pstmt.close();
1064

    
1065
               // get the id of the new record
1066
               query = "SELECT returnfield_id FROM xml_returnfield "
1067
                   + "WHERE returnfield_string LIKE ?";
1068
               logMetacat.info("ReturnField query after Insert:" + query);
1069
               pstmt = dbconn.prepareStatement(query);
1070
               pstmt.setString(1, returnfield);
1071

    
1072
               dbconn.increaseUsageCount(1);
1073
               pstmt.execute();
1074
               rs = pstmt.getResultSet();
1075
               if(rs.next()){
1076
                   id = rs.getInt(1);
1077
               } else {
1078
                   id = -1;
1079
               }
1080
               rs.close();
1081
               pstmt.close();
1082
           }
1083

    
1084
       } catch (Exception e){
1085
           logMetacat.error("Error getting id from xml_returnfield in "
1086
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1087
                                     + e.getMessage());
1088
           id = -1;
1089
       }
1090

    
1091
       returnfield_id = id;
1092
       return count;
1093
   }
1094

    
1095

    
1096
    /*
1097
     * A method to add return field to return doclist hash table
1098
     */
1099
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1100
                                      QuerySpecification qspec,
1101
                                      String user, String[]groups,
1102
                                      DBConnection dbconn, boolean useXMLIndex )
1103
                                      throws Exception
1104
    {
1105
      PreparedStatement pstmt = null;
1106
      ResultSet rs = null;
1107
      String docid = null;
1108
      String fieldname = null;
1109
      String fieldtype = null;
1110
      String fielddata = null;
1111
      String relation = null;
1112

    
1113
      if (qspec.containsExtendedSQL())
1114
      {
1115
        qspec.setUserName(user);
1116
        qspec.setGroup(groups);
1117
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1118
        Vector results = new Vector();
1119
        Iterator keylist = docListResult.getDocids();
1120
        StringBuffer doclist = new StringBuffer();
1121
        Vector parentidList = new Vector();
1122
        Hashtable returnFieldValue = new Hashtable();
1123
        while (keylist.hasNext())
1124
        {
1125
          doclist.append("'");
1126
          doclist.append((String) keylist.next());
1127
          doclist.append("',");
1128
        }
1129
        if (doclist.length() > 0)
1130
        {
1131
          Hashtable controlPairs = new Hashtable();
1132
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1133
          boolean tableHasRows = false;
1134
        
1135

    
1136
           String extendedQuery =
1137
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex);
1138
           logMetacat.info("Extended query: " + extendedQuery);
1139

    
1140
           if(extendedQuery != null){
1141
        	   double extendedQueryStart = System.currentTimeMillis() / 1000;
1142
               pstmt = dbconn.prepareStatement(extendedQuery);
1143
               //increase dbconnection usage count
1144
               dbconn.increaseUsageCount(1);
1145
               pstmt.execute();
1146
               rs = pstmt.getResultSet();
1147
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
1148
               logMetacat.warn(
1149
                   "Time to execute extended query: "
1150
                   + (extendedQueryEnd - extendedQueryStart));
1151
               MetaCatUtil.writeDebugToFile(
1152
                       "Execute extended query "
1153
                       + (extendedQueryEnd - extendedQueryStart));
1154
               MetaCatUtil.writeDebugToDelimiteredFile(" "+ (extendedQueryEnd - extendedQueryStart), false);
1155
               tableHasRows = rs.next();
1156
               while (tableHasRows) {
1157
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1158
                   docid = rs.getString(1).trim();
1159
                   fieldname = rs.getString(2);
1160
                   fielddata = rs.getString(3);
1161
                   fielddata = MetaCatUtil.normalize(fielddata);
1162
                   String parentId = rs.getString(4);
1163
                   fieldtype = rs.getString(5);
1164
                   StringBuffer value = new StringBuffer();
1165

    
1166
                   //handle case when usexmlindex is true differently
1167
                   //at one point merging the nodedata (for large text elements) was 
1168
                   //deemed unnecessary - but now it is needed.  but not for attribute nodes
1169
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1170
                	   //merge node data only for non-ATTRIBUTEs
1171
                	   if (fieldtype != null && !fieldtype.equals("ATTRIBUTE")) {
1172
	                	   //try merging the data
1173
	                	   ReturnFieldValue existingRFV =
1174
	                		   getArrayValue(parentidList, parentId);
1175
	                	   if (existingRFV != null) {
1176
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1177
	                	   }
1178
                	   }
1179
                       value.append("<param name=\"");
1180
                       value.append(fieldname);
1181
                       value.append("\">");
1182
                       value.append(fielddata);
1183
                       value.append("</param>");
1184
                       //set returnvalue
1185
                       returnValue.setDocid(docid);
1186
                       returnValue.setFieldValue(fielddata);
1187
                       returnValue.setFieldType(fieldtype);
1188
                       returnValue.setXMLFieldValue(value.toString());
1189
                       // Store it in hastable
1190
                       putInArray(parentidList, parentId, returnValue);
1191
                   }
1192
                   else {
1193
                       // need to merge nodedata if they have same parent id and
1194
                       // node type is text
1195
                       fielddata = (String) ( (ReturnFieldValue)
1196
                                             getArrayValue(
1197
                           parentidList, parentId)).getFieldValue()
1198
                           + fielddata;
1199
                       value.append("<param name=\"");
1200
                       value.append(fieldname);
1201
                       value.append("\">");
1202
                       value.append(fielddata);
1203
                       value.append("</param>");
1204
                       returnValue.setDocid(docid);
1205
                       returnValue.setFieldValue(fielddata);
1206
                       returnValue.setFieldType(fieldtype);
1207
                       returnValue.setXMLFieldValue(value.toString());
1208
                       // remove the old return value from paretnidList
1209
                       parentidList.remove(parentId);
1210
                       // store the new return value in parentidlit
1211
                       putInArray(parentidList, parentId, returnValue);
1212
                   }
1213
                   tableHasRows = rs.next();
1214
               } //while
1215
               rs.close();
1216
               pstmt.close();
1217

    
1218
               // put the merger node data info into doclistReult
1219
               Enumeration xmlFieldValue = (getElements(parentidList)).
1220
                   elements();
1221
               while (xmlFieldValue.hasMoreElements()) {
1222
                   ReturnFieldValue object =
1223
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1224
                   docid = object.getDocid();
1225
                   if (docListResult.containsDocid(docid)) {
1226
                       String removedelement = (String) docListResult.
1227
                           remove(docid);
1228
                       docListResult.
1229
                           addResultDocument(new ResultDocument(docid,
1230
                               removedelement + object.getXMLFieldValue()));
1231
                   }
1232
                   else {
1233
                       docListResult.addResultDocument(
1234
                         new ResultDocument(docid, object.getXMLFieldValue()));
1235
                   }
1236
               } //while
1237
               double docListResultEnd = System.currentTimeMillis() / 1000;
1238
               logMetacat.warn(
1239
                   "Time to prepare ResultDocumentSet after"
1240
                   + " execute extended query: "
1241
                   + (docListResultEnd - extendedQueryEnd));
1242
           }
1243

    
1244
         
1245
           
1246
           
1247
       }//if doclist lenght is great than zero
1248

    
1249
     }//if has extended query
1250

    
1251
      return docListResult;
1252
    }//addReturnfield
1253

    
1254
  
1255
  /**
1256
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1257
   * string as a param instead of a hashtable.
1258
   *
1259
   * @param xmlquery a string representing a query.
1260
   */
1261
   private  String transformQuery(String xmlquery)
1262
   {
1263
     xmlquery = xmlquery.trim();
1264
     int index = xmlquery.indexOf("?>");
1265
     if (index != -1)
1266
     {
1267
       return xmlquery.substring(index + 2, xmlquery.length());
1268
     }
1269
     else
1270
     {
1271
       return xmlquery;
1272
     }
1273
   }
1274
   
1275
   /*
1276
    * Method to store query string and result xml string into query result
1277
    * cache. If the size alreay reache the limitation, the cache will be
1278
    * cleared first, then store them.
1279
    */
1280
   private void storeQueryResultIntoCache(String query, String resultXML)
1281
   {
1282
	   synchronized (queryResultCache)
1283
	   {
1284
		   if (queryResultCache.size() >= QUERYRESULTCACHESIZE)
1285
		   {
1286
			   queryResultCache.clear();
1287
		   }
1288
		   queryResultCache.put(query, resultXML);
1289
		   
1290
	   }
1291
   }
1292
   
1293
   /*
1294
    * Method to get result xml string from query result cache. 
1295
    * Note: the returned string can be null.
1296
    */
1297
   private String getResultXMLFromCache(String query)
1298
   {
1299
	   String resultSet = null;
1300
	   synchronized (queryResultCache)
1301
	   {
1302
          try
1303
          {
1304
        	 logMetacat.info("Get query from cache ===");
1305
		     resultSet = (String)queryResultCache.get(query);
1306
		   
1307
          }
1308
          catch (Exception e)
1309
          {
1310
        	  resultSet = null;
1311
          }
1312
		   
1313
	   }
1314
	   return resultSet;
1315
   }
1316
   
1317
   /**
1318
    * Method to clear the query result cache.
1319
    */
1320
   public static void clearQueryResultCache()
1321
   {
1322
	   synchronized (queryResultCache)
1323
	   {
1324
		   queryResultCache.clear();
1325
	   }
1326
   }
1327

    
1328

    
1329
    /*
1330
     * A method to search if Vector contains a particular key string
1331
     */
1332
    private boolean containsKey(Vector parentidList, String parentId)
1333
    {
1334

    
1335
        Vector tempVector = null;
1336

    
1337
        for (int count = 0; count < parentidList.size(); count++) {
1338
            tempVector = (Vector) parentidList.get(count);
1339
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1340
        }
1341
        return false;
1342
    }
1343
    
1344
    /*
1345
     * A method to put key and value in Vector
1346
     */
1347
    private void putInArray(Vector parentidList, String key,
1348
            ReturnFieldValue value)
1349
    {
1350

    
1351
        Vector tempVector = null;
1352
        //only filter if the field type is NOT an attribute (say, for text)
1353
        String fieldType = value.getFieldType();
1354
        if (fieldType != null && !fieldType.equals("ATTRIBUTE")) {
1355
        
1356
	        for (int count = 0; count < parentidList.size(); count++) {
1357
	            tempVector = (Vector) parentidList.get(count);
1358
	
1359
	            if (key.compareTo((String) tempVector.get(0)) == 0) {
1360
	                tempVector.remove(1);
1361
	                tempVector.add(1, value);
1362
	                return;
1363
	            }
1364
	        }
1365
        }
1366

    
1367
        tempVector = new Vector();
1368
        tempVector.add(0, key);
1369
        tempVector.add(1, value);
1370
        parentidList.add(tempVector);
1371
        return;
1372
    }
1373

    
1374
    /*
1375
     * A method to get value in Vector given a key
1376
     */
1377
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1378
    {
1379

    
1380
        Vector tempVector = null;
1381

    
1382
        for (int count = 0; count < parentidList.size(); count++) {
1383
            tempVector = (Vector) parentidList.get(count);
1384

    
1385
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1386
                    .get(1); }
1387
        }
1388
        return null;
1389
    }
1390

    
1391
    /*
1392
     * A method to get enumeration of all values in Vector
1393
     */
1394
    private Vector getElements(Vector parentidList)
1395
    {
1396
        Vector enumVector = new Vector();
1397
        Vector tempVector = null;
1398

    
1399
        for (int count = 0; count < parentidList.size(); count++) {
1400
            tempVector = (Vector) parentidList.get(count);
1401

    
1402
            enumVector.add(tempVector.get(1));
1403
        }
1404
        return enumVector;
1405
    }
1406

    
1407
  
1408

    
1409
    /*
1410
     * A method to create a query to get owner's docid list
1411
     */
1412
    private String getOwnerQuery(String owner)
1413
    {
1414
        if (owner != null) {
1415
            owner = owner.toLowerCase();
1416
        }
1417
        StringBuffer self = new StringBuffer();
1418

    
1419
        self.append("SELECT docid,docname,doctype,");
1420
        self.append("date_created, date_updated, rev ");
1421
        self.append("FROM xml_documents WHERE docid IN (");
1422
        self.append("(");
1423
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1424
        self.append("nodedata LIKE '%%%' ");
1425
        self.append(") \n");
1426
        self.append(") ");
1427
        self.append(" AND (");
1428
        self.append(" lower(user_owner) = '" + owner + "'");
1429
        self.append(") ");
1430
        return self.toString();
1431
    }
1432

    
1433
    /**
1434
     * format a structured query as an XML document that conforms to the
1435
     * pathquery.dtd and is appropriate for submission to the DBQuery
1436
     * structured query engine
1437
     *
1438
     * @param params The list of parameters that should be included in the
1439
     *            query
1440
     */
1441
    public static String createSQuery(Hashtable params)
1442
    {
1443
        StringBuffer query = new StringBuffer();
1444
        Enumeration elements;
1445
        Enumeration keys;
1446
        String filterDoctype = null;
1447
        String casesensitive = null;
1448
        String searchmode = null;
1449
        Object nextkey;
1450
        Object nextelement;
1451
        //add the xml headers
1452
        query.append("<?xml version=\"1.0\"?>\n");
1453
        query.append("<pathquery version=\"1.2\">\n");
1454

    
1455

    
1456

    
1457
        if (params.containsKey("meta_file_id")) {
1458
            query.append("<meta_file_id>");
1459
            query.append(((String[]) params.get("meta_file_id"))[0]);
1460
            query.append("</meta_file_id>");
1461
        }
1462

    
1463
        if (params.containsKey("returndoctype")) {
1464
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1465
            for (int i = 0; i < returnDoctypes.length; i++) {
1466
                String doctype = (String) returnDoctypes[i];
1467

    
1468
                if (!doctype.equals("any") && !doctype.equals("ANY")
1469
                        && !doctype.equals("")) {
1470
                    query.append("<returndoctype>").append(doctype);
1471
                    query.append("</returndoctype>");
1472
                }
1473
            }
1474
        }
1475

    
1476
        if (params.containsKey("filterdoctype")) {
1477
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1478
            for (int i = 0; i < filterDoctypes.length; i++) {
1479
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1480
                query.append("</filterdoctype>");
1481
            }
1482
        }
1483

    
1484
        if (params.containsKey("returnfield")) {
1485
            String[] returnfield = ((String[]) params.get("returnfield"));
1486
            for (int i = 0; i < returnfield.length; i++) {
1487
                query.append("<returnfield>").append(returnfield[i]);
1488
                query.append("</returnfield>");
1489
            }
1490
        }
1491

    
1492
        if (params.containsKey("owner")) {
1493
            String[] owner = ((String[]) params.get("owner"));
1494
            for (int i = 0; i < owner.length; i++) {
1495
                query.append("<owner>").append(owner[i]);
1496
                query.append("</owner>");
1497
            }
1498
        }
1499

    
1500
        if (params.containsKey("site")) {
1501
            String[] site = ((String[]) params.get("site"));
1502
            for (int i = 0; i < site.length; i++) {
1503
                query.append("<site>").append(site[i]);
1504
                query.append("</site>");
1505
            }
1506
        }
1507

    
1508
        //allows the dynamic switching of boolean operators
1509
        if (params.containsKey("operator")) {
1510
            query.append("<querygroup operator=\""
1511
                    + ((String[]) params.get("operator"))[0] + "\">");
1512
        } else { //the default operator is UNION
1513
            query.append("<querygroup operator=\"UNION\">");
1514
        }
1515

    
1516
        if (params.containsKey("casesensitive")) {
1517
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1518
        } else {
1519
            casesensitive = "false";
1520
        }
1521

    
1522
        if (params.containsKey("searchmode")) {
1523
            searchmode = ((String[]) params.get("searchmode"))[0];
1524
        } else {
1525
            searchmode = "contains";
1526
        }
1527

    
1528
        //anyfield is a special case because it does a
1529
        //free text search. It does not have a <pathexpr>
1530
        //tag. This allows for a free text search within the structured
1531
        //query. This is useful if the INTERSECT operator is used.
1532
        if (params.containsKey("anyfield")) {
1533
            String[] anyfield = ((String[]) params.get("anyfield"));
1534
            //allow for more than one value for anyfield
1535
            for (int i = 0; i < anyfield.length; i++) {
1536
                if (!anyfield[i].equals("")) {
1537
                    query.append("<queryterm casesensitive=\"" + casesensitive
1538
                            + "\" " + "searchmode=\"" + searchmode
1539
                            + "\"><value>" + anyfield[i]
1540
                            + "</value></queryterm>");
1541
                }
1542
            }
1543
        }
1544

    
1545
        //this while loop finds the rest of the parameters
1546
        //and attempts to query for the field specified
1547
        //by the parameter.
1548
        elements = params.elements();
1549
        keys = params.keys();
1550
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1551
            nextkey = keys.nextElement();
1552
            nextelement = elements.nextElement();
1553

    
1554
            //make sure we aren't querying for any of these
1555
            //parameters since the are already in the query
1556
            //in one form or another.
1557
            Vector ignoredParams = new Vector();
1558
            ignoredParams.add("returndoctype");
1559
            ignoredParams.add("filterdoctype");
1560
            ignoredParams.add("action");
1561
            ignoredParams.add("qformat");
1562
            ignoredParams.add("anyfield");
1563
            ignoredParams.add("returnfield");
1564
            ignoredParams.add("owner");
1565
            ignoredParams.add("site");
1566
            ignoredParams.add("operator");
1567
            ignoredParams.add("sessionid");
1568
            ignoredParams.add("pagesize");
1569
            ignoredParams.add("pagestart");
1570

    
1571
            // Also ignore parameters listed in the properties file
1572
            // so that they can be passed through to stylesheets
1573
            String paramsToIgnore = MetaCatUtil
1574
                    .getOption("query.ignored.params");
1575
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1576
            while (st.hasMoreTokens()) {
1577
                ignoredParams.add(st.nextToken());
1578
            }
1579
            if (!ignoredParams.contains(nextkey.toString())) {
1580
                //allow for more than value per field name
1581
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1582
                    if (!((String[]) nextelement)[i].equals("")) {
1583
                        query.append("<queryterm casesensitive=\""
1584
                                + casesensitive + "\" " + "searchmode=\""
1585
                                + searchmode + "\">" + "<value>" +
1586
                                //add the query value
1587
                                ((String[]) nextelement)[i]
1588
                                + "</value><pathexpr>" +
1589
                                //add the path to query by
1590
                                nextkey.toString() + "</pathexpr></queryterm>");
1591
                    }
1592
                }
1593
            }
1594
        }
1595
        query.append("</querygroup></pathquery>");
1596
        //append on the end of the xml and return the result as a string
1597
        return query.toString();
1598
    }
1599

    
1600
    /**
1601
     * format a simple free-text value query as an XML document that conforms
1602
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1603
     * structured query engine
1604
     *
1605
     * @param value the text string to search for in the xml catalog
1606
     * @param doctype the type of documents to include in the result set -- use
1607
     *            "any" or "ANY" for unfiltered result sets
1608
     */
1609
    public static String createQuery(String value, String doctype)
1610
    {
1611
        StringBuffer xmlquery = new StringBuffer();
1612
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1613
        xmlquery.append("<pathquery version=\"1.0\">");
1614

    
1615
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1616
            xmlquery.append("<returndoctype>");
1617
            xmlquery.append(doctype).append("</returndoctype>");
1618
        }
1619

    
1620
        xmlquery.append("<querygroup operator=\"UNION\">");
1621
        //chad added - 8/14
1622
        //the if statement allows a query to gracefully handle a null
1623
        //query. Without this if a nullpointerException is thrown.
1624
        if (!value.equals("")) {
1625
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1626
            xmlquery.append("searchmode=\"contains\">");
1627
            xmlquery.append("<value>").append(value).append("</value>");
1628
            xmlquery.append("</queryterm>");
1629
        }
1630
        xmlquery.append("</querygroup>");
1631
        xmlquery.append("</pathquery>");
1632

    
1633
        return (xmlquery.toString());
1634
    }
1635

    
1636
    /**
1637
     * format a simple free-text value query as an XML document that conforms
1638
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1639
     * structured query engine
1640
     *
1641
     * @param value the text string to search for in the xml catalog
1642
     */
1643
    public static String createQuery(String value)
1644
    {
1645
        return createQuery(value, "any");
1646
    }
1647

    
1648
    /**
1649
     * Check for "READ" permission on @docid for @user and/or @group from DB
1650
     * connection
1651
     */
1652
    private boolean hasPermission(String user, String[] groups, String docid)
1653
            throws SQLException, Exception
1654
    {
1655
        // Check for READ permission on @docid for @user and/or @groups
1656
        PermissionController controller = new PermissionController(docid);
1657
        return controller.hasPermission(user, groups,
1658
                AccessControlInterface.READSTRING);
1659
    }
1660

    
1661
    /**
1662
     * Get all docIds list for a data packadge
1663
     *
1664
     * @param dataPackageDocid, the string in docId field of xml_relation table
1665
     */
1666
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1667
    {
1668
        DBConnection dbConn = null;
1669
        int serialNumber = -1;
1670
        Vector docIdList = new Vector();//return value
1671
        PreparedStatement pStmt = null;
1672
        ResultSet rs = null;
1673
        String docIdInSubjectField = null;
1674
        String docIdInObjectField = null;
1675

    
1676
        // Check the parameter
1677
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1678

    
1679
        //the query stirng
1680
        String query = "SELECT subject, object from xml_relation where docId = ?";
1681
        try {
1682
            dbConn = DBConnectionPool
1683
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1684
            serialNumber = dbConn.getCheckOutSerialNumber();
1685
            pStmt = dbConn.prepareStatement(query);
1686
            //bind the value to query
1687
            pStmt.setString(1, dataPackageDocid);
1688

    
1689
            //excute the query
1690
            pStmt.execute();
1691
            //get the result set
1692
            rs = pStmt.getResultSet();
1693
            //process the result
1694
            while (rs.next()) {
1695
                //In order to get the whole docIds in a data packadge,
1696
                //we need to put the docIds of subject and object field in
1697
                // xml_relation
1698
                //into the return vector
1699
                docIdInSubjectField = rs.getString(1);//the result docId in
1700
                                                      // subject field
1701
                docIdInObjectField = rs.getString(2);//the result docId in
1702
                                                     // object field
1703

    
1704
                //don't put the duplicate docId into the vector
1705
                if (!docIdList.contains(docIdInSubjectField)) {
1706
                    docIdList.add(docIdInSubjectField);
1707
                }
1708

    
1709
                //don't put the duplicate docId into the vector
1710
                if (!docIdList.contains(docIdInObjectField)) {
1711
                    docIdList.add(docIdInObjectField);
1712
                }
1713
            }//while
1714
            //close the pStmt
1715
            pStmt.close();
1716
        }//try
1717
        catch (SQLException e) {
1718
            logMetacat.error("Error in getDocidListForDataPackage: "
1719
                    + e.getMessage());
1720
        }//catch
1721
        finally {
1722
            try {
1723
                pStmt.close();
1724
            }//try
1725
            catch (SQLException ee) {
1726
                logMetacat.error(
1727
                        "Error in getDocidListForDataPackage: "
1728
                                + ee.getMessage());
1729
            }//catch
1730
            finally {
1731
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1732
            }//fianlly
1733
        }//finally
1734
        return docIdList;
1735
    }//getCurrentDocidListForDataPackadge()
1736

    
1737
    /**
1738
     * Get all docIds list for a data packadge
1739
     *
1740
     * @param dataPackageDocid, the string in docId field of xml_relation table
1741
     */
1742
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1743
    {
1744

    
1745
        Vector docIdList = new Vector();//return value
1746
        Vector tripleList = null;
1747
        String xml = null;
1748

    
1749
        // Check the parameter
1750
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1751

    
1752
        try {
1753
            //initial a documentImpl object
1754
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1755
            //transfer to documentImpl object to string
1756
            xml = packageDocument.toString();
1757

    
1758
            //create a tripcollection object
1759
            TripleCollection tripleForPackage = new TripleCollection(
1760
                    new StringReader(xml));
1761
            //get the vetor of triples
1762
            tripleList = tripleForPackage.getCollection();
1763

    
1764
            for (int i = 0; i < tripleList.size(); i++) {
1765
                //put subject docid into docIdlist without duplicate
1766
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1767
                        .getSubject())) {
1768
                    //put subject docid into docIdlist
1769
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1770
                }
1771
                //put object docid into docIdlist without duplicate
1772
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1773
                        .getObject())) {
1774
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1775
                }
1776
            }//for
1777
        }//try
1778
        catch (Exception e) {
1779
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1780
                    + e.getMessage());
1781
        }//catch
1782

    
1783
        // return result
1784
        return docIdList;
1785
    }//getDocidListForPackageInXMLRevisions()
1786

    
1787
    /**
1788
     * Check if the docId is a data packadge id. If the id is a data packadage
1789
     * id, it should be store in the docId fields in xml_relation table. So we
1790
     * can use a query to get the entries which the docId equals the given
1791
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1792
     * it is.
1793
     *
1794
     * @param docId, the id need to be checked
1795
     */
1796
    private boolean isDataPackageId(String docId)
1797
    {
1798
        boolean result = false;
1799
        PreparedStatement pStmt = null;
1800
        ResultSet rs = null;
1801
        String query = "SELECT docId from xml_relation where docId = ?";
1802
        DBConnection dbConn = null;
1803
        int serialNumber = -1;
1804
        try {
1805
            dbConn = DBConnectionPool
1806
                    .getDBConnection("DBQuery.isDataPackageId");
1807
            serialNumber = dbConn.getCheckOutSerialNumber();
1808
            pStmt = dbConn.prepareStatement(query);
1809
            //bind the value to query
1810
            pStmt.setString(1, docId);
1811
            //execute the query
1812
            pStmt.execute();
1813
            rs = pStmt.getResultSet();
1814
            //process the result
1815
            if (rs.next()) //There are some records for the id in docId fields
1816
            {
1817
                result = true;//It is a data packadge id
1818
            }
1819
            pStmt.close();
1820
        }//try
1821
        catch (SQLException e) {
1822
            logMetacat.error("Error in isDataPackageId: "
1823
                    + e.getMessage());
1824
        } finally {
1825
            try {
1826
                pStmt.close();
1827
            }//try
1828
            catch (SQLException ee) {
1829
                logMetacat.error("Error in isDataPackageId: "
1830
                        + ee.getMessage());
1831
            }//catch
1832
            finally {
1833
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1834
            }//finally
1835
        }//finally
1836
        return result;
1837
    }//isDataPackageId()
1838

    
1839
    /**
1840
     * Check if the user has the permission to export data package
1841
     *
1842
     * @param conn, the connection
1843
     * @param docId, the id need to be checked
1844
     * @param user, the name of user
1845
     * @param groups, the user's group
1846
     */
1847
    private boolean hasPermissionToExportPackage(String docId, String user,
1848
            String[] groups) throws Exception
1849
    {
1850
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1851
        return DocumentImpl.hasReadPermission(user, groups, docId);
1852
    }
1853

    
1854
    /**
1855
     * Get the current Rev for a docid in xml_documents table
1856
     *
1857
     * @param docId, the id need to get version numb If the return value is -5,
1858
     *            means no value in rev field for this docid
1859
     */
1860
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1861
            throws SQLException
1862
    {
1863
        int rev = -5;
1864
        PreparedStatement pStmt = null;
1865
        ResultSet rs = null;
1866
        String query = "SELECT rev from xml_documents where docId = ?";
1867
        DBConnection dbConn = null;
1868
        int serialNumber = -1;
1869
        try {
1870
            dbConn = DBConnectionPool
1871
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1872
            serialNumber = dbConn.getCheckOutSerialNumber();
1873
            pStmt = dbConn.prepareStatement(query);
1874
            //bind the value to query
1875
            pStmt.setString(1, docId);
1876
            //execute the query
1877
            pStmt.execute();
1878
            rs = pStmt.getResultSet();
1879
            //process the result
1880
            if (rs.next()) //There are some records for rev
1881
            {
1882
                rev = rs.getInt(1);
1883
                ;//It is the version for given docid
1884
            } else {
1885
                rev = -5;
1886
            }
1887

    
1888
        }//try
1889
        catch (SQLException e) {
1890
            logMetacat.error(
1891
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1892
                            + e.getMessage());
1893
            throw e;
1894
        }//catch
1895
        finally {
1896
            try {
1897
                pStmt.close();
1898
            }//try
1899
            catch (SQLException ee) {
1900
                logMetacat.error(
1901
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1902
                                + ee.getMessage());
1903
            }//catch
1904
            finally {
1905
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1906
            }//finally
1907
        }//finally
1908
        return rev;
1909
    }//getCurrentRevFromXMLDoumentsTable
1910

    
1911
    /**
1912
     * put a doc into a zip output stream
1913
     *
1914
     * @param docImpl, docmentImpl object which will be sent to zip output
1915
     *            stream
1916
     * @param zipOut, zip output stream which the docImpl will be put
1917
     * @param packageZipEntry, the zip entry name for whole package
1918
     */
1919
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1920
            ZipOutputStream zipOut, String packageZipEntry)
1921
            throws ClassNotFoundException, IOException, SQLException,
1922
            McdbException, Exception
1923
    {
1924
        byte[] byteString = null;
1925
        ZipEntry zEntry = null;
1926

    
1927
        byteString = docImpl.toString().getBytes();
1928
        //use docId as the zip entry's name
1929
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1930
                + docImpl.getDocID());
1931
        zEntry.setSize(byteString.length);
1932
        zipOut.putNextEntry(zEntry);
1933
        zipOut.write(byteString, 0, byteString.length);
1934
        zipOut.closeEntry();
1935

    
1936
    }//addDocToZipOutputStream()
1937

    
1938
    /**
1939
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1940
     * only inlcudes current version. If a DocumentImple object couldn't find
1941
     * for a docid, then the String of this docid was added to vetor rather
1942
     * than DocumentImple object.
1943
     *
1944
     * @param docIdList, a vetor hold a docid list for a data package. In
1945
     *            docid, there is not version number in it.
1946
     */
1947

    
1948
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1949
            throws McdbException, Exception
1950
    {
1951
        //Connection dbConn=null;
1952
        Vector documentImplList = new Vector();
1953
        int rev = 0;
1954

    
1955
        // Check the parameter
1956
        if (docIdList.isEmpty()) { return documentImplList; }//if
1957

    
1958
        //for every docid in vector
1959
        for (int i = 0; i < docIdList.size(); i++) {
1960
            try {
1961
                //get newest version for this docId
1962
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1963
                        .elementAt(i));
1964

    
1965
                // There is no record for this docId in xml_documents table
1966
                if (rev == -5) {
1967
                    // Rather than put DocumentImple object, put a String
1968
                    // Object(docid)
1969
                    // into the documentImplList
1970
                    documentImplList.add((String) docIdList.elementAt(i));
1971
                    // Skip other code
1972
                    continue;
1973
                }
1974

    
1975
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1976
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1977

    
1978
                //create new documentImpl object
1979
                DocumentImpl documentImplObject = new DocumentImpl(
1980
                        docidPlusVersion);
1981
                //add them to vector
1982
                documentImplList.add(documentImplObject);
1983
            }//try
1984
            catch (Exception e) {
1985
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
1986
                        + e.getMessage());
1987
                // continue the for loop
1988
                continue;
1989
            }
1990
        }//for
1991
        return documentImplList;
1992
    }
1993

    
1994
    /**
1995
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
1996
     * object couldn't find for a docid, then the String of this docid was
1997
     * added to vetor rather than DocumentImple object.
1998
     *
1999
     * @param docIdList, a vetor hold a docid list for a data package. In
2000
     *            docid, t here is version number in it.
2001
     */
2002
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2003
    {
2004
        //Connection dbConn=null;
2005
        Vector documentImplList = new Vector();
2006
        String siteCode = null;
2007
        String uniqueId = null;
2008
        int rev = 0;
2009

    
2010
        // Check the parameter
2011
        if (docIdList.isEmpty()) { return documentImplList; }//if
2012

    
2013
        //for every docid in vector
2014
        for (int i = 0; i < docIdList.size(); i++) {
2015

    
2016
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2017

    
2018
            try {
2019
                //create new documentImpl object
2020
                DocumentImpl documentImplObject = new DocumentImpl(
2021
                        docidPlusVersion);
2022
                //add them to vector
2023
                documentImplList.add(documentImplObject);
2024
            }//try
2025
            catch (McdbDocNotFoundException notFoundE) {
2026
                logMetacat.error(
2027
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2028
                                + notFoundE.getMessage());
2029
                // Rather than add a DocumentImple object into vetor, a String
2030
                // object
2031
                // - the doicd was added to the vector
2032
                documentImplList.add(docidPlusVersion);
2033
                // Continue the for loop
2034
                continue;
2035
            }//catch
2036
            catch (Exception e) {
2037
                logMetacat.error(
2038
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2039
                                + e.getMessage());
2040
                // Continue the for loop
2041
                continue;
2042
            }//catch
2043

    
2044
        }//for
2045
        return documentImplList;
2046
    }//getOldVersionAllDocumentImple
2047

    
2048
    /**
2049
     * put a data file into a zip output stream
2050
     *
2051
     * @param docImpl, docmentImpl object which will be sent to zip output
2052
     *            stream
2053
     * @param zipOut, the zip output stream which the docImpl will be put
2054
     * @param packageZipEntry, the zip entry name for whole package
2055
     */
2056
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2057
            ZipOutputStream zipOut, String packageZipEntry)
2058
            throws ClassNotFoundException, IOException, SQLException,
2059
            McdbException, Exception
2060
    {
2061
        byte[] byteString = null;
2062
        ZipEntry zEntry = null;
2063
        // this is data file; add file to zip
2064
        String filePath = MetaCatUtil.getOption("datafilepath");
2065
        if (!filePath.endsWith("/")) {
2066
            filePath += "/";
2067
        }
2068
        String fileName = filePath + docImpl.getDocID();
2069
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2070
        zipOut.putNextEntry(zEntry);
2071
        FileInputStream fin = null;
2072
        try {
2073
            fin = new FileInputStream(fileName);
2074
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2075
            int b = fin.read(buf);
2076
            while (b != -1) {
2077
                zipOut.write(buf, 0, b);
2078
                b = fin.read(buf);
2079
            }//while
2080
            zipOut.closeEntry();
2081
        }//try
2082
        catch (IOException ioe) {
2083
            logMetacat.error("There is an exception: "
2084
                    + ioe.getMessage());
2085
        }//catch
2086
    }//addDataFileToZipOutputStream()
2087

    
2088
    /**
2089
     * create a html summary for data package and put it into zip output stream
2090
     *
2091
     * @param docImplList, the documentImpl ojbects in data package
2092
     * @param zipOut, the zip output stream which the html should be put
2093
     * @param packageZipEntry, the zip entry name for whole package
2094
     */
2095
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2096
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2097
    {
2098
        StringBuffer htmlDoc = new StringBuffer();
2099
        ZipEntry zEntry = null;
2100
        byte[] byteString = null;
2101
        InputStream source;
2102
        DBTransform xmlToHtml;
2103

    
2104
        //create a DBTransform ojbect
2105
        xmlToHtml = new DBTransform();
2106
        //head of html
2107
        htmlDoc.append("<html><head></head><body>");
2108
        for (int i = 0; i < docImplList.size(); i++) {
2109
            // If this String object, this means it is missed data file
2110
            if ((((docImplList.elementAt(i)).getClass()).toString())
2111
                    .equals("class java.lang.String")) {
2112

    
2113
                htmlDoc.append("<a href=\"");
2114
                String dataFileid = (String) docImplList.elementAt(i);
2115
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2116
                htmlDoc.append("Data File: ");
2117
                htmlDoc.append(dataFileid).append("</a><br>");
2118
                htmlDoc.append("<br><hr><br>");
2119

    
2120
            }//if
2121
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2122
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2123
                                              // transform it.
2124
                //transform each file individually then concatenate all of the
2125
                //transformations together.
2126

    
2127
                //for metadata xml title
2128
                htmlDoc.append("<h2>");
2129
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2130
                        .getDocID());
2131
                //htmlDoc.append(".");
2132
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2133
                htmlDoc.append("</h2>");
2134
                //do the actual transform
2135
                StringWriter docString = new StringWriter();
2136
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2137
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2138
                        "-//W3C//HTML//EN", "html", docString);
2139
                htmlDoc.append(docString.toString());
2140
                htmlDoc.append("<br><br><hr><br><br>");
2141
            }//if
2142
            else { //this is a data file so we should link to it in the html
2143
                htmlDoc.append("<a href=\"");
2144
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2145
                        .getDocID();
2146
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2147
                htmlDoc.append("Data File: ");
2148
                htmlDoc.append(dataFileid).append("</a><br>");
2149
                htmlDoc.append("<br><hr><br>");
2150
            }//else
2151
        }//for
2152
        htmlDoc.append("</body></html>");
2153
        byteString = htmlDoc.toString().getBytes();
2154
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2155
        zEntry.setSize(byteString.length);
2156
        zipOut.putNextEntry(zEntry);
2157
        zipOut.write(byteString, 0, byteString.length);
2158
        zipOut.closeEntry();
2159
        //dbConn.close();
2160

    
2161
    }//addHtmlSummaryToZipOutputStream
2162

    
2163
    /**
2164
     * put a data packadge into a zip output stream
2165
     *
2166
     * @param docId, which the user want to put into zip output stream,it has version
2167
     * @param out, a servletoutput stream which the zip output stream will be
2168
     *            put
2169
     * @param user, the username of the user
2170
     * @param groups, the group of the user
2171
     */
2172
    public ZipOutputStream getZippedPackage(String docIdString,
2173
            ServletOutputStream out, String user, String[] groups,
2174
            String passWord) throws ClassNotFoundException, IOException,
2175
            SQLException, McdbException, NumberFormatException, Exception
2176
    {
2177
        ZipOutputStream zOut = null;
2178
        String elementDocid = null;
2179
        DocumentImpl docImpls = null;
2180
        //Connection dbConn = null;
2181
        Vector docIdList = new Vector();
2182
        Vector documentImplList = new Vector();
2183
        Vector htmlDocumentImplList = new Vector();
2184
        String packageId = null;
2185
        String rootName = "package";//the package zip entry name
2186

    
2187
        String docId = null;
2188
        int version = -5;
2189
        // Docid without revision
2190
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2191
        // revision number
2192
        version = MetaCatUtil.getVersionFromString(docIdString);
2193

    
2194
        //check if the reqused docId is a data package id
2195
        if (!isDataPackageId(docId)) {
2196

    
2197
            /*
2198
             * Exception e = new Exception("The request the doc id "
2199
             * +docIdString+ " is not a data package id");
2200
             */
2201

    
2202
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2203
            // zip
2204
            //up the single document and return the zip file.
2205
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2206

    
2207
                Exception e = new Exception("User " + user
2208
                        + " does not have permission"
2209
                        + " to export the data package " + docIdString);
2210
                throw e;
2211
            }
2212

    
2213
            docImpls = new DocumentImpl(docIdString);
2214
            //checking if the user has the permission to read the documents
2215
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2216
                    .getDocID())) {
2217
                zOut = new ZipOutputStream(out);
2218
                //if the docImpls is metadata
2219
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2220
                    //add metadata into zip output stream
2221
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2222
                }//if
2223
                else {
2224
                    //it is data file
2225
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2226
                    htmlDocumentImplList.add(docImpls);
2227
                }//else
2228
            }//if
2229

    
2230
            zOut.finish(); //terminate the zip file
2231
            return zOut;
2232
        }
2233
        // Check the permission of user
2234
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2235

    
2236
            Exception e = new Exception("User " + user
2237
                    + " does not have permission"
2238
                    + " to export the data package " + docIdString);
2239
            throw e;
2240
        } else //it is a packadge id
2241
        {
2242
            //store the package id
2243
            packageId = docId;
2244
            //get current version in database
2245
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2246
            //If it is for current version (-1 means user didn't specify
2247
            // revision)
2248
            if ((version == -1) || version == currentVersion) {
2249
                //get current version number
2250
                version = currentVersion;
2251
                //get package zip entry name
2252
                //it should be docId.revsion.package
2253
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2254
                        + version + MetaCatUtil.getOption("accNumSeparator")
2255
                        + "package";
2256
                //get the whole id list for data packadge
2257
                docIdList = getCurrentDocidListForDataPackage(packageId);
2258
                //get the whole documentImple object
2259
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2260

    
2261
            }//if
2262
            else if (version > currentVersion || version < -1) {
2263
                throw new Exception("The user specified docid: " + docId + "."
2264
                        + version + " doesn't exist");
2265
            }//else if
2266
            else //for an old version
2267
            {
2268

    
2269
                rootName = docIdString
2270
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2271
                //get the whole id list for data packadge
2272
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2273

    
2274
                //get the whole documentImple object
2275
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2276
            }//else
2277

    
2278
            // Make sure documentImplist is not empty
2279
            if (documentImplList.isEmpty()) { throw new Exception(
2280
                    "Couldn't find component for data package: " + packageId); }//if
2281

    
2282
            zOut = new ZipOutputStream(out);
2283
            //put every element into zip output stream
2284
            for (int i = 0; i < documentImplList.size(); i++) {
2285
                // if the object in the vetor is String, this means we couldn't
2286
                // find
2287
                // the document locally, we need find it remote
2288
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2289
                        .equals("class java.lang.String")) {
2290
                    // Get String object from vetor
2291
                    String documentId = (String) documentImplList.elementAt(i);
2292
                    logMetacat.info("docid: " + documentId);
2293
                    // Get doicd without revision
2294
                    String docidWithoutRevision = MetaCatUtil
2295
                            .getDocIdFromString(documentId);
2296
                    logMetacat.info("docidWithoutRevsion: "
2297
                            + docidWithoutRevision);
2298
                    // Get revision
2299
                    String revision = MetaCatUtil
2300
                            .getRevisionStringFromString(documentId);
2301
                    logMetacat.info("revsion from docIdentifier: "
2302
                            + revision);
2303
                    // Zip entry string
2304
                    String zipEntryPath = rootName + "/data/";
2305
                    // Create a RemoteDocument object
2306
                    RemoteDocument remoteDoc = new RemoteDocument(
2307
                            docidWithoutRevision, revision, user, passWord,
2308
                            zipEntryPath);
2309
                    // Here we only read data file from remote metacat
2310
                    String docType = remoteDoc.getDocType();
2311
                    if (docType != null) {
2312
                        if (docType.equals("BIN")) {
2313
                            // Put remote document to zip output
2314
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2315
                            // Add String object to htmlDocumentImplList
2316
                            String elementInHtmlList = remoteDoc
2317
                                    .getDocIdWithoutRevsion()
2318
                                    + MetaCatUtil.getOption("accNumSeparator")
2319
                                    + remoteDoc.getRevision();
2320
                            htmlDocumentImplList.add(elementInHtmlList);
2321
                        }//if
2322
                    }//if
2323

    
2324
                }//if
2325
                else {
2326
                    //create a docmentImpls object (represent xml doc) base on
2327
                    // the docId
2328
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2329
                    //checking if the user has the permission to read the
2330
                    // documents
2331
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2332
                            .getDocID())) {
2333
                        //if the docImpls is metadata
2334
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2335
                            //add metadata into zip output stream
2336
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2337
                            //add the documentImpl into the vetor which will
2338
                            // be used in html
2339
                            htmlDocumentImplList.add(docImpls);
2340

    
2341
                        }//if
2342
                        else {
2343
                            //it is data file
2344
                            addDataFileToZipOutputStream(docImpls, zOut,
2345
                                    rootName);
2346
                            htmlDocumentImplList.add(docImpls);
2347
                        }//else
2348
                    }//if
2349
                }//else
2350
            }//for
2351

    
2352
            //add html summary file
2353
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2354
                    rootName);
2355
            zOut.finish(); //terminate the zip file
2356
            //dbConn.close();
2357
            return zOut;
2358
        }//else
2359
    }//getZippedPackage()
2360

    
2361
    private class ReturnFieldValue
2362
    {
2363

    
2364
        private String docid = null; //return field value for this docid
2365

    
2366
        private String fieldValue = null;
2367

    
2368
        private String xmlFieldValue = null; //return field value in xml
2369
                                             // format
2370
        private String fieldType = null; //ATTRIBUTE, TEXT...
2371

    
2372
        public void setDocid(String myDocid)
2373
        {
2374
            docid = myDocid;
2375
        }
2376

    
2377
        public String getDocid()
2378
        {
2379
            return docid;
2380
        }
2381

    
2382
        public void setFieldValue(String myValue)
2383
        {
2384
            fieldValue = myValue;
2385
        }
2386

    
2387
        public String getFieldValue()
2388
        {
2389
            return fieldValue;
2390
        }
2391

    
2392
        public void setXMLFieldValue(String xml)
2393
        {
2394
            xmlFieldValue = xml;
2395
        }
2396

    
2397
        public String getXMLFieldValue()
2398
        {
2399
            return xmlFieldValue;
2400
        }
2401
        
2402
        public void setFieldType(String myType)
2403
        {
2404
            fieldType = myType;
2405
        }
2406

    
2407
        public String getFieldType()
2408
        {
2409
            return fieldType;
2410
        }
2411

    
2412
    }
2413
    
2414
    /**
2415
     * a class to store one result document consisting of a docid and a document
2416
     */
2417
    private class ResultDocument
2418
    {
2419
      public String docid;
2420
      public String document;
2421
      
2422
      public ResultDocument(String docid, String document)
2423
      {
2424
        this.docid = docid;
2425
        this.document = document;
2426
      }
2427
    }
2428
    
2429
    /**
2430
     * a private class to handle a set of resultDocuments
2431
     */
2432
    private class ResultDocumentSet
2433
    {
2434
      private Vector docids;
2435
      private Vector documents;
2436
      
2437
      public ResultDocumentSet()
2438
      {
2439
        docids = new Vector();
2440
        documents = new Vector();
2441
      }
2442
      
2443
      /**
2444
       * adds a result document to the set
2445
       */
2446
      public void addResultDocument(ResultDocument rd)
2447
      {
2448
        if(rd.docid == null)
2449
          return;
2450
        if(rd.document == null)
2451
          rd.document = "";
2452
       
2453
           docids.addElement(rd.docid);
2454
           documents.addElement(rd.document);
2455
        
2456
      }
2457
      
2458
      /**
2459
       * gets an iterator of docids
2460
       */
2461
      public Iterator getDocids()
2462
      {
2463
        return docids.iterator();
2464
      }
2465
      
2466
      /**
2467
       * gets an iterator of documents
2468
       */
2469
      public Iterator getDocuments()
2470
      {
2471
        return documents.iterator();
2472
      }
2473
      
2474
      /**
2475
       * returns the size of the set
2476
       */
2477
      public int size()
2478
      {
2479
        return docids.size();
2480
      }
2481
      
2482
      /**
2483
       * tests to see if this set contains the given docid
2484
       */
2485
      private boolean containsDocid(String docid)
2486
      {
2487
        for(int i=0; i<docids.size(); i++)
2488
        {
2489
          String docid0 = (String)docids.elementAt(i);
2490
          if(docid0.trim().equals(docid.trim()))
2491
          {
2492
            return true;
2493
          }
2494
        }
2495
        return false;
2496
      }
2497
      
2498
      /**
2499
       * removes the element with the given docid
2500
       */
2501
      public String remove(String docid)
2502
      {
2503
        for(int i=0; i<docids.size(); i++)
2504
        {
2505
          String docid0 = (String)docids.elementAt(i);
2506
          if(docid0.trim().equals(docid.trim()))
2507
          {
2508
            String returnDoc = (String)documents.elementAt(i);
2509
            documents.remove(i);
2510
            docids.remove(i);
2511
            return returnDoc;
2512
          }
2513
        }
2514
        return null;
2515
      }
2516
      
2517
      /**
2518
       * add a result document
2519
       */
2520
      public void put(ResultDocument rd)
2521
      {
2522
        addResultDocument(rd);
2523
      }
2524
      
2525
      /**
2526
       * add a result document by components
2527
       */
2528
      public void put(String docid, String document)
2529
      {
2530
        addResultDocument(new ResultDocument(docid, document));
2531
      }
2532
      
2533
      /**
2534
       * get the document part of the result document by docid
2535
       */
2536
      public Object get(String docid)
2537
      {
2538
        for(int i=0; i<docids.size(); i++)
2539
        {
2540
          String docid0 = (String)docids.elementAt(i);
2541
          if(docid0.trim().equals(docid.trim()))
2542
          {
2543
            return documents.elementAt(i);
2544
          }
2545
        }
2546
        return null;
2547
      }
2548
      
2549
      /**
2550
       * get the document part of the result document by an object
2551
       */
2552
      public Object get(Object o)
2553
      {
2554
        return get((String)o);
2555
      }
2556
      
2557
      /**
2558
       * get an entire result document by index number
2559
       */
2560
      public ResultDocument get(int index)
2561
      {
2562
        return new ResultDocument((String)docids.elementAt(index), 
2563
          (String)documents.elementAt(index));
2564
      }
2565
      
2566
      /**
2567
       * return a string representation of this object
2568
       */
2569
      public String toString()
2570
      {
2571
        String s = "";
2572
        for(int i=0; i<docids.size(); i++)
2573
        {
2574
          s += (String)docids.elementAt(i) + "\n";
2575
        }
2576
        return s;
2577
      }
2578
      /*
2579
       * Set a new document value for a given docid
2580
       */
2581
      public void set(String docid, String document)
2582
      {
2583
    	   for(int i=0; i<docids.size(); i++)
2584
           {
2585
             String docid0 = (String)docids.elementAt(i);
2586
             if(docid0.trim().equals(docid.trim()))
2587
             {
2588
                 documents.set(i, document);
2589
             }
2590
           }
2591
           
2592
      }
2593
    }
2594
}
(21-21/66)