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: 2007-08-02 16:58:44 -0700 (Thu, 02 Aug 2007) $'
14
 * '$Revision: 3342 $'
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 **/
81
    Vector docidOverride = new Vector();
82
    
83
    // a hash table serves as query reuslt cache. Key of hashtable
84
    // is a query string and value is result xml string
85
    private static Hashtable queryResultCache = new Hashtable();
86
    
87
    // Capacity of the query result cache
88
    private static final int QUERYRESULTCACHESIZE = Integer.parseInt(MetaCatUtil.getOption("queryresult_cache_size"));
89

    
90
    /**
91
     * the main routine used to test the DBQuery utility.
92
     * <p>
93
     * Usage: java DBQuery <xmlfile>
94
     *
95
     * @param xmlfile the filename of the xml file containing the query
96
     */
97
    static public void main(String[] args)
98
    {
99

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

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

    
120
                // Time the request if asked for
121
                double startTime = System.currentTimeMillis();
122

    
123
                // Open a connection to the database
124
                MetaCatUtil util = new MetaCatUtil();
125
                //Connection dbconn = util.openDBConnection();
126

    
127
                double connTime = System.currentTimeMillis();
128

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

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

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

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

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

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

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

    
203
    /**
204
     * 
205
     * Construct an instance of DBQuery Class
206
     * BUT accept a docid Vector that will supersede
207
     * the query.printSQL() method
208
     *
209
     * If a docid Vector is passed in,
210
     * the docids will be used to create a simple IN query 
211
     * without the multiple subselects of the printSQL() method
212
     *
213
     * Using this constructor, we just check for 
214
     * a docidOverride Vector in the findResultDoclist() method
215
     *
216
     * @param docids List of docids to display in the resultset
217
     */
218
    public DBQuery(Vector docids)
219
    {
220
        this.docidOverride = docids;
221
        String parserName = MetaCatUtil.getOption("saxparser");
222
        this.parserName = parserName;
223
    }
224

    
225
  /**
226
   * Method put the search result set into out printerwriter
227
   * @param resoponse the return response
228
   * @param out the output printer
229
   * @param params the paratermer hashtable
230
   * @param user the user name (it maybe different to the one in param)
231
   * @param groups the group array
232
   * @param sessionid  the sessionid
233
   */
234
  public void findDocuments(HttpServletResponse response,
235
                                       PrintWriter out, Hashtable params,
236
                                       String user, String[] groups,
237
                                       String sessionid)
238
  {
239
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
240
               .booleanValue();
241
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
242

    
243
  }
244

    
245

    
246
    /**
247
     * Method put the search result set into out printerwriter
248
     * @param resoponse the return response
249
     * @param out the output printer
250
     * @param params the paratermer hashtable
251
     * @param user the user name (it maybe different to the one in param)
252
     * @param groups the group array
253
     * @param sessionid  the sessionid
254
     */
255
    public void findDocuments(HttpServletResponse response,
256
                                         PrintWriter out, Hashtable params,
257
                                         String user, String[] groups,
258
                                         String sessionid, boolean useXMLIndex)
259
    {
260
      int pagesize = 0;
261
      int pagestart = 0;
262
      
263
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
264
      {
265
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
266
        String pagestartStr = ((String[])params.get("pagestart"))[0];
267
        if(pagesizeStr != null && pagestartStr != null)
268
        {
269
          pagesize = (new Integer(pagesizeStr)).intValue();
270
          pagestart = (new Integer(pagestartStr)).intValue();
271
        }
272
      }
273
      
274
      // get query and qformat
275
      String xmlquery = ((String[])params.get("query"))[0];
276

    
277
      logMetacat.info("SESSIONID: " + sessionid);
278
      logMetacat.info("xmlquery: " + xmlquery);
279
      String qformat = ((String[])params.get("qformat"))[0];
280
      logMetacat.info("qformat: " + qformat);
281
      // Get the XML query and covert it into a SQL statment
282
      QuerySpecification qspec = null;
283
      if ( xmlquery != null)
284
      {
285
         xmlquery = transformQuery(xmlquery);
286
         try
287
         {
288
           qspec = new QuerySpecification(xmlquery,
289
                                          parserName,
290
                                          MetaCatUtil.getOption("accNumSeparator"));
291
         }
292
         catch (Exception ee)
293
         {
294
           logMetacat.error("error generating QuerySpecification object"
295
                                    +" in DBQuery.findDocuments"
296
                                    + ee.getMessage());
297
         }
298
      }
299

    
300

    
301

    
302
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
303
      {
304
        //xml format
305
        response.setContentType("text/xml");
306
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex, 
307
          pagesize, pagestart, sessionid);
308
      }//if
309
      else
310
      {
311
        //knb format, in this case we will get whole result and sent it out
312
        response.setContentType("text/html");
313
        PrintWriter nonout = null;
314
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
315
                                                groups, useXMLIndex, pagesize, 
316
                                                pagestart, sessionid);
317
        
318
        //transfer the xml to html
319
        try
320
        {
321
         double startHTMLTransform = System.currentTimeMillis()/1000;
322
         DBTransform trans = new DBTransform();
323
         response.setContentType("text/html");
324

    
325
         // if the user is a moderator, then pass a param to the 
326
         // xsl specifying the fact
327
         if(MetaCatUtil.isModerator(user, groups)){
328
        	 params.put("isModerator", new String[] {"true"});
329
         }
330

    
331
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
332
                                 "-//W3C//HTML//EN", qformat, out, params,
333
                                 sessionid);
334
         double endHTMLTransform = System.currentTimeMillis()/1000;
335
          logMetacat.warn("The time to transfrom resultset from xml to html format is "
336
                  		                             +(endHTMLTransform -startHTMLTransform));
337
          MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Transfrom xml to html  "
338
                             +(endHTMLTransform -startHTMLTransform));
