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
 *    Release: @release@
12
 *
13
 *   '$Author: sgarg $'
14
 *     '$Date: 2006-03-03 11:47:45 -0800 (Fri, 03 Mar 2006) $'
15
 * '$Revision: 2948 $'
16
 *
17
 * This program is free software; you can redistribute it and/or modify
18
 * it under the terms of the GNU General Public License as published by
19
 * the Free Software Foundation; either version 2 of the License, or
20
 * (at your option) any later version.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
 * GNU General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU General Public License
28
 * along with this program; if not, write to the Free Software
29
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30
 */
31

    
32
package edu.ucsb.nceas.metacat;
33

    
34
import java.io.BufferedWriter;
35
import java.io.File;
36
import java.io.FileInputStream;
37
import java.io.FileReader;
38
import java.io.FileWriter;
39
import java.io.IOException;
40
import java.io.InputStream;
41
import java.io.PrintWriter;
42
import java.io.StringReader;
43
import java.io.StringWriter;
44
import java.sql.PreparedStatement;
45
import java.sql.ResultSet;
46
import java.sql.SQLException;
47
import java.util.Enumeration;
48
import java.util.Hashtable;
49
import java.util.StringTokenizer;
50
import java.util.Vector;
51
import java.util.zip.ZipEntry;
52
import java.util.zip.ZipOutputStream;
53

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

    
57
import org.apache.log4j.Logger;
58

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

    
62
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialQuery;
63
import edu.ucsb.nceas.metacat.spatial.PersistentMetacatSpatialDataset;
64
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialDataset;
65
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialDocument;
66
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialConstants;
67

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

    
77
    static final int ALL = 1;
78

    
79
    static final int WRITE = 2;
80

    
81
    static final int READ = 4;
82

    
83
    //private Connection conn = null;
84
    private String parserName = null;
85

    
86
    private MetaCatUtil util = new MetaCatUtil();
87

    
88
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
89

    
90
    /** true if the metacat spatial option is installed **/
91
    private final boolean METACAT_SPATIAL = true;
92

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

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

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

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

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

    
130
                double connTime = System.currentTimeMillis();
131

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

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

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

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

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

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

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

    
206

    
207
  /**
208
   * Method put the search result set into out printerwriter
209
   * @param resoponse the return response
210
   * @param out the output printer
211
   * @param params the paratermer hashtable
212
   * @param user the user name (it maybe different to the one in param)
213
   * @param groups the group array
214
   * @param sessionid  the sessionid
215
   */
216
  public void findDocuments(HttpServletResponse response,
217
                                       PrintWriter out, Hashtable params,
218
                                       String user, String[] groups,
219
                                       String sessionid)
220
  {
221
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
222
               .booleanValue();
223
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
224

    
225
  }
226

    
227

    
228
    /**
229
     * Method put the search result set into out printerwriter
230
     * @param resoponse the return response
231
     * @param out the output printer
232
     * @param params the paratermer hashtable
233
     * @param user the user name (it maybe different to the one in param)
234
     * @param groups the group array
235
     * @param sessionid  the sessionid
236
     */
237
    public void findDocuments(HttpServletResponse response,
238
                                         PrintWriter out, Hashtable params,
239
                                         String user, String[] groups,
240
                                         String sessionid, boolean useXMLIndex)
241
    {
242
      // get query and qformat
243
      String xmlquery = ((String[])params.get("query"))[0];
244

    
245
      logMetacat.warn("xmlquery: " + xmlquery);
246
      String qformat = ((String[])params.get("qformat"))[0];
247
      logMetacat.warn("qformat: " + qformat);
248
      // Get the XML query and covert it into a SQL statment
249
      QuerySpecification qspec = null;
250
      if ( xmlquery != null)
251
      {
252
         xmlquery = transformQuery(xmlquery);
253
         try
254
         {
255
           qspec = new QuerySpecification(xmlquery,
256
                                          parserName,
257
                                          MetaCatUtil.getOption("accNumSeparator"));
258
         }
259
         catch (Exception ee)
260
         {
261
           logMetacat.error("error generating QuerySpecification object"
262
                                    +" in DBQuery.findDocuments"
263
                                    + ee.getMessage());
264
         }
265
      }
266

    
267

    
268

    
269
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
270
      {
271
        //xml format
272
        response.setContentType("text/xml");
273
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex);
274
      }//if
275
      else
276
      {
277
        //knb format, in this case we will get whole result and sent it out
278
        response.setContentType("text/html");
279
        PrintWriter nonout = null;
280
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
281
                                                groups, useXMLIndex);
282
        
283
        //transfer the xml to html
284
        try
285
        {
286

    
287
         DBTransform trans = new DBTransform();
288
         response.setContentType("text/html");
289

    
290
	 // if the user is a moderator, then pass a param to the 
291
         // xsl specifying the fact
292
         if(MetaCatUtil.isModerator(user, groups)){
293
        	 params.put("isModerator", new String[] {"true"});
294
         }
295

    
296
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
297
                                 "-//W3C//HTML//EN", qformat, out, params,
298
                                 sessionid);
299

    
300
        }
301
        catch(Exception e)
302
        {
303
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
304
                                +e.getMessage());
305
         }
306

    
307
      }//else
308

    
309
    }
310

    
311
  /*
312
   * Transforms a hashtable of documents to an xml or html result and sent
313
   * the content to outputstream. Keep going untill hastable is empty. stop it.
314
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
315
   * to xmlquery String
316
   */
