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-07-12 16:56:17 -0700 (Thu, 12 Jul 2007) $'
14
 * '$Revision: 3308 $'
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
    /**
84
     * the main routine used to test the DBQuery utility.
85
     * <p>
86
     * Usage: java DBQuery <xmlfile>
87
     *
88
     * @param xmlfile the filename of the xml file containing the query
89
     */
90
    static public void main(String[] args)
91
    {
92

    
93
        if (args.length < 1) {
94
            System.err.println("Wrong number of arguments!!!");
95
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
96
            return;
97
        } else {
98
            try {
99

    
100
                int i = 0;
101
                boolean showRuntime = false;
102
                boolean useXMLIndex = false;
103
                if (args[i].equals("-t")) {
104
                    showRuntime = true;
105
                    i++;
106
                }
107
                if (args[i].equals("-index")) {
108
                    useXMLIndex = true;
109
                    i++;
110
                }
111
                String xmlfile = args[i];
112

    
113
                // Time the request if asked for
114
                double startTime = System.currentTimeMillis();
115

    
116
                // Open a connection to the database
117
                MetaCatUtil util = new MetaCatUtil();
118
                //Connection dbconn = util.openDBConnection();
119

    
120
                double connTime = System.currentTimeMillis();
121

    
122
                // Execute the query
123
                DBQuery queryobj = new DBQuery();
124
                FileReader xml = new FileReader(new File(xmlfile));
125
                Hashtable nodelist = null;
126
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
127

    
128
                // Print the reulting document listing
129
                StringBuffer result = new StringBuffer();
130
                String document = null;
131
                String docid = null;
132
                result.append("<?xml version=\"1.0\"?>\n");
133
                result.append("<resultset>\n");
134

    
135
                if (!showRuntime) {
136
                    Enumeration doclist = nodelist.keys();
137
                    while (doclist.hasMoreElements()) {
138
                        docid = (String) doclist.nextElement();
139
                        document = (String) nodelist.get(docid);
140
                        result.append("  <document>\n    " + document
141
                                + "\n  </document>\n");
142
                    }
143

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

    
170
            } catch (Exception e) {
171
                System.err.println("Error in DBQuery.main");
172
                System.err.println(e.getMessage());
173
                e.printStackTrace(System.err);
174
            }
175
        }
176
    }
177

    
178
    /**
179
     * construct an instance of the DBQuery class
180
     *
181
     * <p>
182
     * Generally, one would call the findDocuments() routine after creating an
183
     * instance to specify the search query
184
     * </p>
185
     *
186

    
187
     * @param parserName the fully qualified name of a Java class implementing
188
     *            the org.xml.sax.XMLReader interface
189
     */
190
    public DBQuery()
191
    {
192
        String parserName = MetaCatUtil.getOption("saxparser");
193
        this.parserName = parserName;
194
    }
195

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

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

    
236
  }
237

    
238

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

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

    
293

    
294

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

    
318
         // if the user is a moderator, then pass a param to the 
319
         // xsl specifying the fact
320
         if(MetaCatUtil.isModerator(user, groups)){
321
        	 params.put("isModerator", new String[] {"true"});
322
         }
323

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

    
340
      }//else
341

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

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

    
384
    //try to get the cached version first    
385
    Hashtable sessionHash = MetaCatServlet.getSessionHash();
386
    HttpSession sess = (HttpSession)sessionHash.get(sessionid);
387

    
388
    QuerySpecification cachedQuerySpec = null;
389
    if (sess != null)
390
    {
391
    	cachedQuerySpec = (QuerySpecification)sess.getAttribute("query");
392
    }
393
    
394
    resultset.append("<?xml version=\"1.0\"?>\n");
395
    resultset.append("<resultset>\n");
396
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
397
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
398
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
399
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
400

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

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

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

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

    
451
    //default to returning the whole resultset
452
    return resultset;
453
  }//createResultDocuments
454

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

    
498
      /*
499
       * Check the docidOverride Vector
500
       * if defined, we bypass the qspec.printSQL() method
501
       * and contruct a simpler query based on a 
502
       * list of docids rather than a bunch of subselects
503
       */
504
      if ( this.docidOverride.size() == 0 ) {
505
          query = qspec.printSQL(useXMLIndex);
506
      } else {
507
          logMetacat.info("*** docid override " + this.docidOverride.size());
508
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
509
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
510
          for (int i = 0; i < docidOverride.size(); i++) {  
511
              queryBuffer.append("'");
512
              queryBuffer.append( (String)docidOverride.elementAt(i) );
513
              queryBuffer.append("',");
514
          }
515
          // empty string hack 
516
          queryBuffer.append( "'') " );
517
          query = queryBuffer.toString();
518
      } 
519
      String ownerQuery = getOwnerQuery(user);
520
      logMetacat.info("\n\n\n query: " + query);
521
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
522
      // if query is not the owner query, we need to check the permission
523
      // otherwise we don't need (owner has all permission by default)
524
      if (!query.equals(ownerQuery))
525
      {
526
        // set user name and group
527
        qspec.setUserName(user);
528
        qspec.setGroup(groups);
529
        // Get access query
530
        String accessQuery = qspec.getAccessQuery();
531
        if(!query.endsWith("WHERE")){
532
            query = query + accessQuery;
533
        } else {
534
            query = query + accessQuery.substring(4, accessQuery.length());
535
        }
536
        logMetacat.info("\n\n\n final query: " + query);
537
      }
538

    
539
      startTime = System.currentTimeMillis() / 1000;
540
      pstmt = dbconn.prepareStatement(query);
541
      rs = pstmt.executeQuery();
542

    
543
      double queryExecuteTime = System.currentTimeMillis() / 1000;
544
      logMetacat.warn("Time to execute select docid query is "
545
                    + (queryExecuteTime - startTime));
546
      MetaCatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
547
              + (queryExecuteTime - startTime));
548
      MetaCatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
549

    
550
      boolean tableHasRows = rs.next();
551
      
552
      if(pagesize == 0)
553
      { //this makes sure we get all results if there is no paging
554
        pagesize = 99999;
555
        pagestart = 99999;
556
      } 
557
      
558
      int currentIndex = 0;
559
      while (tableHasRows)
560
      {
561
        logMetacat.info("############getting result: " + currentIndex);
562
        docid = rs.getString(1).trim();
563
        logMetacat.info("############processing: " + docid);
564
        docname = rs.getString(2);
565
        doctype = rs.getString(3);
566
        logMetacat.info("############processing: " + doctype);
567
        createDate = rs.getString(4);
568
        updateDate = rs.getString(5);
569
        rev = rs.getInt(6);
570
        
571
         Vector returndocVec = qspec.getReturnDocList();
572
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
573
        {
574
          logMetacat.info("NOT Back tracing now...");
575
           document = new StringBuffer();
576

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

    
667
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
668
     if (out != null)
669
     {
670
         out.println("\n<lastpage>" + lastpage + "</lastpage>\n");
671
     }
672
          
673
     return resultsetBuffer;
674
    }//findReturnDoclist
675

    
676

    
677
    /*
678
     * Send completed search hashtable(part of reulst)to output stream
679
     * and buffer into a buffer stream
680
     */
681
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
682
                                           StringBuffer resultset,
683
                                           PrintWriter out, ResultDocumentSet partOfDoclist,
684
                                           String user, String[]groups,
685
                                       DBConnection dbconn, boolean useXMLIndex)
686
                                       throws Exception
687
   {
688
     double startReturnField = System.currentTimeMillis()/1000;
689
     // check if there is a record in xml_returnfield
690
     // and get the returnfield_id and usage count
691
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
692
     boolean enterRecords = false;
693

    
694
     // get value of xml_returnfield_count
695
     int count = (new Integer(MetaCatUtil
696
                            .getOption("xml_returnfield_count")))
697
                            .intValue();
698

    
699
     // set enterRecords to true if usage_count is more than the offset
700
     // specified in metacat.properties
701
     if(usage_count > count){
702
         enterRecords = true;
703
     }
704

    
705
     if(returnfield_id < 0){
706
         logMetacat.warn("Error in getting returnfield id from"
707
                                  + "xml_returnfield table");
708
         enterRecords = false;
709
     }
710

    
711
     // get the hashtable containing the docids that already in the
712
     // xml_queryresult table
713
     logMetacat.info("size of partOfDoclist before"
714
                             + " docidsInQueryresultTable(): "
715
                             + partOfDoclist.size());
716
     double startGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
717
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
718
                                                        partOfDoclist, dbconn);
719

    
720
     // remove the keys in queryresultDocList from partOfDoclist
721
     Enumeration _keys = queryresultDocList.keys();
