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: perry $'
13
 *     '$Date: 2006-11-29 17:40:19 -0800 (Wed, 29 Nov 2006) $'
14
 * '$Revision: 3104 $'
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.BufferedWriter;
34
import java.io.File;
35
import java.io.FileInputStream;
36
import java.io.FileReader;
37
import java.io.FileWriter;
38
import java.io.IOException;
39
import java.io.InputStream;
40
import java.io.PrintWriter;
41
import java.io.StringReader;
42
import java.io.StringWriter;
43
import java.sql.PreparedStatement;
44
import java.sql.ResultSet;
45
import java.sql.SQLException;
46
import java.util.Enumeration;
47
import java.util.Hashtable;
48
import java.util.StringTokenizer;
49
import java.util.Vector;
50
import java.util.zip.ZipEntry;
51
import java.util.zip.ZipOutputStream;
52

    
53
import javax.servlet.ServletOutputStream;
54
import javax.servlet.http.HttpServletResponse;
55

    
56
import org.apache.log4j.Logger;
57

    
58
import edu.ucsb.nceas.morpho.datapackage.Triple;
59
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
60

    
61

    
62
/**
63
 * A Class that searches a relational DB for elements and attributes that have
64
 * free text matches a query string, or structured query matches to a path
65
 * specified node in the XML hierarchy. It returns a result set consisting of
66
 * the document ID for each document that satisfies the query
67
 */
68
public class DBQuery
69
{
70

    
71
    static final int ALL = 1;
72

    
73
    static final int WRITE = 2;
74

    
75
    static final int READ = 4;
76

    
77
    //private Connection conn = null;
78
    private String parserName = null;
79

    
80
    private MetaCatUtil util = new MetaCatUtil();
81

    
82
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
83

    
84
    /** true if the metacat spatial option is installed **/
85
    private final boolean METACAT_SPATIAL = true;
86

    
87
    /** useful if you just want to grab a list of docids **/
88
    Vector docidOverride = new Vector();
89

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

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

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

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

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

    
127
                double connTime = System.currentTimeMillis();
128

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

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

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

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

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

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

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

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

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

    
243
  }
244

    
245

    
246
    /**
247
     * Method put the search result set into out printerwriter
248
     * @param resoponse the return response
249
     * @param out the output printer
250
     * @param params the paratermer hashtable
251
     * @param user the user name (it maybe different to the one in param)
252
     * @param groups the group array
253
     * @param sessionid  the sessionid
254
     */
255
    public void findDocuments(HttpServletResponse response,
256
                                         PrintWriter out, Hashtable params,
257
                                         String user, String[] groups,
258
                                         String sessionid, boolean useXMLIndex)
259
    {
260
      // get query and qformat
261
      String xmlquery = ((String[])params.get("query"))[0];
262

    
263
      logMetacat.warn("xmlquery: " + xmlquery);
264
      String qformat = ((String[])params.get("qformat"))[0];
265
      logMetacat.warn("qformat: " + qformat);
266
      // Get the XML query and covert it into a SQL statment
267
      QuerySpecification qspec = null;
268
      if ( xmlquery != null)
269
      {
270
         xmlquery = transformQuery(xmlquery);
271
         try
272
         {
273
           qspec = new QuerySpecification(xmlquery,
274
                                          parserName,
275
                                          MetaCatUtil.getOption("accNumSeparator"));
276
         }
277
         catch (Exception ee)
278
         {
279
           logMetacat.error("error generating QuerySpecification object"
280
                                    +" in DBQuery.findDocuments"
281
                                    + ee.getMessage());
282
         }
283
      }
284

    
285

    
286

    
287
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
288
      {
289
        //xml format
290
        response.setContentType("text/xml");
291
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex);
292
      }//if
293
      else
294
      {
295
        //knb format, in this case we will get whole result and sent it out
296
        response.setContentType("text/html");
297
        PrintWriter nonout = null;
298
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
299
                                                groups, useXMLIndex);
300
        
301
        //transfer the xml to html
302
        try
303
        {
304

    
305
         DBTransform trans = new DBTransform();
306
         response.setContentType("text/html");
307

    
308
	 // if the user is a moderator, then pass a param to the 
309
         // xsl specifying the fact
310
         if(MetaCatUtil.isModerator(user, groups)){
311
        	 params.put("isModerator", new String[] {"true"});
312
         }
313

    
314
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
315
                                 "-//W3C//HTML//EN", qformat, out, params,
316
                                 sessionid);
317

    
318
        }
319
        catch(Exception e)
320
        {
321
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
322
                                +e.getMessage());
323
         }
324

    
325
      }//else
326

    
327
    }
328

    
329
  /*
330
   * Transforms a hashtable of documents to an xml or html result and sent
331
   * the content to outputstream. Keep going untill hastable is empty. stop it.
332
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
333
   * to xmlquery String
334
   */
335
  public StringBuffer createResultDocument(String xmlquery,
336
                                            QuerySpecification qspec,
337
                                            PrintWriter out,
338
                                            String user, String[] groups,
339
                                            boolean useXMLIndex)
340
  {
341
    DBConnection dbconn = null;
342
    int serialNumber = -1;
343
    StringBuffer resultset = new StringBuffer();
344
    resultset.append("<?xml version=\"1.0\"?>\n");
345
    resultset.append("<resultset>\n");
346
    resultset.append("  <query>" + xmlquery + "</query>");
347
    // sent query part out
348
    if (out != null)
349
    {
350
      out.println(resultset.toString());
351
    }
352
    if (qspec != null)
353
    {
354
      try
355
      {
356

    
357
        //checkout the dbconnection
358
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
359
        serialNumber = dbconn.getCheckOutSerialNumber();
360

    
361
        //print out the search result
362
        // search the doc list
363
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
364
                                      dbconn, useXMLIndex);
365

    
366
        
367

    
368
      } //try
369
      catch (IOException ioe)
370
      {
371
        logMetacat.error("IO error in DBQuery.findDocuments:");
372
        logMetacat.error(ioe.getMessage());
373

    
374
      }
375
      catch (SQLException e)
376
      {
377
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
378
                                 + e.getMessage());
379
      }
380
      catch (Exception ee)
381
      {
382
        logMetacat.error("Exception in DBQuery.findDocuments: "
383
                                 + ee.getMessage());
384
      }
385
      finally
386
      {
387
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
388
      } //finally
389
    }//if
390
    String closeRestultset = "</resultset>";
391
    resultset.append(closeRestultset);
392
    if (out != null)
393
    {
394
      out.println(closeRestultset);
395
    }
396

    
397
    return resultset;
398
  }//createResultDocuments
399

    
400

    
401

    
402
    /*
403
     * Find the doc list which match the query
404
     */
405
    private StringBuffer findResultDoclist(QuerySpecification qspec,
406
                                      StringBuffer resultsetBuffer,
407
                                      PrintWriter out,
408
                                      String user, String[]groups,
409
                                      DBConnection dbconn, boolean useXMLIndex )
410
                                      throws Exception