339
          MetaCatUtil.writeDebugToDelimiteredFile(" "+(endHTMLTransform -startHTMLTransform), false);
340
        }
341
        catch(Exception e)
342
        {
343
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
344
                                +e.getMessage());
345
         }
346

    
347
      }//else
348

    
349
  }
350
  
351
  /**
352
   * Transforms a hashtable of documents to an xml or html result and sent
353
   * the content to outputstream. Keep going untill hastable is empty. stop it.
354
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
355
   * to xmlquery String
356
   * @param xmlquery
357
   * @param qspec
358
   * @param out
359
   * @param user
360
   * @param groups
361
   * @param useXMLIndex
362
   * @param sessionid
363
   * @return
364
   */
365
    public StringBuffer createResultDocument(String xmlquery,
366
                                              QuerySpecification qspec,
367
                                              PrintWriter out,
368
                                              String user, String[] groups,
369
                                              boolean useXMLIndex)
370
    {
371
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"");
372
    }
373

    
374
  /*
375
   * Transforms a hashtable of documents to an xml or html result and sent
376
   * the content to outputstream. Keep going untill hastable is empty. stop it.
377
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
378
   * to xmlquery String
379
   */
380
  public StringBuffer createResultDocument(String xmlquery,
381
                                            QuerySpecification qspec,
382
                                            PrintWriter out,
383
                                            String user, String[] groups,
384
                                            boolean useXMLIndex, int pagesize,
385
                                            int pagestart, String sessionid)
386
  {
387
    DBConnection dbconn = null;
388
    int serialNumber = -1;
389
    StringBuffer resultset = new StringBuffer();
390

    
391
    //try to get the cached version first    
392
    Hashtable sessionHash = MetaCatServlet.getSessionHash();
393
    HttpSession sess = (HttpSession)sessionHash.get(sessionid);
394

    
395
    
396
    resultset.append("<?xml version=\"1.0\"?>\n");
397
    resultset.append("<resultset>\n");
398
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
399
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
400
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
401
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
402

    
403
    resultset.append("  <query>" + xmlquery + "</query>");
404
    //send out a new query
405
    if (out != null)
406
    {
407
      out.println(resultset.toString());
408
    }
409
    if (qspec != null)
410
    {
411
      try
412
      {
413

    
414
        //checkout the dbconnection
415
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
416
        serialNumber = dbconn.getCheckOutSerialNumber();
417

    
418
        //print out the search result
419
        // search the doc list
420
        StringBuffer resultContent = findResultDoclist(qspec, out, user, groups,
421
                                      dbconn, useXMLIndex, pagesize, pagestart, 
422
                                      sessionid);
423
        resultset.append(resultContent);
424
      } //try
425
      catch (IOException ioe)
426
      {
427
        logMetacat.error("IO error in DBQuery.findDocuments:");
428
        logMetacat.error(ioe.getMessage());
429

    
430
      }
431
      catch (SQLException e)
432
      {
433
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
434
                                 + e.getMessage());
435
      }
436
      catch (Exception ee)
437
      {
438
        logMetacat.error("Exception in DBQuery.findDocuments: "
439
                                 + ee.getMessage());
440
        ee.printStackTrace();
441
      }
442
      finally
443
      {
444
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
445
      } //finally
446
    }//if
447
    String closeRestultset = "</resultset>";
448
    resultset.append(closeRestultset);
449
    if (out != null)
450
    {
451
      out.println(closeRestultset);
452
    }
453

    
454
    //default to returning the whole resultset
455
    return resultset;
456
  }//createResultDocuments
457

    
458
    /*
459
     * Find the doc list which match the query
460
     */
461
    private StringBuffer findResultDoclist(QuerySpecification qspec,
462
                                      PrintWriter out,
463
                                      String user, String[]groups,
464
                                      DBConnection dbconn, boolean useXMLIndex,
465
                                      int pagesize, int pagestart, String sessionid)
466
                                      throws Exception