317
  public StringBuffer createResultDocument(String xmlquery,
318
                                            QuerySpecification qspec,
319
                                            PrintWriter out,
320
                                            String user, String[] groups,
321
                                            boolean useXMLIndex)
322
  {
323
    DBConnection dbconn = null;
324
    int serialNumber = -1;
325
    StringBuffer resultset = new StringBuffer();
326
    resultset.append("<?xml version=\"1.0\"?>\n");
327
    resultset.append("<resultset>\n");
328
    resultset.append("  <query>" + xmlquery + "</query>");
329
    // sent query part out
330
    if (out != null)
331
    {
332
      out.println(resultset.toString());
333
    }
334
    if (qspec != null)
335
    {
336
      try
337
      {
338

    
339
        //checkout the dbconnection
340
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
341
        serialNumber = dbconn.getCheckOutSerialNumber();
342

    
343
        //print out the search result
344
        // search the doc list
345
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
346
                                      dbconn, useXMLIndex);
347

    
348
        
349

    
350
      } //try
351
      catch (IOException ioe)
352
      {
353
        logMetacat.error("IO error in DBQuery.findDocuments:");
354
        logMetacat.error(ioe.getMessage());
355

    
356
      }
357
      catch (SQLException e)
358
      {
359
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
360
                                 + e.getMessage());
361
      }
362
      catch (Exception ee)
363
      {
364
        logMetacat.error("Exception in DBQuery.findDocuments: "
365
                                 + ee.getMessage());
366
      }
367
      finally
368
      {
369
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
370
      } //finally
371
    }//if
372
    String closeRestultset = "</resultset>";
373
    resultset.append(closeRestultset);
374
    if (out != null)
375
    {
376
      out.println(closeRestultset);
377
    }
378

    
379
    return resultset;
380
  }//createResultDocuments
381

    
382

    
383

    
384
    /*
385
     * Find the doc list which match the query
386
     */
387
    private StringBuffer findResultDoclist(QuerySpecification qspec,
388
                                      StringBuffer resultsetBuffer,
389
                                      PrintWriter out,
390
                                      String user, String[]groups,
391
                                      DBConnection dbconn, boolean useXMLIndex )
392
                                      throws Exception
393
    {
394
      
395
      MetacatSpatialDataset metacatSpatialData = null; 
396
      
397
if (MetacatSpatialConstants.runSpatialOption == true  ) {
398
        metacatSpatialData = new MetacatSpatialDataset(); 
399
}  
400
      int offset = 1;
401
      // this is a hack for offset
402
      if (out == null)
403
      {
404
        // for html page, we put everything into one page
405
        offset =
406
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
407
      }
408
      else
409
      {
410
          offset =
411
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
412
      }
413

    
414
      int count = 0;
415
      int index = 0;
416
      Hashtable docListResult = new Hashtable();
417
      PreparedStatement pstmt = null;
418
      String docid = null;
419
      String docname = null;
420
      String doctype = null;
421
      String createDate = null;
422
      String updateDate = null;
423
      StringBuffer document = null;
424
      int rev = 0;
425
      String query = qspec.printSQL(useXMLIndex);
426
      String ownerQuery = getOwnerQuery(user);
427
      logMetacat.info("query: " + query);
428
      //logMetacat.info("query: "+ownerQuery);
429
      // if query is not the owner query, we need to check the permission
430
      // otherwise we don't need (owner has all permission by default)
431
      if (!query.equals(ownerQuery))
432
      {
433
        // set user name and group
434
        qspec.setUserName(user);
435
        qspec.setGroup(groups);
436
        // Get access query
437
        String accessQuery = qspec.getAccessQuery();
438
        if(!query.endsWith("WHERE")){
439
            query = query + accessQuery;
440
        } else {
441
            query = query + accessQuery.substring(4, accessQuery.length());
442
        }
443
        logMetacat.warn(" final query: " + query);
444
      }
445

    
446
      double startTime = System.currentTimeMillis() / 1000;
447
      pstmt = dbconn.prepareStatement(query);
448

    
449
      // Execute the SQL query using the JDBC connection
450
      pstmt.execute();
451
      ResultSet rs = pstmt.getResultSet();
452
      double queryExecuteTime = System.currentTimeMillis() / 1000;
453
      logMetacat.warn("Time for execute query: "
454
                    + (queryExecuteTime - startTime));
455
      boolean tableHasRows = rs.next();
456
      while (tableHasRows)
457
      {
458
        docid = rs.getString(1).trim();
459
        //if ( METACAT_SPATIAL ) {
460
	if (MetacatSpatialConstants.runSpatialOption == true  ) {
461
          System.out.println("###################################################");
462
          System.out.println("###################################################");
463
          System.out.println("###################################################");
464
          System.out.println("###################################################");
465
          System.out.println("###################################################");
466
          System.out.println("################ " + docid + " ####################");
467
          
468
          // make sure that the spatial dataset is initialized
469
          MetacatSpatialQuery spatialQuery = new  MetacatSpatialQuery();
470
          
471
          // create the spatial document 
472
          MetacatSpatialDocument msdoc = spatialQuery.getSpatialDocument(docid);
473

    
474
          // add the spatial document to the spatial dataset
475
          metacatSpatialData.add(msdoc);
476

    
477
          // write the persistent spatial dataset
478
          //////metacatSpatialData.write();
479
          
480
          System.out.println("###################################################");
481
          System.out.println("###################################################");
482
          System.out.println("###################################################");
483
          System.out.println("###################################################");
484
          System.out.println("###################################################");
485
        }
486
        docname = rs.getString(2);
487
        doctype = rs.getString(3);
488
        createDate = rs.getString(4);
489
        updateDate = rs.getString(5);
490
        rev = rs.getInt(6);
491

    
492
        // if there are returndocs to match, backtracking can be performed
493
        // otherwise, just return the document that was hit
494
        Vector returndocVec = qspec.getReturnDocList();
495
         if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
496
                        && !qspec.isPercentageSearch())
497
        {
498
           logMetacat.warn("Back tracing now...");
499
           String sep = MetaCatUtil.getOption("accNumSeparator");
500
           StringBuffer btBuf = new StringBuffer();
501
           btBuf.append("select docid from xml_relation where ");
502

    
503
           //build the doctype list for the backtracking sql statement
504
           btBuf.append("packagetype in (");
505
           for (int i = 0; i < returndocVec.size(); i++)
506
           {
507
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
508
             if (i != (returndocVec.size() - 1))
509
             {
510
                btBuf.append(", ");
511
              }
512
            }
513
            btBuf.append(") ");
514
            btBuf.append("and (subject like '");
515
            btBuf.append(docid).append("'");
516
            btBuf.append("or object like '");
517
            btBuf.append(docid).append("')");
518

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

    
555
                String docid_org = xmldoc.getDocID();
556
                if (docid_org == null)
557
                {
558
                   logMetacat.info("Docid_org was null.");
559
                   //continue;
560
                }
561
                docid = docid_org.trim();
562
                docname = xmldoc.getDocname();
563
                doctype = xmldoc.getDoctype();
564
                createDate = xmldoc.getCreateDate();
565
                updateDate = xmldoc.getUpdateDate();
566
                rev = xmldoc.getRev();
567
                document = new StringBuffer();
568

    
569
                String completeDocid = docid
570
                                + MetaCatUtil.getOption("accNumSeparator");
571
                completeDocid += rev;
572
                document.append("<docid>").append(completeDocid);
573
                document.append("</docid>");
574
                if (docname != null)
575
                {
576
                  document.append("<docname>" + docname + "</docname>");
577
                }
578
                if (doctype != null)
579
                {
580
                  document.append("<doctype>" + doctype + "</doctype>");
581
                }
582
                if (createDate != null)
583
                {
584
                 document.append("<createdate>" + createDate + "</createdate>");
585
                }
586
                if (updateDate != null)
587
                {
588
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
589
                }
590
                // Store the document id and the root node id
591
                docListResult.put(docid, (String) document.toString());
592
                count++;
593

    
594

    
595
                // Get the next package document linked to our hit
596
                hasBtRows = btrs.next();
597
              }//while
598
              npstmt.close();
599
              btrs.close();
600
        }