411
    {
412
      
413
      int offset = 1;
414
      // this is a hack for offset
415
      if (out == null)
416
      {
417
        // for html page, we put everything into one page
418
        offset =
419
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
420
      }
421
      else
422
      {
423
          offset =
424
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
425
      }
426

    
427
      int count = 0;
428
      int index = 0;
429
      Hashtable docListResult = new Hashtable();
430
      PreparedStatement pstmt = null;
431
      String docid = null;
432
      String docname = null;
433
      String doctype = null;
434
      String createDate = null;
435
      String updateDate = null;
436
      StringBuffer document = null;
437
      int rev = 0;
438

    
439
      String query = null;
440

    
441
      /*
442
       * Check the docidOverride Vector
443
       * if defined, we bypass the qspec.printSQL() method
444
       * and contruct a simpler query based on a 
445
       * list of docids rather than a bunch of subselects
446
       */
447
      if ( this.docidOverride.size() == 0 ) {
448
          query = qspec.printSQL(useXMLIndex);
449
      } else {
450
          logMetacat.info("*** docid override " + this.docidOverride.size());
451
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
452
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
453
          for (int i = 0; i < docidOverride.size(); i++) {  
454
              queryBuffer.append("'");
455
              queryBuffer.append( (String)docidOverride.elementAt(i) );
456
              queryBuffer.append("',");
457
          }
458
          // empty string hack 
459
          queryBuffer.append( "'') " );
460
          query = queryBuffer.toString();
461
      } 
462

    
463
      String ownerQuery = getOwnerQuery(user);
464
      logMetacat.info("\n\n\n query: " + query);
465
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
466
      // if query is not the owner query, we need to check the permission
467
      // otherwise we don't need (owner has all permission by default)
468
      if (!query.equals(ownerQuery))
469
      {
470
        // set user name and group
471
        qspec.setUserName(user);
472
        qspec.setGroup(groups);
473
        // Get access query
474
        String accessQuery = qspec.getAccessQuery();
475
        if(!query.endsWith("WHERE")){
476
            query = query + accessQuery;
477
        } else {
478
            query = query + accessQuery.substring(4, accessQuery.length());
479
        }
480
        logMetacat.warn("\n\n\n final query: " + query);
481
      }
482

    
483
      double startTime = System.currentTimeMillis() / 1000;
484
      pstmt = dbconn.prepareStatement(query);
485

    
486
      // Execute the SQL query using the JDBC connection
487
      pstmt.execute();
488
      ResultSet rs = pstmt.getResultSet();
489
      double queryExecuteTime = System.currentTimeMillis() / 1000;
490
      logMetacat.warn("Time for execute query: "
491
                    + (queryExecuteTime - startTime));
492
      boolean tableHasRows = rs.next();
493
      while (tableHasRows)
494
      {
495
        docid = rs.getString(1).trim();
496
        docname = rs.getString(2);
497
        doctype = rs.getString(3);
498
        createDate = rs.getString(4);
499
        updateDate = rs.getString(5);
500
        rev = rs.getInt(6);
501

    
502
        // if there are returndocs to match, backtracking can be performed
503
        // otherwise, just return the document that was hit
504
        Vector returndocVec = qspec.getReturnDocList();
505
         if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
506
                        && !qspec.isPercentageSearch())
507
        {
508
           logMetacat.warn("Back tracing now...");
509
           String sep = MetaCatUtil.getOption("accNumSeparator");
510
           StringBuffer btBuf = new StringBuffer();
511
           btBuf.append("select docid from xml_relation where ");
512

    
513
           //build the doctype list for the backtracking sql statement
514
           btBuf.append("packagetype in (");
515
           for (int i = 0; i < returndocVec.size(); i++)
516
           {
517
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
518
             if (i != (returndocVec.size() - 1))
519
             {
520
                btBuf.append(", ");
521
              }
522
            }
523
            btBuf.append(") ");
524
            btBuf.append("and (subject like '");
525
            btBuf.append(docid).append("'");
526
            btBuf.append("or object like '");
527
            btBuf.append(docid).append("')");
528

    
529
            PreparedStatement npstmt = dbconn.prepareStatement(btBuf.toString());
530
            //should incease usage count
531
            dbconn.increaseUsageCount(1);
532
            npstmt.execute();
533
            ResultSet btrs = npstmt.getResultSet();
534
            boolean hasBtRows = btrs.next();
535
            while (hasBtRows)
536
            {
537
               //there was a backtrackable document found
538
               DocumentImpl xmldoc = null;
539
               String packageDocid = btrs.getString(1);
540
               logMetacat.info("Getting document for docid: "
541
                                         + packageDocid);
542
                try
543
                {
544
                    //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not
545
                    // needed here
546
                    // xmldoc = new DocumentImpl(dbconn, packageDocid);
547
                    //  thus use the following to get the doc info only
548
                    //  xmldoc = new DocumentImpl(dbconn);
549
                    String accNumber = packageDocid + MetaCatUtil.getOption("accNumSeparator") +
550
                    DBUtil.getLatestRevisionInDocumentTable(packageDocid);
551
                    xmldoc = new DocumentImpl(accNumber, false);
552
                    if (xmldoc == null)
553
                    {
554
                       logMetacat.info("Document was null for: "
555
                                                + packageDocid);
556
                    }
557
                }
558
                catch (Exception e)
559
                {
560
                    System.out.println("Error getting document in "
561
                                       + "DBQuery.findDocuments: "
562
                                       + e.getMessage());
563
                }
564

    
565
                String docid_org = xmldoc.getDocID();
566
                if (docid_org == null)
567
                {
568
                   logMetacat.info("Docid_org was null.");
569
                   //continue;
570
                }
571
                docid = docid_org.trim();
572
                docname = xmldoc.getDocname();
573
                doctype = xmldoc.getDoctype();
574
                createDate = xmldoc.getCreateDate();
575
                updateDate = xmldoc.getUpdateDate();
576
                rev = xmldoc.getRev();
577
                document = new StringBuffer();
578

    
579
                String completeDocid = docid
580
                                + MetaCatUtil.getOption("accNumSeparator");
581
                completeDocid += rev;
582
                document.append("<docid>").append(completeDocid);
583
                document.append("</docid>");
584
                if (docname != null)
585
                {
586
                  document.append("<docname>" + docname + "</docname>");
587
                }
588
                if (doctype != null)
589
                {
590
                  document.append("<doctype>" + doctype + "</doctype>");
591
                }
592
                if (createDate != null)
593
                {
594
                 document.append("<createdate>" + createDate + "</createdate>");
595
                }
596
                if (updateDate != null)
597
                {
598
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
599
                }
600
                // Store the document id and the root node id
601
                docListResult.put(docid, (String) document.toString());
602
                count++;
603

    
604

    
605
                // Get the next package document linked to our hit
606
                hasBtRows = btrs.next();
607
              }//while
608
              npstmt.close();
609
              btrs.close();
610
        }
611
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
612
        {
613

    
614
           document = new StringBuffer();
615

    
616
           String completeDocid = docid
617
                            + MetaCatUtil.getOption("accNumSeparator");
618
           completeDocid += rev;
619
           document.append("<docid>").append(completeDocid).append("</docid>");
620
           if (docname != null)
621
           {
622
               document.append("<docname>" + docname + "</docname>");
623
            }
624
            if (doctype != null)
625
            {
626
               document.append("<doctype>" + doctype + "</doctype>");
627
            }
628
            if (createDate != null)
629
            {
630
                document.append("<createdate>" + createDate + "</createdate>");
631
             }
632
             if (updateDate != null)
633
             {
634
               document.append("<updatedate>" + updateDate + "</updatedate>");
635
             }
636
              // Store the document id and the root node id
637
              docListResult.put(docid, (String) document.toString());
638
              count++;
639

    
640

    
641
        }//else
642
        // when doclist reached the offset number, send out doc list and empty
643
        // the hash table
644
        if (count == offset)
645
        {
646
          //reset count
647
          count = 0;
648
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
649
                              user, groups,dbconn, useXMLIndex);
650
          // reset docListResult
651
          docListResult = new Hashtable();
652

    
653
        }
654
       // Advance to the next record in the cursor
655
       tableHasRows = rs.next();
656
     }//while
657
     rs.close();
658
     pstmt.close();
659
     //if docListResult is not empty, it need to be sent.
660
     if (!docListResult.isEmpty())
661
     {
662
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
663
                              user, groups,dbconn, useXMLIndex);
664
     }
665
     double docListTime = System.currentTimeMillis() / 1000;
666
     logMetacat.warn("prepare docid list time: "
667
                    + (docListTime - queryExecuteTime));
668

    
669

    
670
     return resultsetBuffer;
671
    }//findReturnDoclist
672

    
673

    
674
    /*
675
     * Send completed search hashtable(part of reulst)to output stream
676
     * and buffer into a buffer stream
677
     */
678
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
679
                                           StringBuffer resultset,
680
                                           PrintWriter out, Hashtable partOfDoclist,
681
                                           String user, String[]groups,
682
                                       DBConnection dbconn, boolean useXMLIndex)
683
                                       throws Exception
684
   {
685

    
686
     // check if there is a record in xml_returnfield
687
     // and get the returnfield_id and usage count
688
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
689
     boolean enterRecords = false;
690

    
691
     // get value of xml_returnfield_count
692
     int count = (new Integer(MetaCatUtil
693
                            .getOption("xml_returnfield_count")))
694
                            .intValue();
695

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

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

    
708
     // get the hashtable containing the docids that already in the
709
     // xml_queryresult table
710
     logMetacat.info("size of partOfDoclist before"
711
                             + " docidsInQueryresultTable(): "
712
                             + partOfDoclist.size());
713
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
714
                                                        partOfDoclist, dbconn);
715

    
716
     // remove the keys in queryresultDocList from partOfDoclist
717
     Enumeration _keys = queryresultDocList.keys();
718
     while (_keys.hasMoreElements()){
719
         partOfDoclist.remove(_keys.nextElement());
720
     }
721

    
722
     // backup the keys-elements in partOfDoclist to check later
723
     // if the doc entry is indexed yet
724
     Hashtable partOfDoclistBackup = new Hashtable();
725
     _keys = partOfDoclist.keys();
726
     while (_keys.hasMoreElements()){
727
	 Object key = _keys.nextElement();
728
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
729
     }
730

    
731
     logMetacat.info("size of partOfDoclist after"
732
                             + " docidsInQueryresultTable(): "
733
                             + partOfDoclist.size());
734

    
735
     //add return fields for the documents in partOfDoclist
736
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
737
                                        dbconn, useXMLIndex );
738
     //add relationship part part docid list for the documents in partOfDocList
739
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
740

    
741

    
742
     Enumeration keys = partOfDoclist.keys();
743
     String key = null;
744
     String element = null;
745
     String query = null;
746
     int offset = (new Integer(MetaCatUtil
747
                               .getOption("queryresult_string_length")))
748
                               .intValue();
749
     while (keys.hasMoreElements())