467
    {
468
      StringBuffer resultsetBuffer = new StringBuffer();
469
      String query = null;
470
      int count = 0;
471
      int index = 0;
472
      ResultDocumentSet docListResult = new ResultDocumentSet();
473
      PreparedStatement pstmt = null;
474
      String docid = null;
475
      String docname = null;
476
      String doctype = null;
477
      String createDate = null;
478
      String updateDate = null;
479
      StringBuffer document = null;
480
      boolean lastpage = false;
481
      int rev = 0;
482
      double startTime = 0;
483
      //int offset = 1;
484
      double startSelectionTime = System.currentTimeMillis()/1000;
485
      ResultSet rs = null;
486
        
487
      //offset = 1;
488
      // this is a hack for offset
489
      /*if (out == null)
490
      {
491
        // for html page, we put everything into one page
492
        offset =
493
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
494
      }
495
      else
496
      {
497
          offset =
498
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
499
      }*/
500

    
501
      /*
502
       * Check the docidOverride Vector
503
       * if defined, we bypass the qspec.printSQL() method
504
       * and contruct a simpler query based on a 
505
       * list of docids rather than a bunch of subselects
506
       */
507
      if ( this.docidOverride.size() == 0 ) {
508
          query = qspec.printSQL(useXMLIndex);
509
      } else {
510
          logMetacat.info("*** docid override " + this.docidOverride.size());
511
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
512
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
513
          for (int i = 0; i < docidOverride.size(); i++) {  
514
              queryBuffer.append("'");
515
              queryBuffer.append( (String)docidOverride.elementAt(i) );
516
              queryBuffer.append("',");
517
          }
518
          // empty string hack 
519
          queryBuffer.append( "'') " );
520
          query = queryBuffer.toString();
521
      } 
522
      String ownerQuery = getOwnerQuery(user);
523
      logMetacat.info("\n\n\n query: " + query);
524
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
525
      // if query is not the owner query, we need to check the permission
526
      // otherwise we don't need (owner has all permission by default)
527
      if (!query.equals(ownerQuery))
528
      {
529
        // set user name and group
530
        qspec.setUserName(user);
531
        qspec.setGroup(groups);
532
        // Get access query
533
        String accessQuery = qspec.getAccessQuery();
534
        if(!query.endsWith("WHERE")){
535
            query = query + accessQuery;
536
        } else {
537
            query = query + accessQuery.substring(4, accessQuery.length());
538
        }
539
        
540
      }
541
      logMetacat.warn("============ final selection query: " + query);
542
      
543
      // we only get cache for public
544
      if (user != null && user.equalsIgnoreCase("public") 
545
     		 && pagesize == 0 && MetaCatUtil.getOption("query_cache_on").equals("true"))
546
      {
547
   	      String cachedResult = getResultXMLFromCache(query);
548
   	      //System.out.println("==========the string from cache is "+cachedResult);
549
   	      if (cachedResult != null)
550
   	      {
551
   	    	 if (out != null)
552
   	         {
553
   	             out.println(cachedResult);
554
   	         }
555
   	    	 resultsetBuffer.append(cachedResult);
556
   	    	 return resultsetBuffer;
557
   	      }
558
      }
559
      
560
      startTime = System.currentTimeMillis() / 1000;
561
      pstmt = dbconn.prepareStatement(query);
562
      rs = pstmt.executeQuery();
563

    
564
      double queryExecuteTime = System.currentTimeMillis() / 1000;
565
      logMetacat.warn("Time to execute select docid query is "
566
                    + (queryExecuteTime - startTime));
567
      MetaCatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
568
              + (queryExecuteTime - startTime));
569
      MetaCatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
570

    
571
      boolean tableHasRows = rs.next();
572
      
573
      if(pagesize == 0)
574
      { //this makes sure we get all results if there is no paging
575
        pagesize = 9999999;
576
        pagestart = 9999999;
577
      } 
578
      
579
      int currentIndex = 0;
580
      while (tableHasRows)