722
     while (_keys.hasMoreElements()){
723
         partOfDoclist.remove((String)_keys.nextElement());
724
     }
725
     double endGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
726
     logMetacat.warn("Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
727
          		               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
728
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
729
               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
730
     MetaCatUtil.writeDebugToDelimiteredFile(" " +
731
             (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable),false);
732
     // backup the keys-elements in partOfDoclist to check later
733
     // if the doc entry is indexed yet
734
     Hashtable partOfDoclistBackup = new Hashtable();
735
     Iterator itt = partOfDoclist.getDocids();
736
     while (itt.hasNext()){
737
       Object key = itt.next();
738
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
739
     }
740

    
741
     logMetacat.info("size of partOfDoclist after"
742
                             + " docidsInQueryresultTable(): "
743
                             + partOfDoclist.size());
744

    
745
     //add return fields for the documents in partOfDoclist
746
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
747
                                        dbconn, useXMLIndex);
748
     double endExtendedQuery = System.currentTimeMillis()/1000;
749
     logMetacat.warn("Get fields from index and node table (Part2 in return fields) "
750
        		                                          + (endExtendedQuery - endGetReturnValueFromQueryresultable));
751
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
752
             + (endExtendedQuery - endGetReturnValueFromQueryresultable));
753
     MetaCatUtil.writeDebugToDelimiteredFile(" "
754
             + (endExtendedQuery - endGetReturnValueFromQueryresultable), false);
755
     //add relationship part part docid list for the documents in partOfDocList
756
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
757

    
758
     double startStoreReturnField = System.currentTimeMillis()/1000;
759
     Iterator keys = partOfDoclist.getDocids();
760
     String key = null;
761
     String element = null;
762
     String query = null;
763
     int offset = (new Integer(MetaCatUtil
764
                               .getOption("queryresult_string_length")))
765
                               .intValue();
766
     while (keys.hasNext())
767
     {
768
         key = (String) keys.next();
769
         element = (String)partOfDoclist.get(key);
770

    
771
	 // check if the enterRecords is true, elements is not null, element's
772
         // length is less than the limit of table column and if the document
773
         // has been indexed already
774
         if(enterRecords && element != null
775
		&& element.length() < offset
776
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
777
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
778
                 + "queryresult_string) VALUES (?, ?, ?)";
779

    
780
             PreparedStatement pstmt = null;
781
             pstmt = dbconn.prepareStatement(query);
782
             pstmt.setInt(1, returnfield_id);
783
             pstmt.setString(2, key);
784
             pstmt.setString(3, element);
785

    
786
             dbconn.increaseUsageCount(1);
787
             pstmt.execute();
788
             pstmt.close();
789
         }
790
        
791
         // A string with element
792
         String xmlElement = "  <document>" + element + "</document>";
793

    
794
         //send single element to output
795
         if (out != null)
796
         {
797
             out.println(xmlElement);
798
         }
799
         resultset.append(xmlElement);
800
     }//while
801
     
802
     double endStoreReturnField = System.currentTimeMillis()/1000;
803
     logMetacat.warn("Time to store new return fields into xml_queryresult table (Part4 in return fields) "
804
                   + (endStoreReturnField -startStoreReturnField));
805
     MetaCatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
806
             + (endStoreReturnField -startStoreReturnField));
807
     MetaCatUtil.writeDebugToDelimiteredFile(" "
808
             + (endStoreReturnField -startStoreReturnField), false);
809
     
810
     Enumeration keysE = queryresultDocList.keys();
811
     while (keysE.hasMoreElements())
812
     {
813
         key = (String) keysE.nextElement();
814
         element = (String)queryresultDocList.get(key);
815
         // A string with element
816
         String xmlElement = "  <document>" + element + "</document>";
817
         //send single element to output
818
         if (out != null)
819
         {
820
             out.println(xmlElement);
821
         }
822
         resultset.append(xmlElement);
823
     }//while
824
     double returnFieldTime = System.currentTimeMillis() / 1000;
825
     logMetacat.warn("======Total time to get return fields is: "
826
                           + (returnFieldTime - startReturnField));
827
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------"+
828
    		 "Total to get return fields  "
829
                                   + (returnFieldTime - startReturnField));
830
     MetaCatUtil.writeDebugToDelimiteredFile(" "+ (returnFieldTime - startReturnField), false);
831
     return resultset;
832
 }
833

    
834
   /**
835
    * Get the docids already in xml_queryresult table and corresponding
836
    * queryresultstring as a hashtable
837
    */
838
   private Hashtable docidsInQueryresultTable(int returnfield_id,
839
                                              ResultDocumentSet partOfDoclist,
840
                                              DBConnection dbconn){
841

    
842
         Hashtable returnValue = new Hashtable();
843
         PreparedStatement pstmt = null;
844
         ResultSet rs = null;
845

    
846
         // get partOfDoclist as string for the query
847
         Iterator keylist = partOfDoclist.getDocids();
848
         StringBuffer doclist = new StringBuffer();
849
         while (keylist.hasNext())
850
         {
851
             doclist.append("'");
852
             doclist.append((String) keylist.next());
853
             doclist.append("',");
854
         }//while
855

    
856

    
857
         if (doclist.length() > 0)
858
         {
859
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
860

    
861
             // the query to find out docids from xml_queryresult
862
             String query = "select docid, queryresult_string from "
863
                          + "xml_queryresult where returnfield_id = " +
864
                          returnfield_id +" and docid in ("+ doclist + ")";
865
             logMetacat.info("Query to get docids from xml_queryresult:"
866
                                      + query);
867

    
868
             try {
869
                 // prepare and execute the query
870
                 pstmt = dbconn.prepareStatement(query);
871
                 dbconn.increaseUsageCount(1);
872
                 pstmt.execute();
873
                 rs = pstmt.getResultSet();
874
                 boolean tableHasRows = rs.next();
875
                 while (tableHasRows) {
876
                     // store the returned results in the returnValue hashtable
877
                     String key = rs.getString(1);
878
                     String element = rs.getString(2);
879

    
880
                     if(element != null){
881
                         returnValue.put(key, element);
882
                     } else {
883
                         logMetacat.info("Null elment found ("
884
                         + "DBQuery.docidsInQueryresultTable)");
885
                     }
886
                     tableHasRows = rs.next();
887
                 }
888
                 rs.close();
889
                 pstmt.close();
890
             } catch (Exception e){
891
                 logMetacat.error("Error getting docids from "
892
                                          + "queryresult in "
893
                                          + "DBQuery.docidsInQueryresultTable: "
894
                                          + e.getMessage());
895
              }
896
         }
897
         return returnValue;
898
     }
899

    
900

    
901
   /**
902
    * Method to get id from xml_returnfield table
903
    * for a given query specification
904
    */
905
   private int returnfield_id;
906
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
907
                                           DBConnection dbconn){
908
       int id = -1;
909
       int count = 1;
910
       PreparedStatement pstmt = null;
911
       ResultSet rs = null;
912
       String returnfield = qspec.getSortedReturnFieldString();
913

    
914
       // query for finding the id from xml_returnfield
915
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
916
            + "WHERE returnfield_string LIKE ?";
917
       logMetacat.info("ReturnField Query:" + query);
918

    
919
       try {
920
           // prepare and run the query
921
           pstmt = dbconn.prepareStatement(query);
922
           pstmt.setString(1,returnfield);
923
           dbconn.increaseUsageCount(1);
924
           pstmt.execute();
925
           rs = pstmt.getResultSet();
926
           boolean tableHasRows = rs.next();
927

    
928
           // if record found then increase the usage count
929
           // else insert a new record and get the id of the new record
930
           if(tableHasRows){
931
               // get the id
932
               id = rs.getInt(1);
933
               count = rs.getInt(2) + 1;
934
               rs.close();
935
               pstmt.close();
936

    
937
               // increase the usage count
938
               query = "UPDATE xml_returnfield SET usage_count ='" + count
939
                   + "' WHERE returnfield_id ='"+ id +"'";
940
               logMetacat.info("ReturnField Table Update:"+ query);
941

    
942
               pstmt = dbconn.prepareStatement(query);
943
               dbconn.increaseUsageCount(1);
944
               pstmt.execute();
945
               pstmt.close();
946

    
947
           } else {
948
               rs.close();
949
               pstmt.close();
950

    
951
               // insert a new record
952
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
953
                   + "VALUES (?, '1')";
954
               logMetacat.info("ReturnField Table Insert:"+ query);
955
               pstmt = dbconn.prepareStatement(query);
956
               pstmt.setString(1, returnfield);
957
               dbconn.increaseUsageCount(1);
958
               pstmt.execute();
959
               pstmt.close();
960

    
961
               // get the id of the new record
962
               query = "SELECT returnfield_id FROM xml_returnfield "
963
                   + "WHERE returnfield_string LIKE ?";
964
               logMetacat.info("ReturnField query after Insert:" + query);
965
               pstmt = dbconn.prepareStatement(query);
966
               pstmt.setString(1, returnfield);
967

    
968
               dbconn.increaseUsageCount(1);
969
               pstmt.execute();
970
               rs = pstmt.getResultSet();
971
               if(rs.next()){
972
                   id = rs.getInt(1);
973
               } else {
974
                   id = -1;
975
               }
976
               rs.close();
977
               pstmt.close();
978
           }
979

    
980
       } catch (Exception e){
981
           logMetacat.error("Error getting id from xml_returnfield in "
982
                                     + "DBQuery.getXmlReturnfieldsTableId: "
983
                                     + e.getMessage());
984
           id = -1;
985
       }
986

    
987
       returnfield_id = id;
988
       return count;
989
   }