750
     {
751
         key = (String) keys.nextElement();
752
         element = (String)partOfDoclist.get(key);
753

    
754
	 // check if the enterRecords is true, elements is not null, element's
755
         // length is less than the limit of table column and if the document
756
         // has been indexed already
757
         if(enterRecords && element != null
758
		&& element.length() < offset
759
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
760
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
761
                 + "queryresult_string) VALUES (?, ?, ?)";
762

    
763
             PreparedStatement pstmt = null;
764
             pstmt = dbconn.prepareStatement(query);
765
             pstmt.setInt(1, returnfield_id);
766
             pstmt.setString(2, key);
767
             pstmt.setString(3, element);
768

    
769
             dbconn.increaseUsageCount(1);
770
             pstmt.execute();
771
             pstmt.close();
772
         }
773

    
774
         // A string with element
775
         String xmlElement = "  <document>" + element + "</document>";
776

    
777
         //send single element to output
778
         if (out != null)
779
         {
780
             out.println(xmlElement);
781
         }
782
         resultset.append(xmlElement);
783
     }//while
784

    
785

    
786
     keys = queryresultDocList.keys();
787
     while (keys.hasMoreElements())
788
     {
789
         key = (String) keys.nextElement();
790
         element = (String)queryresultDocList.get(key);
791
         // A string with element
792
         String xmlElement = "  <document>" + element + "</document>";
793
         //send single element to output
794
         if (out != null)
795
         {
796
             out.println(xmlElement);
797
         }
798
         resultset.append(xmlElement);
799
     }//while
800

    
801
     return resultset;
802
 }
803

    
804
   /**
805
    * Get the docids already in xml_queryresult table and corresponding
806
    * queryresultstring as a hashtable
807
    */
808
   private Hashtable docidsInQueryresultTable(int returnfield_id,
809
                                              Hashtable partOfDoclist,
810
                                              DBConnection dbconn){
811

    
812
         Hashtable returnValue = new Hashtable();
813
         PreparedStatement pstmt = null;
814
         ResultSet rs = null;
815

    
816
         // get partOfDoclist as string for the query
817
         Enumeration keylist = partOfDoclist.keys();
818
         StringBuffer doclist = new StringBuffer();
819
         while (keylist.hasMoreElements())
820
         {
821
             doclist.append("'");
822
             doclist.append((String) keylist.nextElement());
823
             doclist.append("',");
824
         }//while
825

    
826

    
827
         if (doclist.length() > 0)
828
         {
829
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
830

    
831
             // the query to find out docids from xml_queryresult
832
             String query = "select docid, queryresult_string from "
833
                          + "xml_queryresult where returnfield_id = " +
834
                          returnfield_id +" and docid in ("+ doclist + ")";
835
             logMetacat.info("Query to get docids from xml_queryresult:"
836
                                      + query);
837

    
838
             try {
839
                 // prepare and execute the query
840
                 pstmt = dbconn.prepareStatement(query);
841
                 dbconn.increaseUsageCount(1);
842
                 pstmt.execute();
843
                 rs = pstmt.getResultSet();
844
                 boolean tableHasRows = rs.next();
845
                 while (tableHasRows) {
846
                     // store the returned results in the returnValue hashtable
847
                     String key = rs.getString(1);
848
                     String element = rs.getString(2);
849

    
850
                     if(element != null){
851
                         returnValue.put(key, element);
852
                     } else {
853
                         logMetacat.info("Null elment found ("
854
                         + "DBQuery.docidsInQueryresultTable)");
855
                     }
856
                     tableHasRows = rs.next();
857
                 }
858
                 rs.close();
859
                 pstmt.close();
860
             } catch (Exception e){
861
                 logMetacat.error("Error getting docids from "
862
                                          + "queryresult in "
863
                                          + "DBQuery.docidsInQueryresultTable: "
864
                                          + e.getMessage());
865
              }
866
         }
867
         return returnValue;
868
     }
869

    
870

    
871
   /**
872
    * Method to get id from xml_returnfield table
873
    * for a given query specification
874
    */
875
   private int returnfield_id;
876
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
877
                                           DBConnection dbconn){
878
       int id = -1;
879
       int count = 1;
880
       PreparedStatement pstmt = null;
881
       ResultSet rs = null;
882
       String returnfield = qspec.getSortedReturnFieldString();
883

    
884
       // query for finding the id from xml_returnfield
885
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
886
            + "WHERE returnfield_string LIKE ?";
887
       logMetacat.info("ReturnField Query:" + query);
888

    
889
       try {
890
           // prepare and run the query
891
           pstmt = dbconn.prepareStatement(query);
892
           pstmt.setString(1,returnfield);
893
           dbconn.increaseUsageCount(1);
894
           pstmt.execute();
895
           rs = pstmt.getResultSet();
896
           boolean tableHasRows = rs.next();
897

    
898
           // if record found then increase the usage count
899
           // else insert a new record and get the id of the new record
900
           if(tableHasRows){
901
               // get the id
902
               id = rs.getInt(1);
903
               count = rs.getInt(2) + 1;
904
               rs.close();
905
               pstmt.close();
906

    
907
               // increase the usage count
908
               query = "UPDATE xml_returnfield SET usage_count ='" + count
909
                   + "' WHERE returnfield_id ='"+ id +"'";
910
               logMetacat.info("ReturnField Table Update:"+ query);
911

    
912
               pstmt = dbconn.prepareStatement(query);
913
               dbconn.increaseUsageCount(1);
914
               pstmt.execute();
915
               pstmt.close();
916

    
917
           } else {
918
               rs.close();
919
               pstmt.close();
920

    
921
               // insert a new record
922
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
923
                   + "VALUES (?, '1')";
924
               logMetacat.info("ReturnField Table Insert:"+ query);
925
               pstmt = dbconn.prepareStatement(query);
926
               pstmt.setString(1, returnfield);
927
               dbconn.increaseUsageCount(1);
928
               pstmt.execute();
929
               pstmt.close();
930

    
931
               // get the id of the new record
932
               query = "SELECT returnfield_id FROM xml_returnfield "
933
                   + "WHERE returnfield_string LIKE ?";
934
               logMetacat.info("ReturnField query after Insert:" + query);
935
               pstmt = dbconn.prepareStatement(query);
936
               pstmt.setString(1, returnfield);
937

    
938
               dbconn.increaseUsageCount(1);
939
               pstmt.execute();
940
               rs = pstmt.getResultSet();
941
               if(rs.next()){
942
                   id = rs.getInt(1);
943
               } else {
944
                   id = -1;
945
               }
946
               rs.close();
947
               pstmt.close();
948
           }
949

    
950
       } catch (Exception e){
951
           logMetacat.error("Error getting id from xml_returnfield in "
952
                                     + "DBQuery.getXmlReturnfieldsTableId: "
953
                                     + e.getMessage());
954
           id = -1;
955
       }
956

    
957
       returnfield_id = id;
958
       return count;
959
   }
960

    
961

    
962
    /*
963
     * A method to add return field to return doclist hash table
964
     */
965
    private Hashtable addReturnfield(Hashtable docListResult,
966
                                      QuerySpecification qspec,
967
                                      String user, String[]groups,
968
                                      DBConnection dbconn, boolean useXMLIndex )
969
                                      throws Exception