581
      {
582
        logMetacat.info("############getting result: " + currentIndex);
583
        docid = rs.getString(1).trim();
584
        logMetacat.info("############processing: " + docid);
585
        docname = rs.getString(2);
586
        doctype = rs.getString(3);
587
        logMetacat.info("############processing: " + doctype);
588
        createDate = rs.getString(4);
589
        updateDate = rs.getString(5);
590
        rev = rs.getInt(6);
591
        
592
         Vector returndocVec = qspec.getReturnDocList();
593
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
594
        {
595
          logMetacat.info("NOT Back tracing now...");
596
           document = new StringBuffer();
597

    
598
           String completeDocid = docid
599
                            + MetaCatUtil.getOption("accNumSeparator");
600
           completeDocid += rev;
601
           document.append("<docid>").append(completeDocid).append("</docid>");
602
           if (docname != null)
603
           {
604
               document.append("<docname>" + docname + "</docname>");
605
           }
606
           if (doctype != null)
607
           {
608
              document.append("<doctype>" + doctype + "</doctype>");
609
           }
610
           if (createDate != null)
611
           {
612
               document.append("<createdate>" + createDate + "</createdate>");
613
           }
614
           if (updateDate != null)
615
           {
616
             document.append("<updatedate>" + updateDate + "</updatedate>");
617
           }
618
           // Store the document id and the root node id
619
           
620
           docListResult.addResultDocument(
621
             new ResultDocument(docid, (String) document.toString()));
622
           logMetacat.info("$$$$$$$real result: " + docid);
623
           currentIndex++;
624
           count++;
625
        }//else
626
        
627
        // when doclist reached the offset number, send out doc list and empty
628
        // the hash table
629
        /*if (count == offset && pagesize == 0)
630
        { //if pagesize is not 0, do this later.
631
          //reset count
632
          //logMetacat.warn("############doing subset cache");
633
          count = 0;
634
          handleSubsetResult(qspec, resultsetBuffer, out, docListResult,
635
                              user, groups,dbconn, useXMLIndex);
636
          //reset docListResult
637
          docListResult = new ResultDocumentSet();
638
        }*/
639
       
640
       logMetacat.info("currentIndex: " + currentIndex);
641
       logMetacat.info("page comparator: " + (pagesize * pagestart) + pagesize);
642
       if(currentIndex >= ((pagesize * pagestart) + pagesize))
643
       {
644
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
645
         for(int i=pagesize*pagestart; i<docListResult.size(); i++)
646
         {
647
           pagedResultsHash.put(docListResult.get(i));
648
         }
649
         
650
         docListResult = pagedResultsHash;
651
         break;
652
       }
653
       // Advance to the next record in the cursor
654
       tableHasRows = rs.next();
655
       if(!tableHasRows)
656
       {
657
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
658
         //get the last page of information then break
659
         if(pagesize != 9999999)
660
         {
661
           for(int i=pagesize*pagestart; i<docListResult.size(); i++)
662
           {
663
             pagedResultsHash.put(docListResult.get(i));
664
           }
665
           docListResult = pagedResultsHash;
666
         }
667
         
668
         lastpage = true;
669
         break;
670
       }
671
     }//while
672
     
673
     rs.close();
674
     pstmt.close();
675
     double docListTime = System.currentTimeMillis() / 1000;
676
     logMetacat.warn("======Total time to get docid list is: "
677
                          + (docListTime - startSelectionTime ));
678
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Total selection: "
679
             + (docListTime - startSelectionTime ));
680
     MetaCatUtil.writeDebugToDelimiteredFile(" "+ (docListTime - startSelectionTime ), false);
681
     //if docListResult is not empty, it need to be sent.
682
     if (docListResult.size() != 0)
683
     {
684
      
685
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
686
                              user, groups,dbconn, useXMLIndex);
687
     }
688

    
689
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
690
     if (out != null)
691
     {
692
         out.println("\n<lastpage>" + lastpage + "</lastpage>\n");
693
     }
694
     
695
     // now we only cached none-paged query and user is public
696
     if (user != null && user.equalsIgnoreCase("public") 
697
    		 && pagesize == 9999999 && MetaCatUtil.getOption("query_cache_on").equals("true"))
698
     {
699
       //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
700
  	   storeQueryResultIntoCache(query, resultsetBuffer.toString());
701
     }
702
          
703
     return resultsetBuffer;
704
    }//findReturnDoclist
705

    
706

    
707
    /*
708
     * Send completed search hashtable(part of reulst)to output stream
709
     * and buffer into a buffer stream
710
     */
711
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
712
                                           StringBuffer resultset,
713
                                           PrintWriter out, ResultDocumentSet partOfDoclist,
714
                                           String user, String[]groups,
715
                                       DBConnection dbconn, boolean useXMLIndex)
716
                                       throws Exception
717
   {
718
     double startReturnField = System.currentTimeMillis()/1000;
719
     // check if there is a record in xml_returnfield
720
     // and get the returnfield_id and usage count
721
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
722
     boolean enterRecords = false;
723

    
724
     // get value of xml_returnfield_count
725
     int count = (new Integer(MetaCatUtil
726
                            .getOption("xml_returnfield_count")))
727
                            .intValue();
728

    
729
     // set enterRecords to true if usage_count is more than the offset
730
     // specified in metacat.properties
731
     if(usage_count > count){
732
         enterRecords = true;
733
     }
734

    
735
     if(returnfield_id < 0){
736
         logMetacat.warn("Error in getting returnfield id from"
737
                                  + "xml_returnfield table");
738
         enterRecords = false;
739
     }
740

    
741
     // get the hashtable containing the docids that already in the
742
     // xml_queryresult table
743
     logMetacat.info("size of partOfDoclist before"
744
                             + " docidsInQueryresultTable(): "
745
                             + partOfDoclist.size());
746
     double startGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
747
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
748
                                                        partOfDoclist, dbconn);
749

    
750
     // remove the keys in queryresultDocList from partOfDoclist
751
     Enumeration _keys = queryresultDocList.keys();
752
     while (_keys.hasMoreElements()){
753
         partOfDoclist.remove((String)_keys.nextElement());
754
     }
755
     double endGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
