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-06-08 11:09:26 -0700 (Thu, 08 Jun 2006) $'
15
 * '$Revision: 3003 $'
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
	 if(metacatSpatialData != null){
662
		metacatSpatialData.writeTextQueryData();
663
	 }
664
	
665
     return resultsetBuffer;
666
    }//findReturnDoclist
667

    
668

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

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

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

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

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

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

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

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

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

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

    
736

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

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

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

    
764
             dbconn.increaseUsageCount(1);
765
             pstmt.execute();
766
             pstmt.close();
767
         }
768

    
769
         // A string with element
770
         String xmlElement = "  <document>" + element + "</document>";
771

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

    
780

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

    
796
     return resultset;
797
 }
798

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

    
807
         Hashtable returnValue = new Hashtable();
808
         PreparedStatement pstmt = null;
809
         ResultSet rs = null;
810

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

    
821

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

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

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

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

    
865

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

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

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

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

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

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

    
912
           } else {
913
               rs.close();
914
               pstmt.close();
915

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

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

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

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

    
952
       returnfield_id = id;
953
       return count;
954
   }
955

    
956

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

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

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

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

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

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

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

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

    
1110
     }//if has extended query
1111

    
1112
      return docListResult;
1113
    }//addReturnfield
1114

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

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

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

    
1178
    return docListResult;
1179
  }//addRelation
1180

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

    
1201

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

    
1208
        Vector tempVector = null;
1209

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

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

    
1224
        Vector tempVector = null;
1225

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

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

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

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

    
1249
        Vector tempVector = null;
1250

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

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

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

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

    
1271
            enumVector.add(tempVector.get(1));
1272
        }
1273
        return enumVector;
1274
    }
1275

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

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

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

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

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

    
1353
    }
1354

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

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

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

    
1401

    
1402

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1577
        return (xmlquery.toString());
1578
    }
1579

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1727
        // return result
1728
        return docIdList;
1729
    }//getDocidListForPackageInXMLRevisions()
1730

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

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

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

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

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

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

    
1880
    }//addDocToZipOutputStream()
1881

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

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

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

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

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

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

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

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

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

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

    
1960
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1961

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

    
1988
        }//for
1989
        return documentImplList;
1990
    }//getOldVersionAllDocumentImple
1991

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

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

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

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

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

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

    
2105
    }//addHtmlSummaryToZipOutputStream
2106

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2305
    private class ReturnFieldValue
2306
    {
2307

    
2308
        private String docid = null; //return field value for this docid
2309

    
2310
        private String fieldValue = null;
2311

    
2312
        private String xmlFieldValue = null; //return field value in xml
2313
                                             // format
2314

    
2315
        public void setDocid(String myDocid)
2316
        {
2317
            docid = myDocid;
2318
        }
2319

    
2320
        public String getDocid()
2321
        {
2322
            return docid;
2323
        }
2324

    
2325
        public void setFieldValue(String myValue)
2326
        {
2327
            fieldValue = myValue;
2328
        }
2329

    
2330
        public String getFieldValue()
2331
        {
2332
            return fieldValue;
2333
        }
2334

    
2335
        public void setXMLFieldValue(String xml)
2336
        {
2337
            xmlFieldValue = xml;
2338
        }
2339

    
2340
        public String getXMLFieldValue()
2341
        {
2342
            return xmlFieldValue;
2343
        }
2344

    
2345
    }
2346
}
(21-21/65)