970
    {
971
      PreparedStatement pstmt = null;
972
      ResultSet rs = null;
973
      String docid = null;
974
      String fieldname = null;
975
      String fielddata = null;
976
      String relation = null;
977

    
978
      if (qspec.containsExtendedSQL())
979
      {
980
        qspec.setUserName(user);
981
        qspec.setGroup(groups);
982
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
983
        Vector results = new Vector();
984
        Enumeration keylist = docListResult.keys();
985
        StringBuffer doclist = new StringBuffer();
986
        Vector parentidList = new Vector();
987
        Hashtable returnFieldValue = new Hashtable();
988
        while (keylist.hasMoreElements())
989
        {
990
          doclist.append("'");
991
          doclist.append((String) keylist.nextElement());
992
          doclist.append("',");
993
        }
994
        if (doclist.length() > 0)
995
        {
996
          Hashtable controlPairs = new Hashtable();
997
          double extendedQueryStart = System.currentTimeMillis() / 1000;
998
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
999
          // check if user has permission to see the return field data
1000
          String accessControlSQL =
1001
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
1002
          pstmt = dbconn.prepareStatement(accessControlSQL);
1003
          //increase dbconnection usage count
1004
          dbconn.increaseUsageCount(1);
1005
          pstmt.execute();
1006
          rs = pstmt.getResultSet();
1007
          boolean tableHasRows = rs.next();
1008
          while (tableHasRows)
1009
          {
1010
            long startNodeId = rs.getLong(1);
1011
            long endNodeId = rs.getLong(2);
1012
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
1013
            tableHasRows = rs.next();
1014
          }
1015

    
1016
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
1017
           logMetacat.info( "Time for execute access extended query: "
1018
                          + (extendedAccessQueryEnd - extendedQueryStart));
1019

    
1020
           String extendedQuery =
1021
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
1022
           logMetacat.warn("Extended query: " + extendedQuery);
1023

    
1024
           if(extendedQuery != null){
1025
               pstmt = dbconn.prepareStatement(extendedQuery);
1026
               //increase dbconnection usage count
1027
               dbconn.increaseUsageCount(1);
1028
               pstmt.execute();
1029
               rs = pstmt.getResultSet();
1030
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
1031
               logMetacat.info(
1032
                   "Time for execute extended query: "
1033
                   + (extendedQueryEnd - extendedQueryStart));
1034
               tableHasRows = rs.next();
1035
               while (tableHasRows) {
1036
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1037
                   docid = rs.getString(1).trim();
1038
                   fieldname = rs.getString(2);
1039
                   fielddata = rs.getString(3);
1040
                   fielddata = MetaCatUtil.normalize(fielddata);
1041
                   String parentId = rs.getString(4);
1042
                   StringBuffer value = new StringBuffer();
1043

    
1044
                   // if xml_index is used, there would be just one record per nodeid
1045
                   // as xml_index just keeps one entry for each path
1046
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1047
                       // don't need to merger nodedata
1048
                       value.append("<param name=\"");
1049
                       value.append(fieldname);
1050
                       value.append("\">");
1051
                       value.append(fielddata);
1052
                       value.append("</param>");
1053
                       //set returnvalue
1054
                       returnValue.setDocid(docid);
1055
                       returnValue.setFieldValue(fielddata);
1056
                       returnValue.setXMLFieldValue(value.toString());
1057
                       // Store it in hastable
1058
                       putInArray(parentidList, parentId, returnValue);
1059
                   }
1060
                   else {
1061
                       // need to merge nodedata if they have same parent id and
1062
                       // node type is text
1063
                       fielddata = (String) ( (ReturnFieldValue)
1064
                                             getArrayValue(
1065
                           parentidList, parentId)).getFieldValue()
1066
                           + fielddata;
1067
                       value.append("<param name=\"");
1068
                       value.append(fieldname);
1069
                       value.append("\">");
1070
                       value.append(fielddata);
1071
                       value.append("</param>");
1072
                       returnValue.setDocid(docid);
1073
                       returnValue.setFieldValue(fielddata);
1074
                       returnValue.setXMLFieldValue(value.toString());
1075
                       // remove the old return value from paretnidList
1076
                       parentidList.remove(parentId);
1077
                       // store the new return value in parentidlit
1078
                       putInArray(parentidList, parentId, returnValue);
1079
                   }
1080
                   tableHasRows = rs.next();
1081
               } //while
1082
               rs.close();
1083
               pstmt.close();
1084

    
1085
               // put the merger node data info into doclistReult
1086
               Enumeration xmlFieldValue = (getElements(parentidList)).
1087
                   elements();
1088
               while (xmlFieldValue.hasMoreElements()) {
1089
                   ReturnFieldValue object =
1090
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1091
                   docid = object.getDocid();
1092
                   if (docListResult.containsKey(docid)) {
1093
                       String removedelement = (String) docListResult.
1094
                           remove(docid);
1095
                       docListResult.
1096
                           put(docid,
1097
                               removedelement + object.getXMLFieldValue());
1098
                   }
1099
                   else {
1100
                       docListResult.put(docid, object.getXMLFieldValue());
1101
                   }
1102
               } //while
1103
               double docListResultEnd = System.currentTimeMillis() / 1000;
1104
               logMetacat.warn(
1105
                   "Time for prepare doclistresult after"
1106
                   + " execute extended query: "
1107
                   + (docListResultEnd - extendedQueryEnd));
1108
           }
1109

    
1110
           // get attribures return
1111
           docListResult = getAttributeValueForReturn(qspec,
1112
                           docListResult, doclist.toString(), useXMLIndex);
1113
       }//if doclist lenght is great than zero
1114

    
1115
     }//if has extended query
1116

    
1117
      return docListResult;
1118
    }//addReturnfield
1119

    
1120
    /*
1121
    * A method to add relationship to return doclist hash table
1122
    */
1123
   private Hashtable addRelationship(Hashtable docListResult,
1124
                                     QuerySpecification qspec,
1125
                                     DBConnection dbconn, boolean useXMLIndex )
1126
                                     throws Exception
1127
  {
1128
    PreparedStatement pstmt = null;
1129
    ResultSet rs = null;
1130
    StringBuffer document = null;
1131
    double startRelation = System.currentTimeMillis() / 1000;
1132
    Enumeration docidkeys = docListResult.keys();
1133
    while (docidkeys.hasMoreElements())
1134
    {
1135
      //String connstring =
1136
      // "metacat://"+util.getOption("server")+"?docid=";
1137
      String connstring = "%docid=";
1138
      String docidkey = (String) docidkeys.nextElement();
1139
      pstmt = dbconn.prepareStatement(QuerySpecification
1140
                      .printRelationSQL(docidkey));
1141
      pstmt.execute();
1142
      rs = pstmt.getResultSet();
1143
      boolean tableHasRows = rs.next();
1144
      while (tableHasRows)
1145
      {
1146
        String sub = rs.getString(1);
1147
        String rel = rs.getString(2);
1148
        String obj = rs.getString(3);
1149
        String subDT = rs.getString(4);
1150
        String objDT = rs.getString(5);
1151

    
1152
        document = new StringBuffer();
1153
        document.append("<triple>");
1154
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1155
        document.append("</subject>");
1156
        if (subDT != null)
1157
        {
1158
          document.append("<subjectdoctype>").append(subDT);
1159
          document.append("</subjectdoctype>");
1160
        }
1161
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1162
        document.append("</relationship>");
1163
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1164
        document.append("</object>");
1165
        if (objDT != null)
1166
        {
1167
          document.append("<objectdoctype>").append(objDT);
1168
          document.append("</objectdoctype>");
1169
        }
1170
        document.append("</triple>");
1171

    
1172
        String removedelement = (String) docListResult.remove(docidkey);
1173
        docListResult.put(docidkey, removedelement+ document.toString());
1174
        tableHasRows = rs.next();
1175
      }//while
1176
      rs.close();
1177
      pstmt.close();
1178
    }//while
1179
    double endRelation = System.currentTimeMillis() / 1000;
1180
    logMetacat.info("Time for adding relation to docListResult: "
1181
                             + (endRelation - startRelation));
1182

    
1183
    return docListResult;
1184
  }//addRelation
1185

    
1186
  /**
1187
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1188
   * string as a param instead of a hashtable.
1189
   *
1190
   * @param xmlquery a string representing a query.
1191
   */
1192
   private  String transformQuery(String xmlquery)
1193
   {
1194
     xmlquery = xmlquery.trim();
1195
     int index = xmlquery.indexOf("?>");
1196
     if (index != -1)
1197
     {
1198
       return xmlquery.substring(index + 2, xmlquery.length());
1199
     }
1200
     else
1201
     {
1202
       return xmlquery;
1203
     }
1204
   }
1205

    
1206

    
1207
    /*
1208
     * A method to search if Vector contains a particular key string
1209
     */
1210
    private boolean containsKey(Vector parentidList, String parentId)
1211
    {
1212

    
1213
        Vector tempVector = null;
1214

    
1215
        for (int count = 0; count < parentidList.size(); count++) {
1216
            tempVector = (Vector) parentidList.get(count);
1217
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1218
        }
1219
        return false;
1220
    }
1221

    
1222
    /*
1223
     * A method to put key and value in Vector
1224
     */
1225
    private void putInArray(Vector parentidList, String key,
1226
            ReturnFieldValue value)
1227
    {
1228

    
1229
        Vector tempVector = null;
1230

    
1231
        for (int count = 0; count < parentidList.size(); count++) {
1232
            tempVector = (Vector) parentidList.get(count);
1233

    
1234
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1235
                tempVector.remove(1);
1236
                tempVector.add(1, value);
1237
                return;
1238
            }
1239
        }
1240

    
1241
        tempVector = new Vector();
1242
        tempVector.add(0, key);
1243
        tempVector.add(1, value);
1244
        parentidList.add(tempVector);
1245
        return;
1246
    }
1247

    
1248
    /*
1249
     * A method to get value in Vector given a key
1250
     */
1251
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1252
    {
1253

    
1254
        Vector tempVector = null;
1255

    
1256
        for (int count = 0; count < parentidList.size(); count++) {
1257
            tempVector = (Vector) parentidList.get(count);
1258

    
1259
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1260
                    .get(1); }
1261
        }
1262
        return null;
1263
    }
1264

    
1265
    /*
1266
     * A method to get enumeration of all values in Vector
1267
     */
1268
    private Vector getElements(Vector parentidList)
1269
    {
1270
        Vector enumVector = new Vector();
1271
        Vector tempVector = null;
1272

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

    
1276
            enumVector.add(tempVector.get(1));
1277
        }
1278
        return enumVector;
1279
    }
1280

    
1281
    /*
1282
     * A method to return search result after running a query which return
1283
     * field have attribue
1284
     */
1285
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
1286
            Hashtable docInformationList, String docList, boolean useXMLIndex)