756
     logMetacat.warn("Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
757
          		               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
758
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
759
               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
760
     MetaCatUtil.writeDebugToDelimiteredFile(" " +
761
             (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable),false);
762
     // backup the keys-elements in partOfDoclist to check later
763
     // if the doc entry is indexed yet
764
     Hashtable partOfDoclistBackup = new Hashtable();
765
     Iterator itt = partOfDoclist.getDocids();
766
     while (itt.hasNext()){
767
       Object key = itt.next();
768
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
769
     }
770

    
771
     logMetacat.info("size of partOfDoclist after"
772
                             + " docidsInQueryresultTable(): "
773
                             + partOfDoclist.size());
774

    
775
     //add return fields for the documents in partOfDoclist
776
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
777
                                        dbconn, useXMLIndex);
778
     double endExtendedQuery = System.currentTimeMillis()/1000;
779
     logMetacat.warn("Get fields from index and node table (Part2 in return fields) "
780
        		                                          + (endExtendedQuery - endGetReturnValueFromQueryresultable));
781
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
782
             + (endExtendedQuery - endGetReturnValueFromQueryresultable));
783
     MetaCatUtil.writeDebugToDelimiteredFile(" "
784
             + (endExtendedQuery - endGetReturnValueFromQueryresultable), false);
785
     //add relationship part part docid list for the documents in partOfDocList
786
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
787

    
788
     double startStoreReturnField = System.currentTimeMillis()/1000;
789
     Iterator keys = partOfDoclist.getDocids();
790
     String key = null;
791
     String element = null;
792
     String query = null;
793
     int offset = (new Integer(MetaCatUtil
794
                               .getOption("queryresult_string_length")))
795
                               .intValue();
796
     while (keys.hasNext())
797
     {
798
         key = (String) keys.next();
799
         element = (String)partOfDoclist.get(key);
800

    
801
	 // check if the enterRecords is true, elements is not null, element's
802
         // length is less than the limit of table column and if the document
803
         // has been indexed already
804
         if(enterRecords && element != null
805
		&& element.length() < offset
806
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
807
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
808
                 + "queryresult_string) VALUES (?, ?, ?)";
809

    
810
             PreparedStatement pstmt = null;
811
             pstmt = dbconn.prepareStatement(query);
812
             pstmt.setInt(1, returnfield_id);
813
             pstmt.setString(2, key);
814
             pstmt.setString(3, element);
815

    
816
             dbconn.increaseUsageCount(1);
817
             pstmt.execute();
818
             pstmt.close();
819
         }
820
        
821
         // A string with element
822
         String xmlElement = "  <document>" + element + "</document>";
823

    
824
         //send single element to output
825
         if (out != null)
826
         {
827
             out.println(xmlElement);
828
         }
829
         resultset.append(xmlElement);
830
     }//while
831
     
832
     double endStoreReturnField = System.currentTimeMillis()/1000;
833
     logMetacat.warn("Time to store new return fields into xml_queryresult table (Part4 in return fields) "
834
                   + (endStoreReturnField -startStoreReturnField));
835
     MetaCatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
836
             + (endStoreReturnField -startStoreReturnField));
837
     MetaCatUtil.writeDebugToDelimiteredFile(" "
838
             + (endStoreReturnField -startStoreReturnField), false);
839
     
840
     Enumeration keysE = queryresultDocList.keys();
841
     while (keysE.hasMoreElements())
842
     {
843
         key = (String) keysE.nextElement();
844
         element = (String)queryresultDocList.get(key);
845
         // A string with element
846
         String xmlElement = "  <document>" + element + "</document>";
847
         //send single element to output
848
         if (out != null)
849
         {
850
             out.println(xmlElement);
851
         }
852
         resultset.append(xmlElement);
853
     }//while
854
     double returnFieldTime = System.currentTimeMillis() / 1000;
855
     logMetacat.warn("======Total time to get return fields is: "
856
                           + (returnFieldTime - startReturnField));
857
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------"+
858
    		 "Total to get return fields  "
859
                                   + (returnFieldTime - startReturnField));
860
     MetaCatUtil.writeDebugToDelimiteredFile(" "+ (returnFieldTime - startReturnField), false);
861
     return resultset;
862
 }
863

    
864
   /**
865
    * Get the docids already in xml_queryresult table and corresponding
866
    * queryresultstring as a hashtable
867
    */