990

    
991

    
992
    /*
993
     * A method to add return field to return doclist hash table
994
     */
995
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
996
                                      QuerySpecification qspec,
997
                                      String user, String[]groups,
998
                                      DBConnection dbconn, boolean useXMLIndex )
999
                                      throws Exception
1000
    {
1001
      PreparedStatement pstmt = null;
1002
      ResultSet rs = null;
1003
      String docid = null;
1004
      String fieldname = null;
1005
      String fielddata = null;
1006
      String relation = null;
1007

    
1008
      if (qspec.containsExtendedSQL())
1009
      {
1010
        qspec.setUserName(user);
1011
        qspec.setGroup(groups);
1012
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1013
        Vector results = new Vector();
1014
        Iterator keylist = docListResult.getDocids();
1015
        StringBuffer doclist = new StringBuffer();
1016
        Vector parentidList = new Vector();
1017
        Hashtable returnFieldValue = new Hashtable();
1018
        while (keylist.hasNext())
1019
        {
1020
          doclist.append("'");
1021
          doclist.append((String) keylist.next());
1022
          doclist.append("',");
1023
        }
1024
        if (doclist.length() > 0)
1025
        {
1026
          Hashtable controlPairs = new Hashtable();
1027
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1028
          boolean tableHasRows = false;
1029
          // check if user has permission to see the return field data
1030
          /*String accessControlSQL =
1031
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
1032
          pstmt = dbconn.prepareStatement(accessControlSQL);
1033
          //increase dbconnection usage count
1034
          dbconn.increaseUsageCount(1);
1035
          pstmt.execute();
1036
          rs = pstmt.getResultSet();
1037
          tableHasRows = rs.next();
1038
          while (tableHasRows)
1039
          {
1040
            long startNodeId = rs.getLong(1);
1041
            long endNodeId = rs.getLong(2);
1042
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
1043
            tableHasRows = rs.next();
1044
          }*/
1045

    
1046
           /*double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
1047
           logMetacat.info( "Time for execute access extended query: "
1048
                          + (extendedAccessQueryEnd - extendedQueryStart));*/
1049

    
1050
           String extendedQuery =
1051
               qspec.printExtendedSQL(doclist.toString(), useXMLIndex);
1052
           logMetacat.info("Extended query: " + extendedQuery);
1053

    
1054
           if(extendedQuery != null){
1055
        	   double extendedQueryStart = System.currentTimeMillis() / 1000;
1056
               pstmt = dbconn.prepareStatement(extendedQuery);
1057
               //increase dbconnection usage count
1058
               dbconn.increaseUsageCount(1);
1059
               pstmt.execute();
1060
               rs = pstmt.getResultSet();
1061
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
1062
               logMetacat.warn(
1063
                   "Time to execute extended query: "
1064
                   + (extendedQueryEnd - extendedQueryStart));
1065
               MetaCatUtil.writeDebugToFile(
1066
                       "Execute extended query "
1067
                       + (extendedQueryEnd - extendedQueryStart));
1068
               MetaCatUtil.writeDebugToDelimiteredFile(" "+ (extendedQueryEnd - extendedQueryStart), false);
1069
               tableHasRows = rs.next();
1070
               while (tableHasRows) {
1071
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1072
                   docid = rs.getString(1).trim();
1073
                   fieldname = rs.getString(2);
1074
                   fielddata = rs.getString(3);
1075
                   fielddata = MetaCatUtil.normalize(fielddata);
1076
                   String parentId = rs.getString(4);
1077
                   StringBuffer value = new StringBuffer();
1078

    
1079
                   // if xml_index is used, there would be just one record per nodeid
1080
                   // as xml_index just keeps one entry for each path
1081
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1082
                       // don't need to merger nodedata
1083
                       value.append("<param name=\"");
1084
                       value.append(fieldname);
1085
                       value.append("\">");
1086
                       value.append(fielddata);
1087
                       value.append("</param>");
1088
                       //set returnvalue
1089
                       returnValue.setDocid(docid);
1090
                       returnValue.setFieldValue(fielddata);
1091
                       returnValue.setXMLFieldValue(value.toString());
1092
                       // Store it in hastable
1093
                       putInArray(parentidList, parentId, returnValue);
1094
                   }
1095
                   else {
1096
                       // need to merge nodedata if they have same parent id and
1097
                       // node type is text
1098
                       fielddata = (String) ( (ReturnFieldValue)
1099
                                             getArrayValue(
1100
                           parentidList, parentId)).getFieldValue()
1101
                           + fielddata;
1102
                       value.append("<param name=\"");
1103
                       value.append(fieldname);
1104
                       value.append("\">");
1105
                       value.append(fielddata);
1106
                       value.append("</param>");
1107
                       returnValue.setDocid(docid);
1108
                       returnValue.setFieldValue(fielddata);
1109
                       returnValue.setXMLFieldValue(value.toString());
1110
                       // remove the old return value from paretnidList
1111
                       parentidList.remove(parentId);
1112
                       // store the new return value in parentidlit
1113
                       putInArray(parentidList, parentId, returnValue);
1114
                   }
1115
                   tableHasRows = rs.next();
1116
               } //while
1117
               rs.close();
1118
               pstmt.close();
1119

    
1120
               // put the merger node data info into doclistReult
1121
               Enumeration xmlFieldValue = (getElements(parentidList)).
1122
                   elements();
1123
               while (xmlFieldValue.hasMoreElements()) {
1124
                   ReturnFieldValue object =
1125
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1126
                   docid = object.getDocid();
1127
                   if (docListResult.containsDocid(docid)) {
1128
                       String removedelement = (String) docListResult.
1129
                           remove(docid);
1130
                       docListResult.
1131
                           addResultDocument(new ResultDocument(docid,
1132
                               removedelement + object.getXMLFieldValue()));
1133
                   }
1134
                   else {
1135
                       docListResult.addResultDocument(
1136
                         new ResultDocument(docid, object.getXMLFieldValue()));
1137
                   }
1138
               } //while
1139
               double docListResultEnd = System.currentTimeMillis() / 1000;
1140
               logMetacat.warn(
1141
                   "Time to prepare ResultDocumentSet after"
1142
                   + " execute extended query: "
1143
                   + (docListResultEnd - extendedQueryEnd));
1144
           }
1145

    
1146
         
1147
           
1148
           
1149
       }//if doclist lenght is great than zero
1150

    
1151
     }//if has extended query
1152

    
1153
      return docListResult;
1154
    }//addReturnfield
1155

    
1156
    /*
1157
    * A method to add relationship to return doclist hash table
1158
    */
1159
   private ResultDocumentSet addRelationship(ResultDocumentSet docListResult,
1160
                                     QuerySpecification qspec,
1161
                                     DBConnection dbconn, boolean useXMLIndex )
1162
                                     throws Exception