1287
    {
1288
        StringBuffer XML = null;
1289
        String sql = null;
1290
        DBConnection dbconn = null;
1291
        PreparedStatement pstmt = null;
1292
        ResultSet rs = null;
1293
        int serialNumber = -1;
1294
        boolean tableHasRows = false;
1295

    
1296
        //check the parameter
1297
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1298

    
1299
        // if has attribute as return field
1300
        if (squery.containsAttributeReturnField()) {
1301
            sql = squery.printAttributeQuery(docList, useXMLIndex);
1302
            try {
1303
                dbconn = DBConnectionPool
1304
                        .getDBConnection("DBQuery.getAttributeValue");
1305
                serialNumber = dbconn.getCheckOutSerialNumber();
1306
                pstmt = dbconn.prepareStatement(sql);
1307
                pstmt.execute();
1308
                rs = pstmt.getResultSet();
1309
                tableHasRows = rs.next();
1310
                while (tableHasRows) {
1311
                    String docid = rs.getString(1).trim();
1312
                    String fieldname = rs.getString(2);
1313
                    String fielddata = rs.getString(3);
1314
                    String attirbuteName = rs.getString(4);
1315
                    XML = new StringBuffer();
1316

    
1317
                    XML.append("<param name=\"");
1318
                    XML.append(fieldname);
1319
                    XML.append("/");
1320
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1321
                    XML.append(attirbuteName);
1322
                    XML.append("\">");
1323
                    XML.append(fielddata);
1324
                    XML.append("</param>");
1325
                    tableHasRows = rs.next();
1326

    
1327
                    if (docInformationList.containsKey(docid)) {
1328
                        String removedelement = (String) docInformationList
1329
                                .remove(docid);
1330
                        docInformationList.put(docid, removedelement
1331
                                + XML.toString());
1332
                    } else {
1333
                        docInformationList.put(docid, XML.toString());
1334
                    }
1335
                }//while
1336
                rs.close();
1337
                pstmt.close();
1338
            } catch (Exception se) {
1339
                logMetacat.error(
1340
                        "Error in DBQuery.getAttributeValue1: "
1341
                                + se.getMessage());
1342
            } finally {
1343
                try {
1344
                    pstmt.close();
1345
                }//try
1346
                catch (SQLException sqlE) {
1347
                    logMetacat.error(
1348
                            "Error in DBQuery.getAttributeValue2: "
1349
                                    + sqlE.getMessage());
1350
                }//catch
1351
                finally {
1352
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
1353
                }//finally
1354
            }//finally
1355
        }//if
1356
        return docInformationList;
1357

    
1358
    }
1359

    
1360
    /*
1361
     * A method to create a query to get owner's docid list
1362
     */
1363
    private String getOwnerQuery(String owner)
1364
    {
1365
        if (owner != null) {
1366
            owner = owner.toLowerCase();
1367
        }
1368
        StringBuffer self = new StringBuffer();
1369

    
1370
        self.append("SELECT docid,docname,doctype,");
1371
        self.append("date_created, date_updated, rev ");
1372
        self.append("FROM xml_documents WHERE docid IN (");
1373
        self.append("(");
1374
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1375
        self.append("nodedata LIKE '%%%' ");
1376
        self.append(") \n");
1377
        self.append(") ");
1378
        self.append(" AND (");
1379
        self.append(" lower(user_owner) = '" + owner + "'");
1380
        self.append(") ");
1381
        return self.toString();
1382
    }
1383

    
1384
    /**
1385
     * format a structured query as an XML document that conforms to the
1386
     * pathquery.dtd and is appropriate for submission to the DBQuery
1387
     * structured query engine
1388
     *
1389
     * @param params The list of parameters that should be included in the
1390
     *            query
1391
     */
1392
    public static String createSQuery(Hashtable params)
1393
    {
1394
        StringBuffer query = new StringBuffer();
1395
        Enumeration elements;
1396
        Enumeration keys;
1397
        String filterDoctype = null;
1398
        String casesensitive = null;
1399
        String searchmode = null;
1400
        Object nextkey;
1401
        Object nextelement;
1402
        //add the xml headers
1403
        query.append("<?xml version=\"1.0\"?>\n");
1404
        query.append("<pathquery version=\"1.2\">\n");
1405

    
1406

    
1407

    
1408
        if (params.containsKey("meta_file_id")) {
1409
            query.append("<meta_file_id>");
1410
            query.append(((String[]) params.get("meta_file_id"))[0]);
1411
            query.append("</meta_file_id>");
1412
        }
1413

    
1414
        if (params.containsKey("returndoctype")) {
1415
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1416
            for (int i = 0; i < returnDoctypes.length; i++) {
1417
                String doctype = (String) returnDoctypes[i];
1418

    
1419
                if (!doctype.equals("any") && !doctype.equals("ANY")
1420
                        && !doctype.equals("")) {
1421
                    query.append("<returndoctype>").append(doctype);
1422
                    query.append("</returndoctype>");
1423
                }
1424
            }
1425
        }
1426

    
1427
        if (params.containsKey("filterdoctype")) {
1428
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1429
            for (int i = 0; i < filterDoctypes.length; i++) {
1430
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1431
                query.append("</filterdoctype>");
1432
            }
1433
        }
1434

    
1435
        if (params.containsKey("returnfield")) {
1436
            String[] returnfield = ((String[]) params.get("returnfield"));
1437
            for (int i = 0; i < returnfield.length; i++) {
1438
                query.append("<returnfield>").append(returnfield[i]);
1439
                query.append("</returnfield>");
1440
            }
1441
        }
1442

    
1443
        if (params.containsKey("owner")) {
1444
            String[] owner = ((String[]) params.get("owner"));
1445
            for (int i = 0; i < owner.length; i++) {
1446
                query.append("<owner>").append(owner[i]);
1447
                query.append("</owner>");
1448
            }
1449
        }
1450

    
1451
        if (params.containsKey("site")) {
1452
            String[] site = ((String[]) params.get("site"));
1453
            for (int i = 0; i < site.length; i++) {
1454
                query.append("<site>").append(site[i]);
1455
                query.append("</site>");
1456
            }
1457
        }
1458

    
1459
        //allows the dynamic switching of boolean operators
1460
        if (params.containsKey("operator")) {
1461
            query.append("<querygroup operator=\""
1462
                    + ((String[]) params.get("operator"))[0] + "\">");
1463
        } else { //the default operator is UNION
1464
            query.append("<querygroup operator=\"UNION\">");
1465
        }
1466

    
1467
        if (params.containsKey("casesensitive")) {
1468
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1469
        } else {
1470
            casesensitive = "false";
1471
        }
1472

    
1473
        if (params.containsKey("searchmode")) {
1474
            searchmode = ((String[]) params.get("searchmode"))[0];
1475
        } else {
1476
            searchmode = "contains";
1477
        }
1478

    
1479
        //anyfield is a special case because it does a
1480
        //free text search. It does not have a <pathexpr>
1481
        //tag. This allows for a free text search within the structured
1482
        //query. This is useful if the INTERSECT operator is used.
1483
        if (params.containsKey("anyfield")) {
1484
            String[] anyfield = ((String[]) params.get("anyfield"));
1485
            //allow for more than one value for anyfield
1486
            for (int i = 0; i < anyfield.length; i++) {
1487
                if (!anyfield[i].equals("")) {
1488
                    query.append("<queryterm casesensitive=\"" + casesensitive
1489
                            + "\" " + "searchmode=\"" + searchmode
1490
                            + "\"><value>" + anyfield[i]
1491
                            + "</value></queryterm>");
1492
                }
1493
            }
1494
        }
1495

    
1496
        //this while loop finds the rest of the parameters
1497
        //and attempts to query for the field specified
1498
        //by the parameter.
1499
        elements = params.elements();
1500
        keys = params.keys();
1501
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1502
            nextkey = keys.nextElement();
1503
            nextelement = elements.nextElement();
1504

    
1505
            //make sure we aren't querying for any of these
1506
            //parameters since the are already in the query
1507
            //in one form or another.
1508
            Vector ignoredParams = new Vector();
1509
            ignoredParams.add("returndoctype");
1510
            ignoredParams.add("filterdoctype");
1511
            ignoredParams.add("action");
1512
            ignoredParams.add("qformat");
1513
            ignoredParams.add("anyfield");
1514
            ignoredParams.add("returnfield");
1515
            ignoredParams.add("owner");
1516
            ignoredParams.add("site");
1517
            ignoredParams.add("operator");
1518
            ignoredParams.add("sessionid");
1519

    
1520
            // Also ignore parameters listed in the properties file
1521
            // so that they can be passed through to stylesheets
1522
            String paramsToIgnore = MetaCatUtil
1523
                    .getOption("query.ignored.params");
1524
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1525
            while (st.hasMoreTokens()) {
1526
                ignoredParams.add(st.nextToken());
1527
            }
1528
            if (!ignoredParams.contains(nextkey.toString())) {
1529
                //allow for more than value per field name
1530
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1531
                    if (!((String[]) nextelement)[i].equals("")) {
1532
                        query.append("<queryterm casesensitive=\""
1533
                                + casesensitive + "\" " + "searchmode=\""
1534
                                + searchmode + "\">" + "<value>" +
1535
                                //add the query value
1536
                                ((String[]) nextelement)[i]
1537
                                + "</value><pathexpr>" +
1538
                                //add the path to query by
1539
                                nextkey.toString() + "</pathexpr></queryterm>");
1540
                    }
1541
                }
1542
            }