868
   private Hashtable docidsInQueryresultTable(int returnfield_id,
869
                                              ResultDocumentSet partOfDoclist,
870
                                              DBConnection dbconn){
871

    
872
         Hashtable returnValue = new Hashtable();
873
         PreparedStatement pstmt = null;
874
         ResultSet rs = null;
875

    
876
         // get partOfDoclist as string for the query
877
         Iterator keylist = partOfDoclist.getDocids();
878
         StringBuffer doclist = new StringBuffer();
879
         while (keylist.hasNext())
880
         {
881
             doclist.append("'");
882
             doclist.append((String) keylist.next());
883
             doclist.append("',");
884
         }//while
885

    
886

    
887
         if (doclist.length() > 0)
888
         {
889
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
890

    
891
             // the query to find out docids from xml_queryresult
892
             String query = "select docid, queryresult_string from "
893
                          + "xml_queryresult where returnfield_id = " +
894
                          returnfield_id +" and docid in ("+ doclist + ")";
895
             logMetacat.info("Query to get docids from xml_queryresult:"
896
                                      + query);
897

    
898
             try {
899
                 // prepare and execute the query
900
                 pstmt = dbconn.prepareStatement(query);
901
                 dbconn.increaseUsageCount(1);
902
                 pstmt.execute();
903
                 rs = pstmt.getResultSet();
904
                 boolean tableHasRows = rs.next();
905
                 while (tableHasRows) {
906
                     // store the returned results in the returnValue hashtable
907
                     String key = rs.getString(1);
908
                     String element = rs.getString(2);
909

    
910
                     if(element != null){
911
                         returnValue.put(key, element);
912
                     } else {
913
                         logMetacat.info("Null elment found ("
914
                         + "DBQuery.docidsInQueryresultTable)");
915
                     }
916
                     tableHasRows = rs.next();
917
                 }
918
                 rs.close();
919
                 pstmt.close();
920
             } catch (Exception e){
921
                 logMetacat.error("Error getting docids from "
922
                                          + "queryresult in "
923
                                          + "DBQuery.docidsInQueryresultTable: "
924
                                          + e.getMessage());
925
              }
926
         }
927
         return returnValue;
928
     }
929

    
930

    
931
   /**
932
    * Method to get id from xml_returnfield table
933
    * for a given query specification
934
    */
935
   private int returnfield_id;
936
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
937
                                           DBConnection dbconn){
938
       int id = -1;
939
       int count = 1;
940
       PreparedStatement pstmt = null;
941
       ResultSet rs = null;
942
       String returnfield = qspec.getSortedReturnFieldString();
943

    
944
       // query for finding the id from xml_returnfield
945
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
946
            + "WHERE returnfield_string LIKE ?";
947
       logMetacat.info("ReturnField Query:" + query);
948

    
949
       try {
950
           // prepare and run the query
951
           pstmt = dbconn.prepareStatement(query);
952
           pstmt.setString(1,returnfield);
953
           dbconn.increaseUsageCount(1);
954
           pstmt.execute();
955
           rs = pstmt.getResultSet();
956
           boolean tableHasRows = rs.next();
957

    
958
           // if record found then increase the usage count
959
           // else insert a new record and get the id of the new record
960
           if(tableHasRows){
961
               // get the id
962
               id = rs.getInt(1);
963
               count = rs.getInt(2) + 1;
964
               rs.close();
965
               pstmt.close();
966

    
967
               // increase the usage count
968
               query = "UPDATE xml_returnfield SET usage_count ='" + count
969
                   + "' WHERE returnfield_id ='"+ id +"'";
970
               logMetacat.info("ReturnField Table Update:"+ query);
971

    
972
               pstmt = dbconn.prepareStatement(query);
973
               dbconn.increaseUsageCount(1);
974
               pstmt.execute();
975
               pstmt.close();
976

    
977
           } else {
978
               rs.close();
979
               pstmt.close();
980

    
981
               // insert a new record
982
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
983
                   + "VALUES (?, '1')";
984
               logMetacat.info("ReturnField Table Insert:"+ query);
985
               pstmt = dbconn.prepareStatement(query);
986
               pstmt.setString(1, returnfield);
987
               dbconn.increaseUsageCount(1);
988
               pstmt.execute();
989
               pstmt.close();
990

    
991
               // get the id of the new record
992
               query = "SELECT returnfield_id FROM xml_returnfield "
993
                   + "WHERE returnfield_string LIKE ?";
994
               logMetacat.info("ReturnField query after Insert:" + query);
995
               pstmt = dbconn.prepareStatement(query);
996
               pstmt.setString(1, returnfield);
997

    
998
               dbconn.increaseUsageCount(1);
999
               pstmt.execute();
1000
               rs = pstmt.getResultSet();
1001
               if(rs.next()){
1002
                   id = rs.getInt(1);
1003
               } else {
1004
                   id = -1;
1005
               }
1006
               rs.close();
1007
               pstmt.close();
1008
           }
1009

    
1010
       } catch (Exception e){
1011
           logMetacat.error("Error getting id from xml_returnfield in "
1012
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1013
                                     + e.getMessage());
1014
           id = -1;
1015
       }
1016

    
1017
       returnfield_id = id;
1018
       return count;
1019
   }
1020

    
1021

    
1022
    /*
1023
     * A method to add return field to return doclist hash table
1024
     */
1025
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1026
                                      QuerySpecification qspec,
1027
                                      String user, String[]groups,
1028
                                      DBConnection dbconn, boolean useXMLIndex )
1029
                                      throws Exception