601
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
602
        {
603

    
604
           document = new StringBuffer();
605

    
606
           String completeDocid = docid
607
                            + MetaCatUtil.getOption("accNumSeparator");
608
           completeDocid += rev;
609
           document.append("<docid>").append(completeDocid).append("</docid>");
610
           if (docname != null)
611
           {
612
               document.append("<docname>" + docname + "</docname>");
613
            }
614
            if (doctype != null)
615
            {
616
               document.append("<doctype>" + doctype + "</doctype>");
617
            }
618
            if (createDate != null)
619
            {
620
                document.append("<createdate>" + createDate + "</createdate>");
621
             }
622
             if (updateDate != null)
623
             {
624
               document.append("<updatedate>" + updateDate + "</updatedate>");
625
             }
626
              // Store the document id and the root node id
627
              docListResult.put(docid, (String) document.toString());
628
              count++;
629

    
630

    
631
        }//else
632
        // when doclist reached the offset number, send out doc list and empty
633
        // the hash table
634
        if (count == offset)
635
        {
636
          //reset count
637
          count = 0;
638
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
639
                              user, groups,dbconn, useXMLIndex);
640
          // reset docListResult
641
          docListResult = new Hashtable();
642

    
643
        }
644
       // Advance to the next record in the cursor
645
       tableHasRows = rs.next();
646
     }//while
647
     rs.close();
648
     pstmt.close();
649
     //if docListResult is not empty, it need to be sent.
650
     if (!docListResult.isEmpty())
651
     {
652
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
653
                              user, groups,dbconn, useXMLIndex);
654
     }
655
     double docListTime = System.currentTimeMillis() / 1000;
656
     logMetacat.warn("prepare docid list time: "
657
                    + (docListTime - queryExecuteTime));
658

    
659
     
660
     //write the persistent spatial dataset
661
     metacatSpatialData.writeTextQueryData();
662

    
663
     return resultsetBuffer;
664
    }//findReturnDoclist
665

    
666

    
667
    /*
668
     * Send completed search hashtable(part of reulst)to output stream
669
     * and buffer into a buffer stream
670
     */
671
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
672
                                           StringBuffer resultset,
673
                                           PrintWriter out, Hashtable partOfDoclist,
674
                                           String user, String[]groups,
675
                                       DBConnection dbconn, boolean useXMLIndex)
676
                                       throws Exception