1543
        }
1544
        query.append("</querygroup></pathquery>");
1545
        //append on the end of the xml and return the result as a string
1546
        return query.toString();
1547
    }
1548

    
1549
    /**
1550
     * format a simple free-text value query as an XML document that conforms
1551
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1552
     * structured query engine
1553
     *
1554
     * @param value the text string to search for in the xml catalog
1555
     * @param doctype the type of documents to include in the result set -- use
1556
     *            "any" or "ANY" for unfiltered result sets
1557
     */
1558
    public static String createQuery(String value, String doctype)
1559
    {
1560
        StringBuffer xmlquery = new StringBuffer();
1561
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1562
        xmlquery.append("<pathquery version=\"1.0\">");
1563

    
1564
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1565
            xmlquery.append("<returndoctype>");
1566
            xmlquery.append(doctype).append("</returndoctype>");
1567
        }
1568

    
1569
        xmlquery.append("<querygroup operator=\"UNION\">");
1570
        //chad added - 8/14
1571
        //the if statement allows a query to gracefully handle a null
1572
        //query. Without this if a nullpointerException is thrown.
1573
        if (!value.equals("")) {
1574
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1575
            xmlquery.append("searchmode=\"contains\">");
1576
            xmlquery.append("<value>").append(value).append("</value>");
1577
            xmlquery.append("</queryterm>");
1578
        }
1579
        xmlquery.append("</querygroup>");
1580
        xmlquery.append("</pathquery>");
1581

    
1582
        return (xmlquery.toString());
1583
    }
1584

    
1585
    /**
1586
     * format a simple free-text value query as an XML document that conforms
1587
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1588
     * structured query engine
1589
     *
1590
     * @param value the text string to search for in the xml catalog
1591
     */
1592
    public static String createQuery(String value)
1593
    {
1594
        return createQuery(value, "any");
1595
    }
1596

    
1597
    /**
1598
     * Check for "READ" permission on @docid for @user and/or @group from DB
1599
     * connection
1600
     */
1601
    private boolean hasPermission(String user, String[] groups, String docid)
1602
            throws SQLException, Exception
1603
    {
1604
        // Check for READ permission on @docid for @user and/or @groups
1605
        PermissionController controller = new PermissionController(docid);
1606
        return controller.hasPermission(user, groups,
1607
                AccessControlInterface.READSTRING);
1608
    }
1609

    
1610
    /**
1611
     * Get all docIds list for a data packadge
1612
     *
1613
     * @param dataPackageDocid, the string in docId field of xml_relation table
1614
     */
1615
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1616
    {
1617
        DBConnection dbConn = null;
1618
        int serialNumber = -1;
1619
        Vector docIdList = new Vector();//return value
1620
        PreparedStatement pStmt = null;
1621
        ResultSet rs = null;
1622
        String docIdInSubjectField = null;
1623
        String docIdInObjectField = null;
1624

    
1625
        // Check the parameter
1626
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1627

    
1628
        //the query stirng
1629
        String query = "SELECT subject, object from xml_relation where docId = ?";
1630
        try {
1631
            dbConn = DBConnectionPool
1632
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1633
            serialNumber = dbConn.getCheckOutSerialNumber();
1634
            pStmt = dbConn.prepareStatement(query);
1635
            //bind the value to query
1636
            pStmt.setString(1, dataPackageDocid);
1637

    
1638
            //excute the query
1639
            pStmt.execute();
1640
            //get the result set
1641
            rs = pStmt.getResultSet();
1642
            //process the result
1643
            while (rs.next()) {
1644
                //In order to get the whole docIds in a data packadge,
1645
                //we need to put the docIds of subject and object field in
1646
                // xml_relation
1647
                //into the return vector
1648
                docIdInSubjectField = rs.getString(1);//the result docId in
1649
                                                      // subject field
1650
                docIdInObjectField = rs.getString(2);//the result docId in
1651
                                                     // object field
1652

    
1653
                //don't put the duplicate docId into the vector
1654
                if (!docIdList.contains(docIdInSubjectField)) {
1655
                    docIdList.add(docIdInSubjectField);
1656
                }
1657

    
1658
                //don't put the duplicate docId into the vector
1659
                if (!docIdList.contains(docIdInObjectField)) {
1660
                    docIdList.add(docIdInObjectField);
1661
                }
1662
            }//while
1663
            //close the pStmt
1664
            pStmt.close();
1665
        }//try
1666
        catch (SQLException e) {
1667
            logMetacat.error("Error in getDocidListForDataPackage: "
1668
                    + e.getMessage());
1669
        }//catch
1670
        finally {
1671
            try {
1672
                pStmt.close();
1673
            }//try
1674
            catch (SQLException ee) {
1675
                logMetacat.error(
1676
                        "Error in getDocidListForDataPackage: "
1677
                                + ee.getMessage());
1678
            }//catch
1679
            finally {
1680
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1681
            }//fianlly
1682
        }//finally
1683
        return docIdList;
1684
    }//getCurrentDocidListForDataPackadge()
1685

    
1686
    /**
1687
     * Get all docIds list for a data packadge
1688
     *
1689
     * @param dataPackageDocid, the string in docId field of xml_relation table
1690
     */
1691
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1692
    {
1693

    
1694
        Vector docIdList = new Vector();//return value
1695
        Vector tripleList = null;
1696
        String xml = null;
1697

    
1698
        // Check the parameter
1699
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1700

    
1701
        try {
1702
            //initial a documentImpl object
1703
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1704
            //transfer to documentImpl object to string
1705
            xml = packageDocument.toString();
1706

    
1707
            //create a tripcollection object
1708
            TripleCollection tripleForPackage = new TripleCollection(
1709
                    new StringReader(xml));
1710
            //get the vetor of triples
1711
            tripleList = tripleForPackage.getCollection();
1712

    
1713
            for (int i = 0; i < tripleList.size(); i++) {
1714
                //put subject docid into docIdlist without duplicate
1715
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1716
                        .getSubject())) {
1717
                    //put subject docid into docIdlist
1718
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1719
                }
1720
                //put object docid into docIdlist without duplicate
1721
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1722
                        .getObject())) {
1723
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1724
                }
1725
            }//for
1726
        }//try
1727
        catch (Exception e) {
1728
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1729
                    + e.getMessage());
1730
        }//catch
1731

    
1732
        // return result
1733
        return docIdList;
1734
    }//getDocidListForPackageInXMLRevisions()
1735

    
1736
    /**
1737
     * Check if the docId is a data packadge id. If the id is a data packadage
1738
     * id, it should be store in the docId fields in xml_relation table. So we
1739
     * can use a query to get the entries which the docId equals the given
1740
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1741
     * it is.
1742
     *
1743
     * @param docId, the id need to be checked
1744
     */
1745
    private boolean isDataPackageId(String docId)
1746
    {
1747
        boolean result = false;
1748
        PreparedStatement pStmt = null;
1749
        ResultSet rs = null;
1750
        String query = "SELECT docId from xml_relation where docId = ?";
1751
        DBConnection dbConn = null;
1752
        int serialNumber = -1;
1753
        try {
1754
            dbConn = DBConnectionPool
1755
                    .getDBConnection("DBQuery.isDataPackageId");
1756
            serialNumber = dbConn.getCheckOutSerialNumber();
1757
            pStmt = dbConn.prepareStatement(query);
1758
            //bind the value to query
1759
            pStmt.setString(1, docId);
1760
            //execute the query
1761
            pStmt.execute();
1762
            rs = pStmt.getResultSet();
1763
            //process the result
1764
            if (rs.next()) //There are some records for the id in docId fields
1765
            {
1766
                result = true;//It is a data packadge id
1767
            }
1768
            pStmt.close();
1769
        }//try
1770
        catch (SQLException e) {
1771
            logMetacat.error("Error in isDataPackageId: "
1772
                    + e.getMessage());
1773
        } finally {
1774
            try {
1775
                pStmt.close();
1776
            }//try
1777
            catch (SQLException ee) {
1778
                logMetacat.error("Error in isDataPackageId: "
1779
                        + ee.getMessage());
1780
            }//catch
1781
            finally {
1782
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1783
            }//finally
1784
        }//finally
1785
        return result;
1786
    }//isDataPackageId()
1787

    
1788
    /**
1789
     * Check if the user has the permission to export data package
1790
     *
1791
     * @param conn, the connection
1792
     * @param docId, the id need to be checked
1793
     * @param user, the name of user
1794
     * @param groups, the user's group
1795
     */
1796
    private boolean hasPermissionToExportPackage(String docId, String user,
1797
            String[] groups) throws Exception
1798
    {
1799
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1800
        return DocumentImpl.hasReadPermission(user, groups, docId);
1801
    }