1030
    {
1031
      PreparedStatement pstmt = null;
1032
      ResultSet rs = null;
1033
      String docid = null;
1034
      String fieldname = null;
1035
      String fielddata = null;
1036
      String relation = null;
1037

    
1038
      if (qspec.containsExtendedSQL())
1039
      {
1040
        qspec.setUserName(user);
1041
        qspec.setGroup(groups);
1042
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1043
        Vector results = new Vector();
1044
        Iterator keylist = docListResult.getDocids();
1045
        StringBuffer doclist = new StringBuffer();
1046
        Vector parentidList = new Vector();
1047
        Hashtable returnFieldValue = new Hashtable();
1048
        while (keylist.hasNext())
1049
        {
1050
          doclist.append("'");
1051
          doclist.append((String) keylist.next());
1052
          doclist.append("',");
1053
        }
1054
        if (doclist.length() > 0)
1055
        {
1056
          Hashtable controlPairs = new Hashtable();
1057
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1058
          boolean tableHasRows = false;
1059
          // check if user has permission to see the return field data
1060
          /*String accessControlSQL =
1061
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
1062
          pstmt = dbconn.prepareStatement(accessControlSQL);
1063
          //increase dbconnection usage count
1064
          dbconn.increaseUsageCount(1);
1065
          pstmt.execute();
1066
          rs = pstmt.getResultSet();
1067
          tableHasRows = rs.next();
1068
          while (tableHasRows)
1069
          {
1070
            long startNodeId = rs.getLong(1);
1071
            long endNodeId = rs.getLong(2);
1072
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
1073
            tableHasRows = rs.next();
1074
          }*/
1075

    
1076
           /*double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
1077
           logMetacat.info( "Time for execute access extended query: "
1078
                          + (extendedAccessQueryEnd - extendedQueryStart));*/
1079

    
1080
           String extendedQuery =
1081
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex);
1082
           logMetacat.info("Extended query: " + extendedQuery);
1083

    
1084
           if(extendedQuery != null){
1085
        	   double extendedQueryStart = System.currentTimeMillis() / 1000;
1086
               pstmt = dbconn.prepareStatement(extendedQuery);
1087
               //increase dbconnection usage count
1088
               dbconn.increaseUsageCount(1);
1089
               pstmt.execute();
1090
               rs = pstmt.getResultSet();
1091
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
1092
               logMetacat.warn(
1093
                   "Time to execute extended query: "
1094
                   + (extendedQueryEnd - extendedQueryStart));
1095
               MetaCatUtil.writeDebugToFile(
1096
                       "Execute extended query "
1097
                       + (extendedQueryEnd - extendedQueryStart));
1098
               MetaCatUtil.writeDebugToDelimiteredFile(" "+ (extendedQueryEnd - extendedQueryStart), false);
1099
               tableHasRows = rs.next();
1100
               while (tableHasRows) {
1101
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1102
                   docid = rs.getString(1).trim();
1103
                   fieldname = rs.getString(2);
1104
                   fielddata = rs.getString(3);
1105
                   fielddata = MetaCatUtil.normalize(fielddata);
1106
                   String parentId = rs.getString(4);
1107
                   StringBuffer value = new StringBuffer();
1108

    
1109
                   // if xml_index is used, there would be just one record per nodeid
1110
                   // as xml_index just keeps one entry for each path
1111
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1112
                       // don't need to merger nodedata
1113
                       value.append("<param name=\"");
1114
                       value.append(fieldname);
1115
                       value.append("\">");
1116
                       value.append(fielddata);
1117
                       value.append("</param>");
1118
                       //set returnvalue
1119
                       returnValue.setDocid(docid);
1120
                       returnValue.setFieldValue(fielddata);
1121
                       returnValue.setXMLFieldValue(value.toString());
1122
                       // Store it in hastable
1123
                       putInArray(parentidList, parentId, returnValue);
1124
                   }
1125
                   else {
1126
                       // need to merge nodedata if they have same parent id and
1127
                       // node type is text
1128
                       fielddata = (String) ( (ReturnFieldValue)
1129
                                             getArrayValue(
1130
                           parentidList, parentId)).getFieldValue()
1131
                           + fielddata;
1132
                       value.append("<param name=\"");
1133
                       value.append(fieldname);
1134
                       value.append("\">");
1135
                       value.append(fielddata);
1136
                       value.append("</param>");
1137
                       returnValue.setDocid(docid);
1138
                       returnValue.setFieldValue(fielddata);
1139
                       returnValue.setXMLFieldValue(value.toString());
1140
                       // remove the old return value from paretnidList
1141
                       parentidList.remove(parentId);
1142
                       // store the new return value in parentidlit
1143
                       putInArray(parentidList, parentId, returnValue);
1144
                   }
1145
                   tableHasRows = rs.next();
1146
               } //while
1147
               rs.close();
1148
               pstmt.close();
1149

    
1150
               // put the merger node data info into doclistReult
1151
               Enumeration xmlFieldValue = (getElements(parentidList)).
1152
                   elements();
1153
               while (xmlFieldValue.hasMoreElements()) {
1154
                   ReturnFieldValue object =
1155
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1156
                   docid = object.getDocid();
1157
                   if (docListResult.containsDocid(docid)) {
1158
                       String removedelement = (String) docListResult.
1159
                           remove(docid);
1160
                       docListResult.
1161
                           addResultDocument(new ResultDocument(docid,
1162
                               removedelement + object.getXMLFieldValue()));
1163
                   }
1164
                   else {
1165
                       docListResult.addResultDocument(
1166
                         new ResultDocument(docid, object.getXMLFieldValue()));
1167
                   }
1168
               } //while
1169
               double docListResultEnd = System.currentTimeMillis() / 1000;
1170
               logMetacat.warn(
1171
                   "Time to prepare ResultDocumentSet after"
1172
                   + " execute extended query: "
1173
                   + (docListResultEnd - extendedQueryEnd));
1174
           }
1175

    
1176
         
1177
           
1178
           
1179
       }//if doclist lenght is great than zero