677
   {
678

    
679
     // check if there is a record in xml_returnfield
680
     // and get the returnfield_id and usage count
681
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
682
     boolean enterRecords = false;
683

    
684
     // get value of xml_returnfield_count
685
     int count = (new Integer(MetaCatUtil
686
                            .getOption("xml_returnfield_count")))
687
                            .intValue();
688

    
689
     // set enterRecords to true if usage_count is more than the offset
690
     // specified in metacat.properties
691
     if(usage_count > count){
692
         enterRecords = true;
693
     }
694

    
695
     if(returnfield_id < 0){
696
         logMetacat.warn("Error in getting returnfield id from"
697
                                  + "xml_returnfield table");
698
	enterRecords = false;
699
     }
700

    
701
     // get the hashtable containing the docids that already in the
702
     // xml_queryresult table
703
     logMetacat.info("size of partOfDoclist before"
704
                             + " docidsInQueryresultTable(): "
705
                             + partOfDoclist.size());
706
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
707
                                                        partOfDoclist, dbconn);
708

    
709
     // remove the keys in queryresultDocList from partOfDoclist
710
     Enumeration _keys = queryresultDocList.keys();
711
     while (_keys.hasMoreElements()){
712
         partOfDoclist.remove(_keys.nextElement());
713
     }
714

    
715
     // backup the keys-elements in partOfDoclist to check later
716
     // if the doc entry is indexed yet
717
     Hashtable partOfDoclistBackup = new Hashtable();
718
     _keys = partOfDoclist.keys();
719
     while (_keys.hasMoreElements()){
720
	 Object key = _keys.nextElement();
721
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
722
     }
723

    
724
     logMetacat.info("size of partOfDoclist after"
725
                             + " docidsInQueryresultTable(): "
726
                             + partOfDoclist.size());
727

    
728
     //add return fields for the documents in partOfDoclist
729
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
730
                                        dbconn, useXMLIndex );
731
     //add relationship part part docid list for the documents in partOfDocList
732
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
733

    
734

    
735
     Enumeration keys = partOfDoclist.keys();
736
     String key = null;
737
     String element = null;
738
     String query = null;
739
     int offset = (new Integer(MetaCatUtil
740
                               .getOption("queryresult_string_length")))
741
                               .intValue();
742
     while (keys.hasMoreElements())
743
     {
744
         key = (String) keys.nextElement();
745
         element = (String)partOfDoclist.get(key);
746

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

    
756
             PreparedStatement pstmt = null;
757
             pstmt = dbconn.prepareStatement(query);
758
             pstmt.setInt(1, returnfield_id);
759
             pstmt.setString(2, key);
760
             pstmt.setString(3, element);
761

    
762
             dbconn.increaseUsageCount(1);
763
             pstmt.execute();
764
             pstmt.close();
765
         }
766

    
767
         // A string with element
768
         String xmlElement = "  <document>" + element + "</document>";
769

    
770
         //send single element to output
771
         if (out != null)
772
         {
773
             out.println(xmlElement);
774
         }
775
         resultset.append(xmlElement);
776
     }//while
777

    
778

    
779
     keys = queryresultDocList.keys();
780
     while (keys.hasMoreElements())
781
     {
782
         key = (String) keys.nextElement();
783
         element = (String)queryresultDocList.get(key);
784
         // A string with element
785
         String xmlElement = "  <document>" + element + "</document>";
786
         //send single element to output
787
         if (out != null)
788
         {
789
             out.println(xmlElement);
790
         }
791
         resultset.append(xmlElement);
792
     }//while
793

    
794
     return resultset;
795
 }
796

    
797
   /**
798
    * Get the docids already in xml_queryresult table and corresponding
799
    * queryresultstring as a hashtable
800
    */