1802

    
1803
    /**
1804
     * Get the current Rev for a docid in xml_documents table
1805
     *
1806
     * @param docId, the id need to get version numb If the return value is -5,
1807
     *            means no value in rev field for this docid
1808
     */
1809
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1810
            throws SQLException
1811
    {
1812
        int rev = -5;
1813
        PreparedStatement pStmt = null;
1814
        ResultSet rs = null;
1815
        String query = "SELECT rev from xml_documents where docId = ?";
1816
        DBConnection dbConn = null;
1817
        int serialNumber = -1;
1818
        try {
1819
            dbConn = DBConnectionPool
1820
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1821
            serialNumber = dbConn.getCheckOutSerialNumber();
1822
            pStmt = dbConn.prepareStatement(query);
1823
            //bind the value to query
1824
            pStmt.setString(1, docId);
1825
            //execute the query
1826
            pStmt.execute();
1827
            rs = pStmt.getResultSet();
1828
            //process the result
1829
            if (rs.next()) //There are some records for rev
1830
            {
1831
                rev = rs.getInt(1);
1832
                ;//It is the version for given docid
1833
            } else {
1834
                rev = -5;
1835
            }
1836

    
1837
        }//try
1838
        catch (SQLException e) {
1839
            logMetacat.error(
1840
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1841
                            + e.getMessage());
1842
            throw e;
1843
        }//catch
1844
        finally {
1845
            try {
1846
                pStmt.close();
1847
            }//try
1848
            catch (SQLException ee) {
1849
                logMetacat.error(
1850
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1851
                                + ee.getMessage());
1852
            }//catch
1853
            finally {
1854
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1855
            }//finally
1856
        }//finally
1857
        return rev;
1858
    }//getCurrentRevFromXMLDoumentsTable
1859

    
1860
    /**
1861
     * put a doc into a zip output stream
1862
     *
1863
     * @param docImpl, docmentImpl object which will be sent to zip output
1864
     *            stream
1865
     * @param zipOut, zip output stream which the docImpl will be put
1866
     * @param packageZipEntry, the zip entry name for whole package
1867
     */
1868
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1869
            ZipOutputStream zipOut, String packageZipEntry)
1870
            throws ClassNotFoundException, IOException, SQLException,
1871
            McdbException, Exception
1872
    {
1873
        byte[] byteString = null;
1874
        ZipEntry zEntry = null;
1875

    
1876
        byteString = docImpl.toString().getBytes();
1877
        //use docId as the zip entry's name
1878
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1879
                + docImpl.getDocID());
1880
        zEntry.setSize(byteString.length);
1881
        zipOut.putNextEntry(zEntry);
1882
        zipOut.write(byteString, 0, byteString.length);
1883
        zipOut.closeEntry();
1884

    
1885
    }//addDocToZipOutputStream()
1886

    
1887
    /**
1888
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1889
     * only inlcudes current version. If a DocumentImple object couldn't find
1890
     * for a docid, then the String of this docid was added to vetor rather
1891
     * than DocumentImple object.
1892
     *
1893
     * @param docIdList, a vetor hold a docid list for a data package. In
1894
     *            docid, there is not version number in it.
1895
     */
1896

    
1897
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1898
            throws McdbException, Exception
1899
    {
1900
        //Connection dbConn=null;
1901
        Vector documentImplList = new Vector();
1902
        int rev = 0;
1903

    
1904
        // Check the parameter
1905
        if (docIdList.isEmpty()) { return documentImplList; }//if
1906

    
1907
        //for every docid in vector
1908
        for (int i = 0; i < docIdList.size(); i++) {
1909
            try {
1910
                //get newest version for this docId
1911
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1912
                        .elementAt(i));
1913

    
1914
                // There is no record for this docId in xml_documents table
1915
                if (rev == -5) {
1916
                    // Rather than put DocumentImple object, put a String
1917
                    // Object(docid)
1918
                    // into the documentImplList
1919
                    documentImplList.add((String) docIdList.elementAt(i));
1920
                    // Skip other code
1921
                    continue;
1922
                }
1923

    
1924
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1925
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1926

    
1927
                //create new documentImpl object
1928
                DocumentImpl documentImplObject = new DocumentImpl(
1929
                        docidPlusVersion);
1930
                //add them to vector
1931
                documentImplList.add(documentImplObject);
1932
            }//try
1933
            catch (Exception e) {
1934
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
1935
                        + e.getMessage());
1936
                // continue the for loop
1937
                continue;
1938
            }
1939
        }//for
1940
        return documentImplList;
1941
    }
1942

    
1943
    /**
1944
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
1945
     * object couldn't find for a docid, then the String of this docid was
1946
     * added to vetor rather than DocumentImple object.
1947
     *
1948
     * @param docIdList, a vetor hold a docid list for a data package. In
1949
     *            docid, t here is version number in it.
1950
     */
1951
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
1952
    {
1953
        //Connection dbConn=null;
1954
        Vector documentImplList = new Vector();
1955
        String siteCode = null;
1956
        String uniqueId = null;
1957
        int rev = 0;
1958

    
1959
        // Check the parameter
1960
        if (docIdList.isEmpty()) { return documentImplList; }//if
1961

    
1962
        //for every docid in vector
1963
        for (int i = 0; i < docIdList.size(); i++) {
1964

    
1965
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1966

    
1967
            try {
1968
                //create new documentImpl object
1969
                DocumentImpl documentImplObject = new DocumentImpl(
1970
                        docidPlusVersion);
1971
                //add them to vector
1972
                documentImplList.add(documentImplObject);
1973
            }//try
1974
            catch (McdbDocNotFoundException notFoundE) {
1975
                logMetacat.error(
1976
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1977
                                + notFoundE.getMessage());
1978
                // Rather than add a DocumentImple object into vetor, a String
1979
                // object
1980
                // - the doicd was added to the vector
1981
                documentImplList.add(docidPlusVersion);
1982
                // Continue the for loop
1983
                continue;
1984
            }//catch
1985
            catch (Exception e) {
1986
                logMetacat.error(
1987
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1988
                                + e.getMessage());
1989
                // Continue the for loop
1990
                continue;
1991
            }//catch
1992

    
1993
        }//for
1994
        return documentImplList;
1995
    }//getOldVersionAllDocumentImple
1996

    
1997
    /**
1998
     * put a data file into a zip output stream
1999
     *
2000
     * @param docImpl, docmentImpl object which will be sent to zip output
2001
     *            stream
2002
     * @param zipOut, the zip output stream which the docImpl will be put
2003
     * @param packageZipEntry, the zip entry name for whole package
2004
     */
2005
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2006
            ZipOutputStream zipOut, String packageZipEntry)
2007
            throws ClassNotFoundException, IOException, SQLException,
2008
            McdbException, Exception
2009
    {
2010
        byte[] byteString = null;
2011
        ZipEntry zEntry = null;
2012
        // this is data file; add file to zip
2013
        String filePath = MetaCatUtil.getOption("datafilepath");
2014
        if (!filePath.endsWith("/")) {
2015
            filePath += "/";
2016
        }
2017
        String fileName = filePath + docImpl.getDocID();
2018
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2019
        zipOut.putNextEntry(zEntry);
2020
        FileInputStream fin = null;
2021
        try {
2022
            fin = new FileInputStream(fileName);
2023
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2024
            int b = fin.read(buf);
2025
            while (b != -1) {
2026
                zipOut.write(buf, 0, b);
2027
                b = fin.read(buf);
2028
            }//while
2029
            zipOut.closeEntry();
2030
        }//try
2031
        catch (IOException ioe) {
2032
            logMetacat.error("There is an exception: "
2033
                    + ioe.getMessage());
2034
        }//catch
2035
    }//addDataFileToZipOutputStream()
2036

    
2037
    /**
2038
     * create a html summary for data package and put it into zip output stream
2039
     *
2040
     * @param docImplList, the documentImpl ojbects in data package
2041
     * @param zipOut, the zip output stream which the html should be put
2042
     * @param packageZipEntry, the zip entry name for whole package
2043
     */
2044
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2045
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2046
    {
2047
        StringBuffer htmlDoc = new StringBuffer();
2048
        ZipEntry zEntry = null;
2049
        byte[] byteString = null;
2050
        InputStream source;
2051
        DBTransform xmlToHtml;
2052

    
2053
        //create a DBTransform ojbect
2054
        xmlToHtml = new DBTransform();
2055
        //head of html
2056
        htmlDoc.append("<html><head></head><body>");
2057
        for (int i = 0; i < docImplList.size(); i++) {
2058
            // If this String object, this means it is missed data file
2059
            if ((((docImplList.elementAt(i)).getClass()).toString())
2060
                    .equals("class java.lang.String")) {
2061

    
2062
                htmlDoc.append("<a href=\"");
2063
                String dataFileid = (String) docImplList.elementAt(i);
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

    
2069
            }//if
2070
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2071
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2072
                                              // transform it.
2073
                //transform each file individually then concatenate all of the
2074
                //transformations together.
2075

    
2076
                //for metadata xml title
2077
                htmlDoc.append("<h2>");
2078
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2079
                        .getDocID());
2080
                //htmlDoc.append(".");
2081
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2082
                htmlDoc.append("</h2>");
2083
                //do the actual transform
2084
                StringWriter docString = new StringWriter();
2085
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2086
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2087
                        "-//W3C//HTML//EN", "html", docString);