1163
  {
1164
    PreparedStatement pstmt = null;
1165
    ResultSet rs = null;
1166
    StringBuffer document = null;
1167
    double startRelation = System.currentTimeMillis() / 1000;
1168
    Iterator docidkeys = docListResult.getDocids();
1169
    while (docidkeys.hasNext())
1170
    {
1171
      //String connstring =
1172
      // "metacat://"+util.getOption("server")+"?docid=";
1173
      String connstring = "%docid=";
1174
      String docidkey;
1175
      synchronized(docListResult)
1176
      {
1177
        docidkey = (String) docidkeys.next();
1178
      }
1179
      pstmt = dbconn.prepareStatement(QuerySpecification
1180
                      .printRelationSQL(docidkey));
1181
      pstmt.execute();
1182
      rs = pstmt.getResultSet();
1183
      boolean tableHasRows = rs.next();
1184
      while (tableHasRows)
1185
      {
1186
        String sub = rs.getString(1);
1187
        String rel = rs.getString(2);
1188
        String obj = rs.getString(3);
1189
        String subDT = rs.getString(4);
1190
        String objDT = rs.getString(5);
1191

    
1192
        document = new StringBuffer();
1193
        document.append("<triple>");
1194
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1195
        document.append("</subject>");
1196
        if (subDT != null)
1197
        {
1198
          document.append("<subjectdoctype>").append(subDT);
1199
          document.append("</subjectdoctype>");
1200
        }
1201
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1202
        document.append("</relationship>");
1203
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1204
        document.append("</object>");
1205
        if (objDT != null)
1206
        {
1207
          document.append("<objectdoctype>").append(objDT);
1208
          document.append("</objectdoctype>");
1209
        }
1210
        document.append("</triple>");
1211

    
1212
        String removedelement = (String) docListResult.get(docidkey);
1213
        docListResult.set(docidkey, removedelement+ document.toString());
1214
        tableHasRows = rs.next();
1215
      }//while
1216
      rs.close();
1217
      pstmt.close();
1218
      
1219
    }//while
1220
    double endRelation = System.currentTimeMillis() / 1000;
1221
    logMetacat.warn("Time to add relationship to return fields (part 3 in return fields): "
1222
                             + (endRelation - startRelation));
1223
    MetaCatUtil.writeDebugToFile("-----------------------------------------Add relationship to return field(part3 in return fields): "
1224
            + (endRelation - startRelation));
1225
    MetaCatUtil.writeDebugToDelimiteredFile(" "+ (endRelation - startRelation), false);
1226

    
1227
    return docListResult;
1228
  }//addRelation
1229

    
1230
  /**
1231
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1232
   * string as a param instead of a hashtable.
1233
   *
1234
   * @param xmlquery a string representing a query.
1235
   */
1236
   private  String transformQuery(String xmlquery)
1237
   {
1238
     xmlquery = xmlquery.trim();
1239
     int index = xmlquery.indexOf("?>");
1240
     if (index != -1)
1241
     {
1242
       return xmlquery.substring(index + 2, xmlquery.length());
1243
     }
1244
     else
1245
     {
1246
       return xmlquery;
1247
     }
1248
   }
1249

    
1250

    
1251
    /*
1252
     * A method to search if Vector contains a particular key string
1253
     */
1254
    private boolean containsKey(Vector parentidList, String parentId)
1255
    {
1256

    
1257
        Vector tempVector = null;
1258

    
1259
        for (int count = 0; count < parentidList.size(); count++) {
1260
            tempVector = (Vector) parentidList.get(count);
1261
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1262
        }
1263
        return false;
1264
    }
1265

    
1266
    /*
1267
     * A method to put key and value in Vector
1268
     */
1269
    private void putInArray(Vector parentidList, String key,
1270
            ReturnFieldValue value)
1271
    {
1272

    
1273
        Vector tempVector = null;
1274

    
1275
        for (int count = 0; count < parentidList.size(); count++) {
1276
            tempVector = (Vector) parentidList.get(count);
1277

    
1278
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1279
                tempVector.remove(1);
1280
                tempVector.add(1, value);
1281
                return;
1282
            }
1283
        }
1284

    
1285
        tempVector = new Vector();
1286
        tempVector.add(0, key);
1287
        tempVector.add(1, value);
1288
        parentidList.add(tempVector);
1289
        return;
1290
    }
1291

    
1292
    /*
1293
     * A method to get value in Vector given a key
1294
     */
1295
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1296
    {
1297

    
1298
        Vector tempVector = null;
1299

    
1300
        for (int count = 0; count < parentidList.size(); count++) {
1301
            tempVector = (Vector) parentidList.get(count);
1302

    
1303
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1304
                    .get(1); }
1305
        }
1306
        return null;
1307
    }
1308

    
1309
    /*
1310
     * A method to get enumeration of all values in Vector
1311
     */
1312
    private Vector getElements(Vector parentidList)
1313
    {
1314
        Vector enumVector = new Vector();
1315
        Vector tempVector = null;
1316

    
1317
        for (int count = 0; count < parentidList.size(); count++) {
1318
            tempVector = (Vector) parentidList.get(count);
1319

    
1320
            enumVector.add(tempVector.get(1));
1321
        }
1322
        return enumVector;
1323
    }
1324

    
1325
  
1326

    
1327
    /*
1328
     * A method to create a query to get owner's docid list
1329
     */
1330
    private String getOwnerQuery(String owner)
1331
    {
1332
        if (owner != null) {
1333
            owner = owner.toLowerCase();
1334
        }
1335
        StringBuffer self = new StringBuffer();
1336

    
1337
        self.append("SELECT docid,docname,doctype,");
1338
        self.append("date_created, date_updated, rev ");
1339
        self.append("FROM xml_documents WHERE docid IN (");
1340
        self.append("(");
1341
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1342
        self.append("nodedata LIKE '%%%' ");
1343
        self.append(") \n");
1344
        self.append(") ");
1345
        self.append(" AND (");
1346
        self.append(" lower(user_owner) = '" + owner + "'");
1347
        self.append(") ");
1348
        return self.toString();
1349
    }
1350

    
1351
    /**
1352
     * format a structured query as an XML document that conforms to the
1353
     * pathquery.dtd and is appropriate for submission to the DBQuery
1354
     * structured query engine
1355
     *
1356
     * @param params The list of parameters that should be included in the
1357
     *            query
1358
     */
1359
    public static String createSQuery(Hashtable params)
1360
    {
1361
        StringBuffer query = new StringBuffer();
1362
        Enumeration elements;
1363
        Enumeration keys;
1364
        String filterDoctype = null;
1365
        String casesensitive = null;
1366
        String searchmode = null;
1367
        Object nextkey;
1368
        Object nextelement;
1369
        //add the xml headers
1370
        query.append("<?xml version=\"1.0\"?>\n");
1371
        query.append("<pathquery version=\"1.2\">\n");
1372

    
1373

    
1374

    
1375
        if (params.containsKey("meta_file_id")) {
1376
            query.append("<meta_file_id>");
1377
            query.append(((String[]) params.get("meta_file_id"))[0]);
1378
            query.append("</meta_file_id>");
1379
        }
1380

    
1381
        if (params.containsKey("returndoctype")) {
1382
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1383
            for (int i = 0; i < returnDoctypes.length; i++) {
1384
                String doctype = (String) returnDoctypes[i];
1385

    
1386
                if (!doctype.equals("any") && !doctype.equals("ANY")
1387
                        && !doctype.equals("")) {
1388
                    query.append("<returndoctype>").append(doctype);
1389
                    query.append("</returndoctype>");
1390
                }
1391
            }
1392
        }
1393

    
1394
        if (params.containsKey("filterdoctype")) {
1395
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1396
            for (int i = 0; i < filterDoctypes.length; i++) {
1397
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1398
                query.append("</filterdoctype>");
1399
            }
1400
        }
1401

    
1402
        if (params.containsKey("returnfield")) {
1403
            String[] returnfield = ((String[]) params.get("returnfield"));
1404
            for (int i = 0; i < returnfield.length; i++) {
1405
                query.append("<returnfield>").append(returnfield[i]);
1406
                query.append("</returnfield>");
1407
            }
1408
        }
1409

    
1410
        if (params.containsKey("owner")) {
1411
            String[] owner = ((String[]) params.get("owner"));
1412
            for (int i = 0; i < owner.length; i++) {
1413
                query.append("<owner>").append(owner[i]);
1414
                query.append("</owner>");
1415
            }
1416
        }
1417

    
1418
        if (params.containsKey("site")) {
1419
            String[] site = ((String[]) params.get("site"));
1420
            for (int i = 0; i < site.length; i++) {
1421
                query.append("<site>").append(site[i]);
1422
                query.append("</site>");
1423
            }
1424
        }
1425

    
1426
        //allows the dynamic switching of boolean operators
1427
        if (params.containsKey("operator")) {
1428
            query.append("<querygroup operator=\""
1429
                    + ((String[]) params.get("operator"))[0] + "\">");
1430
        } else { //the default operator is UNION
1431
            query.append("<querygroup operator=\"UNION\">");
1432
        }
1433

    
1434
        if (params.containsKey("casesensitive")) {
1435
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1436
        } else {
1437
            casesensitive = "false";
1438
        }
1439

    
1440
        if (params.containsKey("searchmode")) {
1441
            searchmode = ((String[]) params.get("searchmode"))[0];
1442
        } else {
1443
            searchmode = "contains";
1444
        }
1445

    
1446
        //anyfield is a special case because it does a
1447
        //free text search. It does not have a <pathexpr>
1448
        //tag. This allows for a free text search within the structured
1449
        //query. This is useful if the INTERSECT operator is used.
1450
        if (params.containsKey("anyfield")) {
1451
            String[] anyfield = ((String[]) params.get("anyfield"));
1452
            //allow for more than one value for anyfield
1453
            for (int i = 0; i < anyfield.length; i++) {
1454
                if (!anyfield[i].equals("")) {
1455
                    query.append("<queryterm casesensitive=\"" + casesensitive
1456
                            + "\" " + "searchmode=\"" + searchmode
1457
                            + "\"><value>" + anyfield[i]
1458
                            + "</value></queryterm>");
1459
                }
1460
            }
1461
        }
1462

    
1463
        //this while loop finds the rest of the parameters
1464
        //and attempts to query for the field specified
1465
        //by the parameter.
1466
        elements = params.elements();
1467
        keys = params.keys();
1468
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1469
            nextkey = keys.nextElement();
1470
            nextelement = elements.nextElement();
1471

    
1472
            //make sure we aren't querying for any of these
1473
            //parameters since the are already in the query
1474
            //in one form or another.
1475
            Vector ignoredParams = new Vector();
1476
            ignoredParams.add("returndoctype");
1477
            ignoredParams.add("filterdoctype");
1478
            ignoredParams.add("action");
1479
            ignoredParams.add("qformat");
1480
            ignoredParams.add("anyfield");
1481
            ignoredParams.add("returnfield");
1482
            ignoredParams.add("owner");
1483
            ignoredParams.add("site");
1484
            ignoredParams.add("operator");
1485
            ignoredParams.add("sessionid");
1486
            ignoredParams.add("pagesize");
1487
            ignoredParams.add("pagestart");
1488

    
1489
            // Also ignore parameters listed in the properties file
1490
            // so that they can be passed through to stylesheets
1491
            String paramsToIgnore = MetaCatUtil
1492
                    .getOption("query.ignored.params");
1493
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1494
            while (st.hasMoreTokens()) {
1495
                ignoredParams.add(st.nextToken());
1496
            }
1497
            if (!ignoredParams.contains(nextkey.toString())) {
1498
                //allow for more than value per field name
1499
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1500
                    if (!((String[]) nextelement)[i].equals("")) {
1501
                        query.append("<queryterm casesensitive=\""
1502
                                + casesensitive + "\" " + "searchmode=\""
1503
                                + searchmode + "\">" + "<value>" +
1504
                                //add the query value
1505
                                ((String[]) nextelement)[i]
1506
                                + "</value><pathexpr>" +
1507
                                //add the path to query by
1508
                                nextkey.toString() + "</pathexpr></queryterm>");
1509
                    }
1510
                }
1511
            }