801
   private Hashtable docidsInQueryresultTable(int returnfield_id,
802
                                              Hashtable partOfDoclist,
803
                                              DBConnection dbconn){
804

    
805
         Hashtable returnValue = new Hashtable();
806
         PreparedStatement pstmt = null;
807
         ResultSet rs = null;
808

    
809
         // get partOfDoclist as string for the query
810
         Enumeration keylist = partOfDoclist.keys();
811
         StringBuffer doclist = new StringBuffer();
812
         while (keylist.hasMoreElements())
813
         {
814
             doclist.append("'");
815
             doclist.append((String) keylist.nextElement());
816
             doclist.append("',");
817
         }//while
818

    
819

    
820
         if (doclist.length() > 0)
821
         {
822
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
823

    
824
             // the query to find out docids from xml_queryresult
825
             String query = "select docid, queryresult_string from "
826
                          + "xml_queryresult where returnfield_id = " +
827
                          returnfield_id +" and docid in ("+ doclist + ")";
828
             logMetacat.info("Query to get docids from xml_queryresult:"
829
                                      + query);
830

    
831
             try {
832
                 // prepare and execute the query
833
                 pstmt = dbconn.prepareStatement(query);
834
                 dbconn.increaseUsageCount(1);
835
                 pstmt.execute();
836
                 rs = pstmt.getResultSet();
837
                 boolean tableHasRows = rs.next();
838
                 while (tableHasRows) {
839
                     // store the returned results in the returnValue hashtable
840
                     String key = rs.getString(1);
841
                     String element = rs.getString(2);
842

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

    
863

    
864
   /**
865
    * Method to get id from xml_returnfield table
866
    * for a given query specification
867
    */
868
   private int returnfield_id;
869
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
870
                                           DBConnection dbconn){
871
       int id = -1;
872
       int count = 1;
873
       PreparedStatement pstmt = null;
874
       ResultSet rs = null;
875
       String returnfield = qspec.getSortedReturnFieldString();
876

    
877
       // query for finding the id from xml_returnfield
878
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
879
            + "WHERE returnfield_string LIKE ?";
880
       logMetacat.info("ReturnField Query:" + query);
881

    
882
       try {
883
           // prepare and run the query
884
           pstmt = dbconn.prepareStatement(query);
885
           pstmt.setString(1,returnfield);
886
           dbconn.increaseUsageCount(1);
887
           pstmt.execute();
888
           rs = pstmt.getResultSet();
889
           boolean tableHasRows = rs.next();
890

    
891
           // if record found then increase the usage count
892
           // else insert a new record and get the id of the new record
893
           if(tableHasRows){
894
               // get the id
895
               id = rs.getInt(1);
896
               count = rs.getInt(2) + 1;
897
               rs.close();
898
               pstmt.close();
899

    
900
               // increase the usage count
901
               query = "UPDATE xml_returnfield SET usage_count ='" + count
902
                   + "' WHERE returnfield_id ='"+ id +"'";
903
               logMetacat.info("ReturnField Table Update:"+ query);
904

    
905
               pstmt = dbconn.prepareStatement(query);
906
               dbconn.increaseUsageCount(1);
907
               pstmt.execute();
908
               pstmt.close();
909

    
910
           } else {
911
               rs.close();
912
               pstmt.close();
913

    
914
               // insert a new record
915
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
916
                   + "VALUES (?, '1')";
917
               logMetacat.info("ReturnField Table Insert:"+ query);
918
               pstmt = dbconn.prepareStatement(query);
919
               pstmt.setString(1, returnfield);
920
               dbconn.increaseUsageCount(1);
921
               pstmt.execute();
922
               pstmt.close();
923

    
924
               // get the id of the new record
925
               query = "SELECT returnfield_id FROM xml_returnfield "
926
                   + "WHERE returnfield_string LIKE ?";
927
               logMetacat.info("ReturnField query after Insert:" + query);
928
               pstmt = dbconn.prepareStatement(query);
929
               pstmt.setString(1, returnfield);
930

    
931
               dbconn.increaseUsageCount(1);
932
               pstmt.execute();
933
               rs = pstmt.getResultSet();
934
               if(rs.next()){
935
                   id = rs.getInt(1);
936
               } else {
937
                   id = -1;
938
               }
939
               rs.close();
940
               pstmt.close();
941
           }
942

    
943
       } catch (Exception e){
944
           logMetacat.error("Error getting id from xml_returnfield in "
945
                                     + "DBQuery.getXmlReturnfieldsTableId: "
946
                                     + e.getMessage());
947
           id = -1;
948
       }
949

    
950
       returnfield_id = id;
951
       return count;
952
   }
953

    
954

    
955
    /*
956
     * A method to add return field to return doclist hash table
957
     */
958
    private Hashtable addReturnfield(Hashtable docListResult,
959
                                      QuerySpecification qspec,
960
                                      String user, String[]groups,
961
                                      DBConnection dbconn, boolean useXMLIndex )
962
                                      throws Exception
963
    {
964
      PreparedStatement pstmt = null;
965
      ResultSet rs = null;
966
      String docid = null;
967
      String fieldname = null;
968
      String fielddata = null;
969
      String relation = null;
970

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

    
1009
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
1010
           logMetacat.info( "Time for execute access extended query: "
1011
                          + (extendedAccessQueryEnd - extendedQueryStart));
1012

    
1013
           String extendedQuery =
1014
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
1015
           logMetacat.warn("Extended query: " + extendedQuery);
1016

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

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

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

    
1103
           // get attribures return
1104
           docListResult = getAttributeValueForReturn(qspec,
1105
                           docListResult, doclist.toString(), useXMLIndex);
1106
       }//if doclist lenght is great than zero
1107

    
1108
     }//if has extended query
1109

    
1110
      return docListResult;
1111
    }//addReturnfield
1112

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

    
1145
        document = new StringBuffer();
1146
        document.append("<triple>");
1147
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1148
        document.append("</subject>");
1149
        if (subDT != null)
1150
        {
1151
          document.append("<subjectdoctype>").append(subDT);
1152
          document.append("</subjectdoctype>");
1153
        }
1154
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1155
        document.append("</relationship>");
1156
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1157
        document.append("</object>");
1158
        if (objDT != null)
1159
        {
1160
          document.append("<objectdoctype>").append(objDT);
1161
          document.append("</objectdoctype>");
1162
        }
1163
        document.append("</triple>");
1164

    
1165
        String removedelement = (String) docListResult.remove(docidkey);
1166
        docListResult.put(docidkey, removedelement+ document.toString());
1167
        tableHasRows = rs.next();
1168
      }//while
1169
      rs.close();
1170
      pstmt.close();
1171
    }//while
1172
    double endRelation = System.currentTimeMillis() / 1000;
1173
    logMetacat.info("Time for adding relation to docListResult: "
1174
                             + (endRelation - startRelation));
1175

    
1176
    return docListResult;
1177
  }//addRelation
1178

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

    
1199

    
1200
    /*
1201
     * A method to search if Vector contains a particular key string
1202
     */
1203
    private boolean containsKey(Vector parentidList, String parentId)