2088
                htmlDoc.append(docString.toString());
2089
                htmlDoc.append("<br><br><hr><br><br>");
2090
            }//if
2091
            else { //this is a data file so we should link to it in the html
2092
                htmlDoc.append("<a href=\"");
2093
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2094
                        .getDocID();
2095
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2096
                htmlDoc.append("Data File: ");
2097
                htmlDoc.append(dataFileid).append("</a><br>");
2098
                htmlDoc.append("<br><hr><br>");
2099
            }//else
2100
        }//for
2101
        htmlDoc.append("</body></html>");
2102
        byteString = htmlDoc.toString().getBytes();
2103
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2104
        zEntry.setSize(byteString.length);
2105
        zipOut.putNextEntry(zEntry);
2106
        zipOut.write(byteString, 0, byteString.length);
2107
        zipOut.closeEntry();
2108
        //dbConn.close();
2109

    
2110
    }//addHtmlSummaryToZipOutputStream
2111

    
2112
    /**
2113
     * put a data packadge into a zip output stream
2114
     *
2115
     * @param docId, which the user want to put into zip output stream,it has version
2116
     * @param out, a servletoutput stream which the zip output stream will be
2117
     *            put
2118
     * @param user, the username of the user
2119
     * @param groups, the group of the user
2120
     */
2121
    public ZipOutputStream getZippedPackage(String docIdString,
2122
            ServletOutputStream out, String user, String[] groups,
2123
            String passWord) throws ClassNotFoundException, IOException,
2124
            SQLException, McdbException, NumberFormatException, Exception
2125
    {
2126
        ZipOutputStream zOut = null;
2127
        String elementDocid = null;
2128
        DocumentImpl docImpls = null;
2129
        //Connection dbConn = null;
2130
        Vector docIdList = new Vector();
2131
        Vector documentImplList = new Vector();
2132
        Vector htmlDocumentImplList = new Vector();
2133
        String packageId = null;
2134
        String rootName = "package";//the package zip entry name
2135

    
2136
        String docId = null;
2137
        int version = -5;
2138
        // Docid without revision
2139
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2140
        // revision number
2141
        version = MetaCatUtil.getVersionFromString(docIdString);
2142

    
2143
        //check if the reqused docId is a data package id
2144
        if (!isDataPackageId(docId)) {
2145

    
2146
            /*
2147
             * Exception e = new Exception("The request the doc id "
2148
             * +docIdString+ " is not a data package id");
2149
             */
2150

    
2151
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2152
            // zip
2153
            //up the single document and return the zip file.
2154
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2155

    
2156
                Exception e = new Exception("User " + user
2157
                        + " does not have permission"
2158
                        + " to export the data package " + docIdString);
2159
                throw e;
2160
            }
2161

    
2162
            docImpls = new DocumentImpl(docIdString);
2163
            //checking if the user has the permission to read the documents
2164
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2165
                    .getDocID())) {
2166
                zOut = new ZipOutputStream(out);
2167
                //if the docImpls is metadata
2168
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2169
                    //add metadata into zip output stream
2170
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2171
                }//if
2172
                else {
2173
                    //it is data file
2174
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2175
                    htmlDocumentImplList.add(docImpls);
2176
                }//else
2177
            }//if
2178

    
2179
            zOut.finish(); //terminate the zip file
2180
            return zOut;
2181
        }
2182
        // Check the permission of user
2183
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2184

    
2185
            Exception e = new Exception("User " + user
2186
                    + " does not have permission"
2187
                    + " to export the data package " + docIdString);
2188
            throw e;
2189
        } else //it is a packadge id
2190
        {
2191
            //store the package id
2192
            packageId = docId;
2193
            //get current version in database
2194
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2195
            //If it is for current version (-1 means user didn't specify
2196
            // revision)
2197
            if ((version == -1) || version == currentVersion) {
2198
                //get current version number
2199
                version = currentVersion;
2200
                //get package zip entry name
2201
                //it should be docId.revsion.package
2202
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2203
                        + version + MetaCatUtil.getOption("accNumSeparator")
2204
                        + "package";
2205
                //get the whole id list for data packadge
2206
                docIdList = getCurrentDocidListForDataPackage(packageId);
2207
                //get the whole documentImple object
2208
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2209

    
2210
            }//if
2211
            else if (version > currentVersion || version < -1) {
2212
                throw new Exception("The user specified docid: " + docId + "."
2213
                        + version + " doesn't exist");
2214
            }//else if
2215
            else //for an old version
2216
            {
2217

    
2218
                rootName = docIdString
2219
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2220
                //get the whole id list for data packadge
2221
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2222

    
2223
                //get the whole documentImple object
2224
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2225
            }//else
2226

    
2227
            // Make sure documentImplist is not empty
2228
            if (documentImplList.isEmpty()) { throw new Exception(
2229
                    "Couldn't find component for data package: " + packageId); }//if
2230

    
2231
            zOut = new ZipOutputStream(out);
2232
            //put every element into zip output stream
2233
            for (int i = 0; i < documentImplList.size(); i++) {
2234
                // if the object in the vetor is String, this means we couldn't
2235
                // find
2236
                // the document locally, we need find it remote
2237
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2238
                        .equals("class java.lang.String")) {
2239
                    // Get String object from vetor
2240
                    String documentId = (String) documentImplList.elementAt(i);
2241
                    logMetacat.info("docid: " + documentId);
2242
                    // Get doicd without revision
2243
                    String docidWithoutRevision = MetaCatUtil
2244
                            .getDocIdFromString(documentId);
2245
                    logMetacat.info("docidWithoutRevsion: "
2246
                            + docidWithoutRevision);
2247
                    // Get revision
2248
                    String revision = MetaCatUtil
2249
                            .getRevisionStringFromString(documentId);
2250
                    logMetacat.info("revsion from docIdentifier: "
2251
                            + revision);
2252
                    // Zip entry string
2253
                    String zipEntryPath = rootName + "/data/";
2254
                    // Create a RemoteDocument object
2255
                    RemoteDocument remoteDoc = new RemoteDocument(
2256
                            docidWithoutRevision, revision, user, passWord,
2257
                            zipEntryPath);
2258
                    // Here we only read data file from remote metacat
2259
                    String docType = remoteDoc.getDocType();
2260
                    if (docType != null) {
2261
                        if (docType.equals("BIN")) {
2262
                            // Put remote document to zip output
2263
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2264
                            // Add String object to htmlDocumentImplList
2265
                            String elementInHtmlList = remoteDoc
2266
                                    .getDocIdWithoutRevsion()
2267
                                    + MetaCatUtil.getOption("accNumSeparator")
2268
                                    + remoteDoc.getRevision();
2269
                            htmlDocumentImplList.add(elementInHtmlList);
2270
                        }//if
2271
                    }//if
2272

    
2273
                }//if
2274
                else {
2275
                    //create a docmentImpls object (represent xml doc) base on
2276
                    // the docId
2277
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2278
                    //checking if the user has the permission to read the
2279
                    // documents
2280
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2281
                            .getDocID())) {
2282
                        //if the docImpls is metadata
2283
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2284
                            //add metadata into zip output stream
2285
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2286
                            //add the documentImpl into the vetor which will
2287
                            // be used in html
2288
                            htmlDocumentImplList.add(docImpls);
2289

    
2290
                        }//if
2291
                        else {
2292
                            //it is data file
2293
                            addDataFileToZipOutputStream(docImpls, zOut,
2294
                                    rootName);
2295
                            htmlDocumentImplList.add(docImpls);
2296
                        }//else
2297
                    }//if
2298
                }//else
2299
            }//for
2300

    
2301
            //add html summary file
2302
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2303
                    rootName);
2304
            zOut.finish(); //terminate the zip file
2305
            //dbConn.close();
2306
            return zOut;
2307
        }//else
2308
    }//getZippedPackage()
2309

    
2310
    private class ReturnFieldValue
2311
    {
2312

    
2313
        private String docid = null; //return field value for this docid
2314

    
2315
        private String fieldValue = null;
2316

    
2317
        private String xmlFieldValue = null; //return field value in xml
2318
                                             // format
2319

    
2320
        public void setDocid(String myDocid)
2321
        {
2322
            docid = myDocid;
2323
        }
2324

    
2325
        public String getDocid()
2326
        {
2327
            return docid;
2328
        }
2329

    
2330
        public void setFieldValue(String myValue)
2331
        {
2332
            fieldValue = myValue;
2333
        }
2334

    
2335
        public String getFieldValue()
2336
        {
2337
            return fieldValue;
2338
        }
2339

    
2340
        public void setXMLFieldValue(String xml)
2341
        {
2342
            xmlFieldValue = xml;
2343
        }
2344

    
2345
        public String getXMLFieldValue()
2346
        {
2347
            return xmlFieldValue;
2348
        }
2349

    
2350
    }
2351
}
(21-21/65)