1512
        }
1513
        query.append("</querygroup></pathquery>");
1514
        //append on the end of the xml and return the result as a string
1515
        return query.toString();
1516
    }
1517

    
1518
    /**
1519
     * format a simple free-text value query as an XML document that conforms
1520
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1521
     * structured query engine
1522
     *
1523
     * @param value the text string to search for in the xml catalog
1524
     * @param doctype the type of documents to include in the result set -- use
1525
     *            "any" or "ANY" for unfiltered result sets
1526
     */
1527
    public static String createQuery(String value, String doctype)
1528
    {
1529
        StringBuffer xmlquery = new StringBuffer();
1530
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1531
        xmlquery.append("<pathquery version=\"1.0\">");
1532

    
1533
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1534
            xmlquery.append("<returndoctype>");
1535
            xmlquery.append(doctype).append("</returndoctype>");
1536
        }
1537

    
1538
        xmlquery.append("<querygroup operator=\"UNION\">");
1539
        //chad added - 8/14
1540
        //the if statement allows a query to gracefully handle a null
1541
        //query. Without this if a nullpointerException is thrown.
1542
        if (!value.equals("")) {
1543
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1544
            xmlquery.append("searchmode=\"contains\">");
1545
            xmlquery.append("<value>").append(value).append("</value>");
1546
            xmlquery.append("</queryterm>");
1547
        }
1548
        xmlquery.append("</querygroup>");
1549
        xmlquery.append("</pathquery>");
1550

    
1551
        return (xmlquery.toString());
1552
    }
1553

    
1554
    /**
1555
     * format a simple free-text value query as an XML document that conforms
1556
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1557
     * structured query engine
1558
     *
1559
     * @param value the text string to search for in the xml catalog
1560
     */
1561
    public static String createQuery(String value)
1562
    {
1563
        return createQuery(value, "any");
1564
    }
1565

    
1566
    /**
1567
     * Check for "READ" permission on @docid for @user and/or @group from DB
1568
     * connection
1569
     */
1570
    private boolean hasPermission(String user, String[] groups, String docid)
1571
            throws SQLException, Exception
1572
    {
1573
        // Check for READ permission on @docid for @user and/or @groups
1574
        PermissionController controller = new PermissionController(docid);
1575
        return controller.hasPermission(user, groups,
1576
                AccessControlInterface.READSTRING);
1577
    }
1578

    
1579
    /**
1580
     * Get all docIds list for a data packadge
1581
     *
1582
     * @param dataPackageDocid, the string in docId field of xml_relation table
1583
     */
1584
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1585
    {
1586
        DBConnection dbConn = null;
1587
        int serialNumber = -1;
1588
        Vector docIdList = new Vector();//return value
1589
        PreparedStatement pStmt = null;
1590
        ResultSet rs = null;
1591
        String docIdInSubjectField = null;
1592
        String docIdInObjectField = null;
1593

    
1594
        // Check the parameter
1595
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1596

    
1597
        //the query stirng
1598
        String query = "SELECT subject, object from xml_relation where docId = ?";
1599
        try {
1600
            dbConn = DBConnectionPool
1601
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1602
            serialNumber = dbConn.getCheckOutSerialNumber();
1603
            pStmt = dbConn.prepareStatement(query);
1604
            //bind the value to query
1605
            pStmt.setString(1, dataPackageDocid);
1606

    
1607
            //excute the query
1608
            pStmt.execute();
1609
            //get the result set
1610
            rs = pStmt.getResultSet();
1611
            //process the result
1612
            while (rs.next()) {
1613
                //In order to get the whole docIds in a data packadge,
1614
                //we need to put the docIds of subject and object field in
1615
                // xml_relation
1616
                //into the return vector
1617
                docIdInSubjectField = rs.getString(1);//the result docId in
1618
                                                      // subject field
1619
                docIdInObjectField = rs.getString(2);//the result docId in
1620
                                                     // object field
1621

    
1622
                //don't put the duplicate docId into the vector
1623
                if (!docIdList.contains(docIdInSubjectField)) {
1624
                    docIdList.add(docIdInSubjectField);
1625
                }
1626

    
1627
                //don't put the duplicate docId into the vector
1628
                if (!docIdList.contains(docIdInObjectField)) {
1629
                    docIdList.add(docIdInObjectField);
1630
                }
1631
            }//while
1632
            //close the pStmt
1633
            pStmt.close();
1634
        }//try
1635
        catch (SQLException e) {
1636
            logMetacat.error("Error in getDocidListForDataPackage: "
1637
                    + e.getMessage());
1638
        }//catch
1639
        finally {
1640
            try {
1641
                pStmt.close();
1642
            }//try
1643
            catch (SQLException ee) {
1644
                logMetacat.error(
1645
                        "Error in getDocidListForDataPackage: "
1646
                                + ee.getMessage());
1647
            }//catch
1648
            finally {
1649
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1650
            }//fianlly
1651
        }//finally
1652
        return docIdList;
1653
    }//getCurrentDocidListForDataPackadge()
1654

    
1655
    /**
1656
     * Get all docIds list for a data packadge
1657
     *
1658
     * @param dataPackageDocid, the string in docId field of xml_relation table
1659
     */
1660
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1661
    {
1662

    
1663
        Vector docIdList = new Vector();//return value
1664
        Vector tripleList = null;
1665
        String xml = null;
1666

    
1667
        // Check the parameter
1668
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1669

    
1670
        try {
1671
            //initial a documentImpl object
1672
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1673
            //transfer to documentImpl object to string
1674
            xml = packageDocument.toString();
1675

    
1676
            //create a tripcollection object
1677
            TripleCollection tripleForPackage = new TripleCollection(
1678
                    new StringReader(xml));
1679
            //get the vetor of triples
1680
            tripleList = tripleForPackage.getCollection();
1681

    
1682
            for (int i = 0; i < tripleList.size(); i++) {
1683
                //put subject docid into docIdlist without duplicate
1684
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1685
                        .getSubject())) {
1686
                    //put subject docid into docIdlist
1687
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1688
                }
1689
                //put object docid into docIdlist without duplicate
1690
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1691
                        .getObject())) {
1692
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1693
                }