1204
    {
1205

    
1206
        Vector tempVector = null;
1207

    
1208
        for (int count = 0; count < parentidList.size(); count++) {
1209
            tempVector = (Vector) parentidList.get(count);
1210
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1211
        }
1212
        return false;
1213
    }
1214

    
1215
    /*
1216
     * A method to put key and value in Vector
1217
     */
1218
    private void putInArray(Vector parentidList, String key,
1219
            ReturnFieldValue value)
1220
    {
1221

    
1222
        Vector tempVector = null;
1223

    
1224
        for (int count = 0; count < parentidList.size(); count++) {
1225
            tempVector = (Vector) parentidList.get(count);
1226

    
1227
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1228
                tempVector.remove(1);
1229
                tempVector.add(1, value);
1230
                return;
1231
            }
1232
        }
1233

    
1234
        tempVector = new Vector();
1235
        tempVector.add(0, key);
1236
        tempVector.add(1, value);
1237
        parentidList.add(tempVector);
1238
        return;
1239
    }
1240

    
1241
    /*
1242
     * A method to get value in Vector given a key
1243
     */
1244
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1245
    {
1246

    
1247
        Vector tempVector = null;
1248

    
1249
        for (int count = 0; count < parentidList.size(); count++) {
1250
            tempVector = (Vector) parentidList.get(count);
1251

    
1252
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1253
                    .get(1); }
1254
        }
1255
        return null;
1256
    }
1257

    
1258
    /*
1259
     * A method to get enumeration of all values in Vector
1260
     */
1261
    private Vector getElements(Vector parentidList)
1262
    {
1263
        Vector enumVector = new Vector();
1264
        Vector tempVector = null;
1265

    
1266
        for (int count = 0; count < parentidList.size(); count++) {
1267
            tempVector = (Vector) parentidList.get(count);
1268

    
1269
            enumVector.add(tempVector.get(1));
1270
        }
1271
        return enumVector;
1272
    }
1273

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

    
1289
        //check the parameter
1290
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1291

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

    
1310
                    XML.append("<param name=\"");
1311
                    XML.append(fieldname);
1312
                    XML.append("/");
1313
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1314
                    XML.append(attirbuteName);
1315
                    XML.append("\">");
1316
                    XML.append(fielddata);
1317
                    XML.append("</param>");
1318
                    tableHasRows = rs.next();
1319

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

    
1351
    }
1352

    
1353
    /*
1354
     * A method to create a query to get owner's docid list
1355
     */
1356
    private String getOwnerQuery(String owner)
1357
    {
1358
        if (owner != null) {
1359
            owner = owner.toLowerCase();
1360
        }
1361
        StringBuffer self = new StringBuffer();
1362

    
1363
        self.append("SELECT docid,docname,doctype,");
1364
        self.append("date_created, date_updated, rev ");
1365
        self.append("FROM xml_documents WHERE docid IN (");
1366
        self.append("(");
1367
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1368
        self.append("nodedata LIKE '%%%' ");
1369
        self.append(") \n");
1370
        self.append(") ");
1371
        self.append(" AND (");
1372
        self.append(" lower(user_owner) = '" + owner + "'");
1373
        self.append(") ");
1374
        return self.toString();
1375
    }
1376

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

    
1399

    
1400

    
1401
        if (params.containsKey("meta_file_id")) {
1402
            query.append("<meta_file_id>");
1403
            query.append(((String[]) params.get("meta_file_id"))[0]);
1404
            query.append("</meta_file_id>");
1405
        }
1406

    
1407
        if (params.containsKey("returndoctype")) {
1408
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1409
            for (int i = 0; i < returnDoctypes.length; i++) {
1410
                String doctype = (String) returnDoctypes[i];
1411

    
1412
                if (!doctype.equals("any") && !doctype.equals("ANY")
1413
                        && !doctype.equals("")) {
1414
                    query.append("<returndoctype>").append(doctype);
1415
                    query.append("</returndoctype>");
1416
                }
1417
            }
1418
        }
1419

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

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

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

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

    
1452
        //allows the dynamic switching of boolean operators
1453
        if (params.containsKey("operator")) {
1454
            query.append("<querygroup operator=\""
1455
                    + ((String[]) params.get("operator"))[0] + "\">");
1456
        } else { //the default operator is UNION
1457
            query.append("<querygroup operator=\"UNION\">");
1458
        }
1459

    
1460
        if (params.containsKey("casesensitive")) {
1461
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1462
        } else {
1463
            casesensitive = "false";
1464
        }
1465

    
1466
        if (params.containsKey("searchmode")) {
1467
            searchmode = ((String[]) params.get("searchmode"))[0];
1468
        } else {
1469
            searchmode = "contains";
1470
        }
1471

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

    
1489
        //this while loop finds the rest of the parameters
1490
        //and attempts to query for the field specified
1491
        //by the parameter.
1492
        elements = params.elements();
1493
        keys = params.keys();
1494
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1495
            nextkey = keys.nextElement();
1496
            nextelement = elements.nextElement();
1497

    
1498
            //make sure we aren't querying for any of these
1499
            //parameters since the are already in the query
1500
            //in one form or another.
1501
            Vector ignoredParams = new Vector();
1502
            ignoredParams.add("returndoctype");
1503
            ignoredParams.add("filterdoctype");
1504
            ignoredParams.add("action");
1505
            ignoredParams.add("qformat");
1506
            ignoredParams.add("anyfield");
1507
            ignoredParams.add("returnfield");