1180

    
1181
     }//if has extended query
1182

    
1183
      return docListResult;
1184
    }//addReturnfield
1185

    
1186
    /*
1187
    * A method to add relationship to return doclist hash table
1188
    */
1189
   private ResultDocumentSet addRelationship(ResultDocumentSet docListResult,
1190
                                     QuerySpecification qspec,
1191
                                     DBConnection dbconn, boolean useXMLIndex )
1192
                                     throws Exception
1193
  {
1194
    PreparedStatement pstmt = null;
1195
    ResultSet rs = null;
1196
    StringBuffer document = null;
1197
    double startRelation = System.currentTimeMillis() / 1000;
1198
    Iterator docidkeys = docListResult.getDocids();
1199
    while (docidkeys.hasNext())
1200
    {
1201
      //String connstring =
1202
      // "metacat://"+util.getOption("server")+"?docid=";
1203
      String connstring = "%docid=";
1204
      String docidkey;
1205
      synchronized(docListResult)
1206
      {
1207
        docidkey = (String) docidkeys.next();
1208
      }
1209
      pstmt = dbconn.prepareStatement(QuerySpecification
1210
                      .printRelationSQL(docidkey));
1211
      pstmt.execute();
1212
      rs = pstmt.getResultSet();
1213
      boolean tableHasRows = rs.next();
1214
      while (tableHasRows)
1215
      {
1216
        String sub = rs.getString(1);
1217
        String rel = rs.getString(2);
1218
        String obj = rs.getString(3);
1219
        String subDT = rs.getString(4);
1220
        String objDT = rs.getString(5);
1221

    
1222
        document = new StringBuffer();
1223
        document.append("<triple>");
1224
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1225
        document.append("</subject>");
1226
        if (subDT != null)
1227
        {
1228
          document.append("<subjectdoctype>").append(subDT);
1229
          document.append("</subjectdoctype>");
1230
        }
1231
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1232
        document.append("</relationship>");
1233
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1234
        document.append("</object>");
1235
        if (objDT != null)
1236
        {
1237
          document.append("<objectdoctype>").append(objDT);
1238
          document.append("</objectdoctype>");
1239
        }
1240
        document.append("</triple>");
1241

    
1242
        String removedelement = (String) docListResult.get(docidkey);
1243
        docListResult.set(docidkey, removedelement+ document.toString());
1244
        tableHasRows = rs.next();
1245
      }//while
1246
      rs.close();
1247
      pstmt.close();
1248
      
1249
    }//while
1250
    double endRelation = System.currentTimeMillis() / 1000;
1251
    logMetacat.warn("Time to add relationship to return fields (part 3 in return fields): "
1252
                             + (endRelation - startRelation));
1253
    MetaCatUtil.writeDebugToFile("-----------------------------------------Add relationship to return field(part3 in return fields): "
1254
            + (endRelation - startRelation));
1255
    MetaCatUtil.writeDebugToDelimiteredFile(" "+ (endRelation - startRelation), false);
1256

    
1257
    return docListResult;
1258
  }//addRelation
1259

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

    
1332

    
1333
    /*
1334
     * A method to search if Vector contains a particular key string
1335
     */
1336
    private boolean containsKey(Vector parentidList, String parentId)
1337
    {
1338

    
1339
        Vector tempVector = null;
1340

    
1341
        for (int count = 0; count < parentidList.size(); count++) {
1342
            tempVector = (Vector) parentidList.get(count);
1343
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1344
        }
1345
        return false;
1346
    }
1347

    
1348
    /*
1349
     * A method to put key and value in Vector
1350
     */
1351
    private void putInArray(Vector parentidList, String key,
1352
            ReturnFieldValue value)
1353
    {
1354

    
1355
        Vector tempVector = null;
1356

    
1357
        for (int count = 0; count < parentidList.size(); count++) {
1358
            tempVector = (Vector) parentidList.get(count);
1359

    
1360
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1361
                tempVector.remove(1);
1362
                tempVector.add(1, value);
1363
                return;
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

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

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

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

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

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

    
2396
        public String getXMLFieldValue()
2397
        {
2398
            return xmlFieldValue;
2399
        }
2400

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