1694
            }//for
1695
        }//try
1696
        catch (Exception e) {
1697
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1698
                    + e.getMessage());
1699
        }//catch
1700

    
1701
        // return result
1702
        return docIdList;
1703
    }//getDocidListForPackageInXMLRevisions()
1704

    
1705
    /**
1706
     * Check if the docId is a data packadge id. If the id is a data packadage
1707
     * id, it should be store in the docId fields in xml_relation table. So we
1708
     * can use a query to get the entries which the docId equals the given
1709
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1710
     * it is.
1711
     *
1712
     * @param docId, the id need to be checked
1713
     */
1714
    private boolean isDataPackageId(String docId)
1715
    {
1716
        boolean result = false;
1717
        PreparedStatement pStmt = null;
1718
        ResultSet rs = null;
1719
        String query = "SELECT docId from xml_relation where docId = ?";
1720
        DBConnection dbConn = null;
1721
        int serialNumber = -1;
1722
        try {
1723
            dbConn = DBConnectionPool
1724
                    .getDBConnection("DBQuery.isDataPackageId");
1725
            serialNumber = dbConn.getCheckOutSerialNumber();
1726
            pStmt = dbConn.prepareStatement(query);
1727
            //bind the value to query
1728
            pStmt.setString(1, docId);
1729
            //execute the query
1730
            pStmt.execute();
1731
            rs = pStmt.getResultSet();
1732
            //process the result
1733
            if (rs.next()) //There are some records for the id in docId fields
1734
            {
1735
                result = true;//It is a data packadge id
1736
            }
1737
            pStmt.close();
1738
        }//try
1739
        catch (SQLException e) {
1740
            logMetacat.error("Error in isDataPackageId: "
1741
                    + e.getMessage());
1742
        } finally {
1743
            try {
1744
                pStmt.close();
1745
            }//try
1746
            catch (SQLException ee) {
1747
                logMetacat.error("Error in isDataPackageId: "
1748
                        + ee.getMessage());
1749
            }//catch
1750
            finally {
1751
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1752
            }//finally
1753
        }//finally
1754
        return result;
1755
    }//isDataPackageId()
1756

    
1757
    /**
1758
     * Check if the user has the permission to export data package
1759
     *
1760
     * @param conn, the connection
1761
     * @param docId, the id need to be checked
1762
     * @param user, the name of user
1763
     * @param groups, the user's group
1764
     */
1765
    private boolean hasPermissionToExportPackage(String docId, String user,
1766
            String[] groups) throws Exception
1767
    {
1768
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1769
        return DocumentImpl.hasReadPermission(user, groups, docId);
1770
    }
1771

    
1772
    /**
1773
     * Get the current Rev for a docid in xml_documents table
1774
     *
1775
     * @param docId, the id need to get version numb If the return value is -5,
1776
     *            means no value in rev field for this docid
1777
     */
1778
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1779
            throws SQLException
1780
    {
1781
        int rev = -5;
1782
        PreparedStatement pStmt = null;
1783
        ResultSet rs = null;
1784
        String query = "SELECT rev from xml_documents where docId = ?";
1785
        DBConnection dbConn = null;
1786
        int serialNumber = -1;
1787
        try {
1788
            dbConn = DBConnectionPool
1789
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1790
            serialNumber = dbConn.getCheckOutSerialNumber();
1791
            pStmt = dbConn.prepareStatement(query);
1792
            //bind the value to query
1793
            pStmt.setString(1, docId);
1794
            //execute the query
1795
            pStmt.execute();
1796
            rs = pStmt.getResultSet();
1797
            //process the result
1798
            if (rs.next()) //There are some records for rev
1799
            {
1800
                rev = rs.getInt(1);
1801
                ;//It is the version for given docid
1802
            } else {
1803
                rev = -5;
1804
            }
1805

    
1806
        }//try
1807
        catch (SQLException e) {
1808
            logMetacat.error(
1809
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1810
                            + e.getMessage());
1811
            throw e;
1812
        }//catch
1813
        finally {
1814
            try {
1815
                pStmt.close();
1816
            }//try
1817
            catch (SQLException ee) {
1818
                logMetacat.error(
1819
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1820
                                + ee.getMessage());
1821
            }//catch
1822
            finally {
1823
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1824
            }//finally
1825
        }//finally
1826
        return rev;
1827
    }//getCurrentRevFromXMLDoumentsTable
1828

    
1829
    /**
1830
     * put a doc into a zip output stream
1831
     *
1832
     * @param docImpl, docmentImpl object which will be sent to zip output
1833
     *            stream
1834
     * @param zipOut, zip output stream which the docImpl will be put
1835
     * @param packageZipEntry, the zip entry name for whole package
1836
     */
1837
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1838
            ZipOutputStream zipOut, String packageZipEntry)
1839
            throws ClassNotFoundException, IOException, SQLException,
1840
            McdbException, Exception
1841
    {
1842
        byte[] byteString = null;
1843
        ZipEntry zEntry = null;
1844

    
1845
        byteString = docImpl.toString().getBytes();
1846
        //use docId as the zip entry's name
1847
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1848
                + docImpl.getDocID());
1849
        zEntry.setSize(byteString.length);
1850
        zipOut.putNextEntry(zEntry);
1851
        zipOut.write(byteString, 0, byteString.length);
1852
        zipOut.closeEntry();
1853

    
1854
    }//addDocToZipOutputStream()
1855

    
1856
    /**
1857
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1858
     * only inlcudes current version. If a DocumentImple object couldn't find
1859
     * for a docid, then the String of this docid was added to vetor rather
1860
     * than DocumentImple object.
1861
     *
1862
     * @param docIdList, a vetor hold a docid list for a data package. In
1863
     *            docid, there is not version number in it.
1864
     */
1865

    
1866
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1867
            throws McdbException, Exception
1868
    {
1869
        //Connection dbConn=null;
1870
        Vector documentImplList = new Vector();
1871
        int rev = 0;
1872

    
1873
        // Check the parameter
1874
        if (docIdList.isEmpty()) { return documentImplList; }//if
1875

    
1876
        //for every docid in vector
1877
        for (int i = 0; i < docIdList.size(); i++) {
1878
            try {
1879
                //get newest version for this docId
1880
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1881
                        .elementAt(i));
1882

    
1883
                // There is no record for this docId in xml_documents table
1884
                if (rev == -5) {
1885
                    // Rather than put DocumentImple object, put a String
1886
                    // Object(docid)
1887
                    // into the documentImplList
1888
                    documentImplList.add((String) docIdList.elementAt(i));
1889
                    // Skip other code
1890
                    continue;
1891
                }
1892

    
1893
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1894
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1895

    
1896
                //create new documentImpl object
1897
                DocumentImpl documentImplObject = new DocumentImpl(
1898
                        docidPlusVersion);
1899
                //add them to vector
1900
                documentImplList.add(documentImplObject);
1901
            }//try
1902
            catch (Exception e) {
1903
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
1904
                        + e.getMessage());
1905
                // continue the for loop
1906
                continue;
1907
            }
1908
        }//for
1909
        return documentImplList;
1910
    }
1911

    
1912
    /**
1913
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
1914
     * object couldn't find for a docid, then the String of this docid was
1915
     * added to vetor rather than DocumentImple object.
1916
     *
1917
     * @param docIdList, a vetor hold a docid list for a data package. In
1918
     *            docid, t here is version number in it.
1919
     */
1920
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
1921
    {
1922
        //Connection dbConn=null;
1923
        Vector documentImplList = new Vector();
1924
        String siteCode = null;
1925
        String uniqueId = null;
1926
        int rev = 0;
1927

    
1928
        // Check the parameter
1929
        if (docIdList.isEmpty()) { return documentImplList; }//if
1930

    
1931
        //for every docid in vector
1932
        for (int i = 0; i < docIdList.size(); i++) {
1933

    
1934
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1935

    
1936
            try {
1937
                //create new documentImpl object
1938
                DocumentImpl documentImplObject = new DocumentImpl(
1939
                        docidPlusVersion);
1940
                //add them to vector
1941
                documentImplList.add(documentImplObject);
1942
            }//try
1943
            catch (McdbDocNotFoundException notFoundE) {
1944
                logMetacat.error(
1945
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1946
                                + notFoundE.getMessage());
1947
                // Rather than add a DocumentImple object into vetor, a String
1948
                // object
1949
                // - the doicd was added to the vector
1950
                documentImplList.add(docidPlusVersion);
1951
                // Continue the for loop
1952
                continue;
1953
            }//catch
1954
            catch (Exception e) {
1955
                logMetacat.error(
1956
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1957
                                + e.getMessage());
1958
                // Continue the for loop
1959
                continue;
1960
            }//catch
1961

    
1962
        }//for
1963
        return documentImplList;
1964
    }//getOldVersionAllDocumentImple
