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: perry $'
14
 *     '$Date: 2006-10-04 14:44:38 -0700 (Wed, 04 Oct 2006) $'
15
 * '$Revision: 3055 $'
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

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

    
72
    static final int ALL = 1;
73

    
74
    static final int WRITE = 2;
75

    
76
    static final int READ = 4;
77

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

    
81
    private MetaCatUtil util = new MetaCatUtil();
82

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

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

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

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

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

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

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

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

    
128
                double connTime = System.currentTimeMillis();
129

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

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

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

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

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

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

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

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

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

    
244
  }
245

    
246

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

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

    
286

    
287

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

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

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

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

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

    
326
      }//else
327

    
328
    }
329

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

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

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

    
367
        
368

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

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

    
398
    return resultset;
399
  }//createResultDocuments
400

    
401

    
402

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

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

    
440
      String query = null;
441

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

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

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

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

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

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

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

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

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

    
605

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

    
615
           document = new StringBuffer();
616

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

    
641

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

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

    
670

    
671
     return resultsetBuffer;
672
    }//findReturnDoclist
673

    
674

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

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

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

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

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

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

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

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

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

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

    
742

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

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

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

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

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

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

    
786

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

    
802
     return resultset;
803
 }
804

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

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

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

    
827

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

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

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

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

    
871

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

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

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

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

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

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

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

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

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

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

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

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

    
962

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

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

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

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

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

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

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

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

    
1116
     }//if has extended query
1117

    
1118
      return docListResult;
1119
    }//addReturnfield
1120

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

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

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

    
1184
    return docListResult;
1185
  }//addRelation
1186

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

    
1207

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

    
1214
        Vector tempVector = null;
1215

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

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

    
1230
        Vector tempVector = null;
1231

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

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

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

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

    
1255
        Vector tempVector = null;
1256

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

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

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

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

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

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

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

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

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

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

    
1359
    }
1360

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

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

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

    
1407

    
1408

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1886
    }//addDocToZipOutputStream()
1887

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2063
                htmlDoc.append("<a href=\"");
2064
                String dataFileid = (String) docImplList.elementAt(i);
2065
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2066
                htmlDoc.append("Data File: ");
2067
                htmlDoc.append(dataFileid).append("</a><br>");
2068
                htmlDoc.append("<br><hr><br>");
2069

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

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

    
2111
    }//addHtmlSummaryToZipOutputStream
2112

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2311
    private class ReturnFieldValue
2312
    {
2313

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

    
2316
        private String fieldValue = null;
2317

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

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

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

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

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

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

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

    
2351
    }
2352
}
(21-21/65)