1508
            ignoredParams.add("owner");
1509
            ignoredParams.add("site");
1510
            ignoredParams.add("operator");
1511
            ignoredParams.add("sessionid");
1512

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

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

    
1557
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1558
            xmlquery.append("<returndoctype>");
1559
            xmlquery.append(doctype).append("</returndoctype>");
1560
        }
1561

    
1562
        xmlquery.append("<querygroup operator=\"UNION\">");
1563
        //chad added - 8/14
1564
        //the if statement allows a query to gracefully handle a null
1565
        //query. Without this if a nullpointerException is thrown.
1566
        if (!value.equals("")) {
1567
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1568
            xmlquery.append("searchmode=\"contains\">");
1569
            xmlquery.append("<value>").append(value).append("</value>");
1570
            xmlquery.append("</queryterm>");
1571
        }
1572
        xmlquery.append("</querygroup>");
1573
        xmlquery.append("</pathquery>");
1574

    
1575
        return (xmlquery.toString());
1576
    }
1577

    
1578
    /**
1579
     * format a simple free-text value query as an XML document that conforms
1580
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1581
     * structured query engine
1582
     *
1583
     * @param value the text string to search for in the xml catalog
1584
     */
1585
    public static String createQuery(String value)
1586
    {
1587
        return createQuery(value, "any");
1588
    }
1589

    
1590
    /**
1591
     * Check for "READ" permission on @docid for @user and/or @group from DB
1592
     * connection
1593
     */
1594
    private boolean hasPermission(String user, String[] groups, String docid)
1595
            throws SQLException, Exception
1596
    {
1597
        // Check for READ permission on @docid for @user and/or @groups
1598
        PermissionController controller = new PermissionController(docid);
1599
        return controller.hasPermission(user, groups,
1600
                AccessControlInterface.READSTRING);
1601
    }
1602

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

    
1618
        // Check the parameter
1619
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1620

    
1621
        //the query stirng
1622
        String query = "SELECT subject, object from xml_relation where docId = ?";
1623
        try {
1624
            dbConn = DBConnectionPool
1625
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1626
            serialNumber = dbConn.getCheckOutSerialNumber();
1627
            pStmt = dbConn.prepareStatement(query);
1628
            //bind the value to query
1629
            pStmt.setString(1, dataPackageDocid);
1630

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

    
1646
                //don't put the duplicate docId into the vector
1647
                if (!docIdList.contains(docIdInSubjectField)) {
1648
                    docIdList.add(docIdInSubjectField);
1649
                }
1650

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

    
1679
    /**
1680
     * Get all docIds list for a data packadge
1681
     *
1682
     * @param dataPackageDocid, the string in docId field of xml_relation table
1683
     */
1684
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1685
    {
1686

    
1687
        Vector docIdList = new Vector();//return value
1688
        Vector tripleList = null;
1689
        String xml = null;
1690

    
1691
        // Check the parameter
1692
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1693

    
1694
        try {
1695
            //initial a documentImpl object
1696
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1697
            //transfer to documentImpl object to string
1698
            xml = packageDocument.toString();
1699

    
1700
            //create a tripcollection object
1701
            TripleCollection tripleForPackage = new TripleCollection(
1702
                    new StringReader(xml));
1703
            //get the vetor of triples
1704
            tripleList = tripleForPackage.getCollection();
1705

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

    
1725
        // return result
1726
        return docIdList;
1727
    }//getDocidListForPackageInXMLRevisions()
1728

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

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

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

    
1830
        }//try
1831
        catch (SQLException e) {
1832
            logMetacat.error(
1833
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1834
                            + e.getMessage());
1835
            throw e;
1836
        }//catch
1837
        finally {
1838
            try {
1839
                pStmt.close();
1840
            }//try
1841
            catch (SQLException ee) {
1842
                logMetacat.error(
1843
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1844
                                + ee.getMessage());
1845
            }//catch
1846
            finally {
1847
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1848
            }//finally
1849
        }//finally
1850
        return rev;
1851
    }//getCurrentRevFromXMLDoumentsTable
1852

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

    
1869
        byteString = docImpl.toString().getBytes();
1870
        //use docId as the zip entry's name
1871
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1872
                + docImpl.getDocID());
1873
        zEntry.setSize(byteString.length);
1874
        zipOut.putNextEntry(zEntry);
1875
        zipOut.write(byteString, 0, byteString.length);
1876
        zipOut.closeEntry();
1877

    
1878
    }//addDocToZipOutputStream()
1879

    
1880
    /**
1881
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1882
     * only inlcudes current version. If a DocumentImple object couldn't find
1883
     * for a docid, then the String of this docid was added to vetor rather
1884
     * than DocumentImple object.
1885
     *
1886
     * @param docIdList, a vetor hold a docid list for a data package. In
1887
     *            docid, there is not version number in it.
1888
     */
1889

    
1890
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1891
            throws McdbException, Exception