1965

    
1966
    /**
1967
     * put a data file into a zip output stream
1968
     *
1969
     * @param docImpl, docmentImpl object which will be sent to zip output
1970
     *            stream
1971
     * @param zipOut, the zip output stream which the docImpl will be put
1972
     * @param packageZipEntry, the zip entry name for whole package
1973
     */
1974
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
1975
            ZipOutputStream zipOut, String packageZipEntry)
1976
            throws ClassNotFoundException, IOException, SQLException,
1977
            McdbException, Exception
1978
    {
1979
        byte[] byteString = null;
1980
        ZipEntry zEntry = null;
1981
        // this is data file; add file to zip
1982
        String filePath = MetaCatUtil.getOption("datafilepath");
1983
        if (!filePath.endsWith("/")) {
1984
            filePath += "/";
1985
        }
1986
        String fileName = filePath + docImpl.getDocID();
1987
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
1988
        zipOut.putNextEntry(zEntry);
1989
        FileInputStream fin = null;
1990
        try {
1991
            fin = new FileInputStream(fileName);
1992
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1993
            int b = fin.read(buf);
1994
            while (b != -1) {
1995
                zipOut.write(buf, 0, b);
1996
                b = fin.read(buf);
1997
            }//while
1998
            zipOut.closeEntry();
1999
        }//try
2000
        catch (IOException ioe) {
2001
            logMetacat.error("There is an exception: "
2002
                    + ioe.getMessage());
2003
        }//catch
2004
    }//addDataFileToZipOutputStream()
2005

    
2006
    /**
2007
     * create a html summary for data package and put it into zip output stream
2008
     *
2009
     * @param docImplList, the documentImpl ojbects in data package
2010
     * @param zipOut, the zip output stream which the html should be put
2011
     * @param packageZipEntry, the zip entry name for whole package
2012
     */
2013
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2014
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2015
    {
2016
        StringBuffer htmlDoc = new StringBuffer();
2017
        ZipEntry zEntry = null;
2018
        byte[] byteString = null;
2019
        InputStream source;
2020
        DBTransform xmlToHtml;
2021

    
2022
        //create a DBTransform ojbect
2023
        xmlToHtml = new DBTransform();
2024
        //head of html
2025
        htmlDoc.append("<html><head></head><body>");
2026
        for (int i = 0; i < docImplList.size(); i++) {
2027
            // If this String object, this means it is missed data file
2028
            if ((((docImplList.elementAt(i)).getClass()).toString())
2029
                    .equals("class java.lang.String")) {
2030

    
2031
                htmlDoc.append("<a href=\"");
2032
                String dataFileid = (String) docImplList.elementAt(i);
2033
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2034
                htmlDoc.append("Data File: ");
2035
                htmlDoc.append(dataFileid).append("</a><br>");
2036
                htmlDoc.append("<br><hr><br>");
2037

    
2038
            }//if
2039
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2040
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2041
                                              // transform it.
2042
                //transform each file individually then concatenate all of the
2043
                //transformations together.
2044

    
2045
                //for metadata xml title
2046
                htmlDoc.append("<h2>");
2047
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2048
                        .getDocID());
2049
                //htmlDoc.append(".");
2050
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2051
                htmlDoc.append("</h2>");
2052
                //do the actual transform
2053
                StringWriter docString = new StringWriter();
2054
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2055
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2056
                        "-//W3C//HTML//EN", "html", docString);
2057
                htmlDoc.append(docString.toString());
2058
                htmlDoc.append("<br><br><hr><br><br>");
2059
            }//if
2060
            else { //this is a data file so we should link to it in the html
2061
                htmlDoc.append("<a href=\"");
2062
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2063
                        .getDocID();
2064
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2065
                htmlDoc.append("Data File: ");
2066
                htmlDoc.append(dataFileid).append("</a><br>");
2067
                htmlDoc.append("<br><hr><br>");
2068
            }//else
2069
        }//for
2070
        htmlDoc.append("</body></html>");
2071
        byteString = htmlDoc.toString().getBytes();
2072
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2073
        zEntry.setSize(byteString.length);
2074
        zipOut.putNextEntry(zEntry);
2075
        zipOut.write(byteString, 0, byteString.length);
2076
        zipOut.closeEntry();
2077
        //dbConn.close();
2078

    
2079
    }//addHtmlSummaryToZipOutputStream
2080

    
2081
    /**
2082
     * put a data packadge into a zip output stream
2083
     *
2084
     * @param docId, which the user want to put into zip output stream,it has version
2085
     * @param out, a servletoutput stream which the zip output stream will be
2086
     *            put
2087
     * @param user, the username of the user
2088
     * @param groups, the group of the user
2089
     */
2090
    public ZipOutputStream getZippedPackage(String docIdString,
2091
            ServletOutputStream out, String user, String[] groups,
2092
            String passWord) throws ClassNotFoundException, IOException,
2093
            SQLException, McdbException, NumberFormatException, Exception
2094
    {
2095
        ZipOutputStream zOut = null;
2096
        String elementDocid = null;
2097
        DocumentImpl docImpls = null;
2098
        //Connection dbConn = null;
2099
        Vector docIdList = new Vector();
2100
        Vector documentImplList = new Vector();
2101
        Vector htmlDocumentImplList = new Vector();
2102
        String packageId = null;
2103
        String rootName = "package";//the package zip entry name
2104

    
2105
        String docId = null;
2106
        int version = -5;
2107
        // Docid without revision
2108
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2109
        // revision number
2110
        version = MetaCatUtil.getVersionFromString(docIdString);
2111

    
2112
        //check if the reqused docId is a data package id
2113
        if (!isDataPackageId(docId)) {
2114

    
2115
            /*
2116
             * Exception e = new Exception("The request the doc id "
2117
             * +docIdString+ " is not a data package id");
2118
             */
2119

    
2120
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2121
            // zip
2122
            //up the single document and return the zip file.
2123
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2124

    
2125
                Exception e = new Exception("User " + user
2126
                        + " does not have permission"
2127
                        + " to export the data package " + docIdString);
2128
                throw e;
2129
            }
2130

    
2131
            docImpls = new DocumentImpl(docIdString);
2132
            //checking if the user has the permission to read the documents
2133
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2134
                    .getDocID())) {
2135
                zOut = new ZipOutputStream(out);
2136
                //if the docImpls is metadata
2137
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2138
                    //add metadata into zip output stream
2139
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2140
                }//if
2141
                else {
2142
                    //it is data file
2143
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2144
                    htmlDocumentImplList.add(docImpls);
2145
                }//else
2146
            }//if
2147

    
2148
            zOut.finish(); //terminate the zip file
2149
            return zOut;
2150
        }
2151
        // Check the permission of user
2152
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2153

    
2154
            Exception e = new Exception("User " + user
2155
                    + " does not have permission"
2156
                    + " to export the data package " + docIdString);
2157
            throw e;
2158
        } else //it is a packadge id
2159
        {
2160
            //store the package id
2161
            packageId = docId;
2162
            //get current version in database
2163
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2164
            //If it is for current version (-1 means user didn't specify
2165
            // revision)
2166
            if ((version == -1) || version == currentVersion) {
2167
                //get current version number
2168
                version = currentVersion;
2169
                //get package zip entry name
2170
                //it should be docId.revsion.package
2171
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2172
                        + version + MetaCatUtil.getOption("accNumSeparator")
2173
                        + "package";
2174
                //get the whole id list for data packadge
2175
                docIdList = getCurrentDocidListForDataPackage(packageId);
2176
                //get the whole documentImple object
2177
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2178

    
2179
            }//if
2180
            else if (version > currentVersion || version < -1) {
2181
                throw new Exception("The user specified docid: " + docId + "."
2182
                        + version + " doesn't exist");
2183
            }//else if
2184
            else //for an old version
2185
            {
2186

    
2187
                rootName = docIdString
2188
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2189
                //get the whole id list for data packadge
2190
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2191

    
2192
                //get the whole documentImple object
2193
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2194
            }//else
2195

    
2196
            // Make sure documentImplist is not empty
2197
            if (documentImplList.isEmpty()) { throw new Exception(
2198
                    "Couldn't find component for data package: " + packageId); }//if
2199

    
2200
            zOut = new ZipOutputStream(out);
2201
            //put every element into zip output stream
2202
            for (int i = 0; i < documentImplList.size(); i++) {
2203
                // if the object in the vetor is String, this means we couldn't
2204
                // find
2205
                // the document locally, we need find it remote
2206
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2207
                        .equals("class java.lang.String")) {
2208
                    // Get String object from vetor
2209
                    String documentId = (String) documentImplList.elementAt(i);
2210
                    logMetacat.info("docid: " + documentId);
2211
                    // Get doicd without revision
2212
                    String docidWithoutRevision = MetaCatUtil
2213
                            .getDocIdFromString(documentId);
2214
                    logMetacat.info("docidWithoutRevsion: "
2215
                            + docidWithoutRevision);
2216
                    // Get revision
2217
                    String revision = MetaCatUtil
2218
                            .getRevisionStringFromString(documentId);
2219
                    logMetacat.info("revsion from docIdentifier: "
2220
                            + revision);
2221
                    // Zip entry string
2222
                    String zipEntryPath = rootName + "/data/";
2223
                    // Create a RemoteDocument object
2224
                    RemoteDocument remoteDoc = new RemoteDocument(
2225
                            docidWithoutRevision, revision, user, passWord,
2226
                            zipEntryPath);
2227
                    // Here we only read data file from remote metacat
2228
                    String docType = remoteDoc.getDocType();
2229
                    if (docType != null) {
2230
                        if (docType.equals("BIN")) {
2231
                            // Put remote document to zip output
2232
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2233
                            // Add String object to htmlDocumentImplList
2234
                            String elementInHtmlList = remoteDoc
2235
                                    .getDocIdWithoutRevsion()
2236
                                    + MetaCatUtil.getOption("accNumSeparator")
2237
                                    + remoteDoc.getRevision();
2238
                            htmlDocumentImplList.add(elementInHtmlList);
2239
                        }//if
2240
                    }//if
2241

    
2242
                }//if
2243
                else {
2244
                    //create a docmentImpls object (represent xml doc) base on
2245
                    // the docId
2246
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2247
                    //checking if the user has the permission to read the
2248
                    // documents
2249
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2250
                            .getDocID())) {
2251
                        //if the docImpls is metadata
2252
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2253
                            //add metadata into zip output stream
2254
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2255
                            //add the documentImpl into the vetor which will
2256
                            // be used in html
2257
                            htmlDocumentImplList.add(docImpls);
2258

    
2259
                        }//if
2260
                        else {
2261
                            //it is data file
2262
                            addDataFileToZipOutputStream(docImpls, zOut,
2263
                                    rootName);
2264
                            htmlDocumentImplList.add(docImpls);
2265
                        }//else
2266
                    }//if
2267
                }//else
2268
            }//for
2269

    
2270
            //add html summary file
2271
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2272
                    rootName);
2273
            zOut.finish(); //terminate the zip file
2274
            //dbConn.close();
2275
            return zOut;
2276
        }//else
2277
    }//getZippedPackage()
2278

    
2279
    private class ReturnFieldValue
2280
    {
2281

    
2282
        private String docid = null; //return field value for this docid
2283

    
2284
        private String fieldValue = null;
2285

    
2286
        private String xmlFieldValue = null; //return field value in xml
2287
                                             // format
2288

    
2289
        public void setDocid(String myDocid)
2290
        {
2291
            docid = myDocid;
2292
        }
2293

    
2294
        public String getDocid()
2295
        {
2296
            return docid;
2297
        }
2298

    
2299
        public void setFieldValue(String myValue)
2300
        {
2301
            fieldValue = myValue;
2302
        }
2303

    
2304
        public String getFieldValue()
2305
        {
2306
            return fieldValue;
2307
        }
2308

    
2309
        public void setXMLFieldValue(String xml)
2310
        {
2311
            xmlFieldValue = xml;
2312
        }
2313

    
2314
        public String getXMLFieldValue()
2315
        {
2316
            return xmlFieldValue;
2317
        }
2318

    
2319
    }
2320
    
2321
    /**
2322
     * a class to store one result document consisting of a docid and a document
2323
     */
2324
    private class ResultDocument
2325
    {
2326
      public String docid;
2327
      public String document;
2328
      
2329
      public ResultDocument(String docid, String document)
2330
      {
2331
        this.docid = docid;
2332
        this.document = document;
2333
      }
2334
    }
2335
    
2336
    /**
2337
     * a private class to handle a set of resultDocuments
2338
     */
2339
    private class ResultDocumentSet
2340
    {
2341
      private Vector docids;
2342
      private Vector documents;
2343
      
2344
      public ResultDocumentSet()
2345
      {
2346
        docids = new Vector();
2347
        documents = new Vector();
2348
      }
2349
      
2350
      /**
2351
       * adds a result document to the set
2352
       */
2353
      public void addResultDocument(ResultDocument rd)
2354
      {
2355
        if(rd.docid == null)
2356
          return;
2357
        if(rd.document == null)
2358
          rd.document = "";
2359
        if (!containsDocid(rd.docid))
2360
        {
2361
           docids.addElement(rd.docid);
2362
           documents.addElement(rd.document);
2363
        }
2364
      }
2365
      
2366
      /**
2367
       * gets an iterator of docids
2368
       */
2369
      public Iterator getDocids()
2370
      {
2371
        return docids.iterator();
2372
      }
2373
      
2374
      /**
2375
       * gets an iterator of documents
2376
       */
2377
      public Iterator getDocuments()
2378
      {
2379
        return documents.iterator();
2380
      }
2381
      
2382
      /**
2383
       * returns the size of the set
2384
       */
2385
      public int size()
2386
      {
2387
        return docids.size();
2388
      }
2389
      
2390
      /**
2391
       * tests to see if this set contains the given docid
2392
       */
2393
      public boolean containsDocid(String docid)
2394
      {
2395
        for(int i=0; i<docids.size(); i++)
2396
        {
2397
          String docid0 = (String)docids.elementAt(i);
2398
          if(docid0.trim().equals(docid.trim()))
2399
          {
2400
            return true;
2401
          }
2402
        }
2403
        return false;
2404
      }
2405
      
2406
      /**
2407
       * removes the element with the given docid
2408
       */
2409
      public String remove(String docid)
2410
      {
2411
        for(int i=0; i<docids.size(); i++)
2412
        {
2413
          String docid0 = (String)docids.elementAt(i);
2414
          if(docid0.trim().equals(docid.trim()))
2415
          {
2416
            String returnDoc = (String)documents.elementAt(i);
2417
            documents.remove(i);
2418
            docids.remove(i);
2419
            return returnDoc;
2420
          }
2421
        }
2422
        return null;
2423
      }
2424
      
2425
      /**
2426
       * add a result document
2427
       */
2428
      public void put(ResultDocument rd)
2429
      {
2430
        addResultDocument(rd);
2431
      }
2432
      
2433
      /**
2434
       * add a result document by components
2435
       */
2436
      public void put(String docid, String document)
2437
      {
2438
        addResultDocument(new ResultDocument(docid, document));
2439
      }
2440
      
2441
      /**
2442
       * get the document part of the result document by docid
2443
       */
2444
      public Object get(String docid)
2445
      {
2446
        for(int i=0; i<docids.size(); i++)
2447
        {
2448
          String docid0 = (String)docids.elementAt(i);
2449
          if(docid0.trim().equals(docid.trim()))
2450
          {
2451
            return documents.elementAt(i);
2452
          }
2453
        }
2454
        return null;
2455
      }
2456
      
2457
      /**
2458
       * get the document part of the result document by an object
2459
       */
2460
      public Object get(Object o)
2461
      {
2462
        return get((String)o);
2463
      }
2464
      
2465
      /**
2466
       * get an entire result document by index number
2467
       */
2468
      public ResultDocument get(int index)
2469
      {
2470
        return new ResultDocument((String)docids.elementAt(index), 
2471
          (String)documents.elementAt(index));
2472
      }
2473
      
2474
      /**
2475
       * return a string representation of this object
2476
       */
2477
      public String toString()
2478
      {
2479
        String s = "";
2480
        for(int i=0; i<docids.size(); i++)
2481
        {
2482
          s += (String)docids.elementAt(i) + "\n";
2483
        }
2484
        return s;
2485
      }
2486
      /*
2487
       * Set a new document value for a given docid
2488
       */
2489
      public void set(String docid, String document)
2490
      {
2491
    	   for(int i=0; i<docids.size(); i++)
2492
           {
2493
             String docid0 = (String)docids.elementAt(i);
2494
             if(docid0.trim().equals(docid.trim()))
2495
             {
2496
                 documents.set(i, document);
2497
             }
2498
           }
2499
           
2500
      }
2501
    }
2502
}
(21-21/66)