1892
    {
1893
        //Connection dbConn=null;
1894
        Vector documentImplList = new Vector();
1895
        int rev = 0;
1896

    
1897
        // Check the parameter
1898
        if (docIdList.isEmpty()) { return documentImplList; }//if
1899

    
1900
        //for every docid in vector
1901
        for (int i = 0; i < docIdList.size(); i++) {
1902
            try {
1903
                //get newest version for this docId
1904
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1905
                        .elementAt(i));
1906

    
1907
                // There is no record for this docId in xml_documents table
1908
                if (rev == -5) {
1909
                    // Rather than put DocumentImple object, put a String
1910
                    // Object(docid)
1911
                    // into the documentImplList
1912
                    documentImplList.add((String) docIdList.elementAt(i));
1913
                    // Skip other code
1914
                    continue;
1915
                }
1916

    
1917
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1918
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1919

    
1920
                //create new documentImpl object
1921
                DocumentImpl documentImplObject = new DocumentImpl(
1922
                        docidPlusVersion);
1923
                //add them to vector
1924
                documentImplList.add(documentImplObject);
1925
            }//try
1926
            catch (Exception e) {
1927
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
1928
                        + e.getMessage());
1929
                // continue the for loop
1930
                continue;
1931
            }
1932
        }//for
1933
        return documentImplList;
1934
    }
1935

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

    
1952
        // Check the parameter
1953
        if (docIdList.isEmpty()) { return documentImplList; }//if
1954

    
1955
        //for every docid in vector
1956
        for (int i = 0; i < docIdList.size(); i++) {
1957

    
1958
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1959

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

    
1986
        }//for
1987
        return documentImplList;
1988
    }//getOldVersionAllDocumentImple
1989

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

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

    
2046
        //create a DBTransform ojbect
2047
        xmlToHtml = new DBTransform();
2048
        //head of html
2049
        htmlDoc.append("<html><head></head><body>");
2050
        for (int i = 0; i < docImplList.size(); i++) {
2051
            // If this String object, this means it is missed data file
2052
            if ((((docImplList.elementAt(i)).getClass()).toString())
2053
                    .equals("class java.lang.String")) {
2054

    
2055
                htmlDoc.append("<a href=\"");
2056
                String dataFileid = (String) docImplList.elementAt(i);
2057
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2058
                htmlDoc.append("Data File: ");
2059
                htmlDoc.append(dataFileid).append("</a><br>");
2060
                htmlDoc.append("<br><hr><br>");
2061

    
2062
            }//if
2063
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2064
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2065
                                              // transform it.
2066
                //transform each file individually then concatenate all of the
2067
                //transformations together.
2068

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

    
2103
    }//addHtmlSummaryToZipOutputStream
2104

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

    
2129
        String docId = null;
2130
        int version = -5;
2131
        // Docid without revision
2132
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2133
        // revision number
2134
        version = MetaCatUtil.getVersionFromString(docIdString);
2135

    
2136
        //check if the reqused docId is a data package id
2137
        if (!isDataPackageId(docId)) {
2138

    
2139
            /*
2140
             * Exception e = new Exception("The request the doc id "
2141
             * +docIdString+ " is not a data package id");
2142
             */
2143

    
2144
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2145
            // zip
2146
            //up the single document and return the zip file.
2147
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2148

    
2149
                Exception e = new Exception("User " + user
2150
                        + " does not have permission"
2151
                        + " to export the data package " + docIdString);
2152
                throw e;
2153
            }
2154

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

    
2172
            zOut.finish(); //terminate the zip file
2173
            return zOut;
2174
        }
2175
        // Check the permission of user
2176
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2177

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

    
2203
            }//if
2204
            else if (version > currentVersion || version < -1) {
2205
                throw new Exception("The user specified docid: " + docId + "."
2206
                        + version + " doesn't exist");
2207
            }//else if
2208
            else //for an old version
2209
            {
2210

    
2211
                rootName = docIdString
2212
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2213
                //get the whole id list for data packadge
2214
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2215

    
2216
                //get the whole documentImple object
2217
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2218
            }//else
2219

    
2220
            // Make sure documentImplist is not empty
2221
            if (documentImplList.isEmpty()) { throw new Exception(
2222
                    "Couldn't find component for data package: " + packageId); }//if
2223

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

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

    
2283
                        }//if
2284
                        else {
2285
                            //it is data file
2286
                            addDataFileToZipOutputStream(docImpls, zOut,
2287
                                    rootName);
2288
                            htmlDocumentImplList.add(docImpls);
2289
                        }//else
2290
                    }//if
2291
                }//else
2292
            }//for
2293

    
2294
            //add html summary file
2295
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2296
                    rootName);
2297
            zOut.finish(); //terminate the zip file
2298
            //dbConn.close();
2299
            return zOut;
2300
        }//else
2301
    }//getZippedPackage()
2302

    
2303
    private class ReturnFieldValue
2304
    {
2305

    
2306
        private String docid = null; //return field value for this docid
2307

    
2308
        private String fieldValue = null;
2309

    
2310
        private String xmlFieldValue = null; //return field value in xml
2311
                                             // format
2312

    
2313
        public void setDocid(String myDocid)
2314
        {
2315
            docid = myDocid;
2316
        }
2317

    
2318
        public String getDocid()
2319
        {
2320
            return docid;
2321
        }
2322

    
2323
        public void setFieldValue(String myValue)
2324
        {
2325
            fieldValue = myValue;
2326
        }
2327

    
2328
        public String getFieldValue()
2329
        {
2330
            return fieldValue;
2331
        }
2332

    
2333
        public void setXMLFieldValue(String xml)
2334
        {
2335
            xmlFieldValue = xml;
2336
        }
2337

    
2338
        public String getXMLFieldValue()
2339
        {
2340
            return xmlFieldValue;
2341
        }
2342

    
2343
    }
2344
}
(21-21/65)