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: tao $'
14
 *     '$Date: 2002-06-13 11:54:51 -0700 (Thu, 13 Jun 2002) $'
15
 * '$Revision: 1217 $'
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 edu.ucsb.nceas.morpho.datapackage.*;
35
import java.io.*;
36
import java.util.Vector;
37
import java.util.zip.*;
38
import java.net.URL;
39
import java.net.MalformedURLException;
40
import java.sql.*;
41
import java.util.Stack;
42
import java.util.Hashtable;
43
import java.util.Enumeration;
44
import java.io.File;
45
import java.io.FileWriter;
46
import java.io.BufferedWriter;
47
import javax.servlet.ServletOutputStream;
48

    
49
/** 
50
 * A Class that searches a relational DB for elements and 
51
 * attributes that have free text matches a query string,
52
 * or structured query matches to a path specified node in the 
53
 * XML hierarchy.  It returns a result set consisting of the 
54
 * document ID for each document that satisfies the query
55
 */
56
public class DBQuery {
57

    
58
  static final int ALL = 1;
59
  static final int WRITE = 2;
60
  static final int READ = 4;
61
 
62
  //private Connection  conn = null;
63
  private String  parserName = null;
64
  private MetaCatUtil util = new MetaCatUtil();
65
  /**
66
   * the main routine used to test the DBQuery utility.
67
   * <p>
68
   * Usage: java DBQuery <xmlfile>
69
   *
70
   * @param xmlfile the filename of the xml file containing the query
71
   */
72
  static public void main(String[] args) {
73
     
74
     if (args.length < 1)
75
     {
76
        System.err.println("Wrong number of arguments!!!");
77
        System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
78
        return;
79
     } else {
80
        try {
81

    
82
          int i = 0;
83
          boolean showRuntime = false;
84
          boolean useXMLIndex = false;
85
          if ( args[i].equals( "-t" ) ) {
86
            showRuntime = true;
87
            i++;
88
          }
89
          if ( args[i].equals( "-index" ) ) {
90
            useXMLIndex = true;
91
            i++;
92
          } 
93
          String xmlfile  = args[i];
94

    
95
          // Time the request if asked for
96
          double startTime = System.currentTimeMillis();
97

    
98
          // Open a connection to the database
99
          MetaCatUtil   util = new MetaCatUtil();
100
          //Connection dbconn = util.openDBConnection();
101

    
102
          double connTime = System.currentTimeMillis();
103

    
104
          // Execute the query
105
          DBQuery queryobj = new DBQuery(util.getOption("saxparser"));
106
          FileReader xml = new FileReader(new File(xmlfile));
107
          Hashtable nodelist = null;
108
          nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
109

    
110
          // Print the reulting document listing
111
          StringBuffer result = new StringBuffer();
112
          String document = null;
113
          String docid = null;
114
          result.append("<?xml version=\"1.0\"?>\n");
115
          result.append("<resultset>\n"); 
116
  
117
          if (!showRuntime)
118
          {
119
            Enumeration doclist = nodelist.keys();
120
            while (doclist.hasMoreElements()) {
121
              docid = (String)doclist.nextElement();
122
              document = (String)nodelist.get(docid);
123
              result.append("  <document>\n    " + document + 
124
                            "\n  </document>\n");
125
            }
126
            
127
            result.append("</resultset>\n");
128
          }
129
          // Time the request if asked for
130
          double stopTime = System.currentTimeMillis();
131
          double dbOpenTime = (connTime - startTime)/1000;
132
          double readTime = (stopTime - connTime)/1000;
133
          double executionTime = (stopTime - startTime)/1000;
134
          if (showRuntime) {
135
            System.out.print("  " + executionTime);
136
            System.out.print("  " + dbOpenTime);
137
            System.out.print("  " + readTime);
138
            System.out.print("  " + nodelist.size());
139
            System.out.println();
140
          }
141
          //System.out.println(result);
142
          //write into a file "result.txt"
143
          if (!showRuntime)
144
          {
145
            File f = new File("./result.txt");
146
            FileWriter fw = new FileWriter(f);
147
            BufferedWriter out = new BufferedWriter(fw);
148
            out.write(result.toString());          
149
            out.flush();
150
            out.close();
151
            fw.close();
152
          }
153
          
154
        } 
155
        catch (Exception e) {
156
          System.err.println("Error in DBQuery.main");
157
          System.err.println(e.getMessage());
158
          e.printStackTrace(System.err);
159
        }
160
     }
161
  }
162
  
163
  /**
164
   * construct an instance of the DBQuery class 
165
   *
166
   * <p>Generally, one would call the findDocuments() routine after creating 
167
   * an instance to specify the search query</p>
168
   *
169
   * @param conn the JDBC connection that we use for the query
170
   * @param parserName the fully qualified name of a Java class implementing
171
   *                   the org.xml.sax.XMLReader interface
172
   */
173
  public DBQuery(String parserName ) 
174
                  throws IOException, 
175
                         SQLException, 
176
                         ClassNotFoundException {
177
    //this.conn = conn;
178
    this.parserName = parserName;
179
  }
180
  
181
  /** 
182
   * routine to search the elements and attributes looking to match query
183
   *
184
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
185
   * @param user the username of the user
186
   * @param group the group of the user
187
   */
188
  public Hashtable findDocuments(Reader xmlquery, String user, String[] groups)
189
  {
190
    return findDocuments(xmlquery, user, groups, true);
191
  }
192

    
193
  /** 
194
   * routine to search the elements and attributes looking to match query
195
   *
196
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
197
   * @param user the username of the user
198
   * @param group the group of the user
199
   * @param useXMLIndex flag whether to search using the path index
200
   */
201
  public Hashtable findDocuments(Reader xmlquery, String user, String[] groups,
202
                                 boolean useXMLIndex)
203
  {
204
      Hashtable   docListResult = new Hashtable();
205
      PreparedStatement pstmt = null;
206
      String docid = null;
207
      String docname = null;
208
      String doctype = null;
209
      String createDate = null;
210
      String updateDate = null;
211
      String fieldname = null;
212
      String fielddata = null;
213
      String relation = null;
214
      //Connection dbconn = null;
215
      //Connection dbconn2 = null;
216
      int rev = 0;
217
      StringBuffer document = null;
218
      DBConnection dbconn = null;
219
      int serialNumber = -1;
220
      
221
      try {
222
        /*if (conn == null || conn.isClosed()) {
223
          dbconn = util.openDBConnection();
224
        } else {
225
          dbconn = conn;
226
        }*/
227
        
228
        dbconn=DBConnectionPool.getDBConnection("DBQuery.findDocuments");
229
        serialNumber=dbconn.getCheckOutSerialNumber();
230
        // problem with ODBC driver multi-threading
231
     //   dbconn2 = util.openDBConnection(); // for use by AccessControlList
232
        
233
        // Get the XML query and covert it into a SQL statment
234
        QuerySpecification qspec = new QuerySpecification(xmlquery, 
235
                                   parserName, 
236
                                   util.getOption("accNumSeparator"));
237
  //System.out.println(qspec.printSQL(useXMLIndex)); 
238
        pstmt = dbconn.prepareStatement( qspec.printSQL(useXMLIndex) );
239
  
240
        // Execute the SQL query using the JDBC connection
241
        pstmt.execute();
242
        ResultSet rs = pstmt.getResultSet();
243
        boolean tableHasRows = rs.next();
244
        while (tableHasRows) 
245
        {
246
          docid = rs.getString(1).trim();
247
          if ( !hasPermission(user, groups, docid) ) {
248
            // Advance to the next record in the cursor
249
            tableHasRows = rs.next();
250
            continue;
251
          }
252
          docname = rs.getString(2);
253
          doctype = rs.getString(3);
254
          createDate = rs.getString(4);
255
          updateDate = rs.getString(5);
256
          rev = rs.getInt(6);
257

    
258
          // if there are returndocs to match, backtracking can be performed
259
          // otherwise, just return the document that was hit
260
          Vector returndocVec = qspec.getReturnDocList();
261
          if (returndocVec.size() != 0 && !returndocVec.contains(doctype))
262
          { 
263
            MetaCatUtil.debugMessage("Back tracing now...", 50);
264
            String sep = util.getOption("accNumSeparator");
265
            StringBuffer btBuf = new StringBuffer();
266
            btBuf.append("select docid from xml_relation where ");
267

    
268
            //build the doctype list for the backtracking sql statement
269
            btBuf.append("packagetype in (");
270
            for(int i=0; i<returndocVec.size(); i++)
271
            {
272
              btBuf.append("'").append((String)returndocVec.get(i)).append("'");
273
              if (i != (returndocVec.size() - 1))
274
              {
275
                btBuf.append(", ");
276
              } 
277
            }
278
            btBuf.append(") ");
279

    
280
            btBuf.append("and (subject like '");
281
            btBuf.append(docid).append(sep).append(rev).append("'");
282
            btBuf.append("or object like '");
283
            btBuf.append(docid).append(sep).append(rev).append("')");
284
            
285
            PreparedStatement npstmt = dbconn.
286
                                       prepareStatement(btBuf.toString());
287
            //should incease usage count
288
            dbconn.increaseUsageCount(1);
289
            npstmt.execute();
290
            ResultSet btrs = npstmt.getResultSet();
291
            boolean hasBtRows = btrs.next();
292
            while (hasBtRows)
293
            { //there was a backtrackable document found
294
              DocumentImpl xmldoc = null;
295
              String packageDocid = btrs.getString(1);
296
              util.debugMessage("Getting document for docid: "+packageDocid,40);
297
              try
298
              {
299
                //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not needed here
300
                // xmldoc = new DocumentImpl(dbconn, packageDocid);
301
                //  thus use the following to get the doc info only
302
                //  xmldoc = new DocumentImpl(dbconn);
303
                xmldoc = new DocumentImpl(packageDocid, false);
304
                if (xmldoc == null) {
305
                  util.debugMessage("Document was null for: "+packageDocid, 50);
306
                }
307
              }
308
              catch(Exception e)
309
              {
310
                System.out.println("Error getting document in " + 
311
                                   "DBQuery.findDocuments: " + e.getMessage());
312
              }
313
              
314
              String docid_org = xmldoc.getDocID();
315
              if (docid_org == null) {
316
                util.debugMessage("Docid_org was null.", 40);
317
              }
318
              docid   = docid_org.trim();
319
              docname = xmldoc.getDocname();
320
              doctype = xmldoc.getDoctype();
321
              createDate = xmldoc.getCreateDate();
322
              updateDate = xmldoc.getUpdateDate();
323
              rev = xmldoc.getRev();
324

    
325
              document = new StringBuffer();
326

    
327
              String completeDocid = docid + util.getOption("accNumSeparator");
328
              completeDocid += rev;
329
              document.append("<docid>").append(completeDocid);
330
              document.append("</docid>");
331
              if (docname != null) {
332
                document.append("<docname>" + docname + "</docname>");
333
              }
334
              if (doctype != null) {
335
                document.append("<doctype>" + doctype + "</doctype>");
336
              }
337
              if (createDate != null) {
338
                document.append("<createdate>" + createDate + "</createdate>");
339
              }
340
              if (updateDate != null) {
341
                document.append("<updatedate>" + updateDate + "</updatedate>");
342
              }
343
              // Store the document id and the root node id
344
              docListResult.put(docid,(String)document.toString());
345
         
346
              // Get the next package document linked to our hit
347
              hasBtRows = btrs.next();
348
            }
349
            npstmt.close();
350
            btrs.close();
351
          } else {
352
          
353
            document = new StringBuffer();
354

    
355
            String completeDocid = docid + util.getOption("accNumSeparator");
356
            completeDocid += rev;
357
            document.append("<docid>").append(completeDocid).append("</docid>");
358
            if (docname != null) {
359
              document.append("<docname>" + docname + "</docname>");
360
            }
361
            if (doctype != null) {
362
              document.append("<doctype>" + doctype + "</doctype>");
363
            }
364
            if (createDate != null) {
365
              document.append("<createdate>" + createDate + "</createdate>");
366
            }
367
            if (updateDate != null) {
368
              document.append("<updatedate>" + updateDate + "</updatedate>");
369
            }
370
            // Store the document id and the root node id
371
            docListResult.put(docid,(String)document.toString());
372
  
373
          }
374

    
375
          // Advance to the next record in the cursor
376
          tableHasRows = rs.next();
377
        }
378
        rs.close();
379
        pstmt.close();
380
        
381
        if (qspec.containsExtendedSQL())
382
        {
383
          Vector extendedFields = new Vector(qspec.getReturnFieldList());
384
          Vector results = new Vector();
385
          Enumeration keylist = docListResult.keys();
386
          StringBuffer doclist = new StringBuffer();
387
          while(keylist.hasMoreElements())
388
          {
389
            doclist.append("'");
390
            doclist.append((String)keylist.nextElement());
391
            doclist.append("',");
392
          }
393
          if (doclist.length() > 0) {
394
            doclist.deleteCharAt(doclist.length()-1); //remove the last comma
395
            //pstmt.close();
396
            pstmt = dbconn.prepareStatement(qspec.printExtendedSQL(
397
                                        doclist.toString()));
398
            //increase dbconnection usage count
399
            dbconn.increaseUsageCount(1);
400
            pstmt.execute();
401
            rs = pstmt.getResultSet();
402
            tableHasRows = rs.next();
403
            while(tableHasRows) 
404
            {
405
              docid = rs.getString(1).trim();
406
              if ( !hasPermission(user, groups, docid) ) {
407
                // Advance to the next record in the cursor
408
                tableHasRows = rs.next();
409
                continue;
410
              }
411
              fieldname = rs.getString(2);
412
              fielddata = rs.getString(3);
413
              
414
              document = new StringBuffer();
415
  
416
              document.append("<param name=\"");
417
              document.append(fieldname);
418
              document.append("\">");
419
              document.append(fielddata);
420
              document.append("</param>");
421
  
422
              tableHasRows = rs.next();
423
              if (docListResult.containsKey(docid))
424
              {
425
                String removedelement = (String)docListResult.remove(docid);
426
                docListResult.put(docid, removedelement + document.toString());
427
              }
428
              else
429
              {
430
                docListResult.put(docid, document.toString()); 
431
              }
432
            }
433
          }
434
          rs.close();
435
        }
436
        pstmt.close();
437
        
438
        //this loop adds the relation data to the resultdoc
439
        //this code might be able to be added to the backtracking code above
440
        Enumeration docidkeys = docListResult.keys();
441
        while(docidkeys.hasMoreElements())
442
        {
443
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
444
          String connstring = "%docid=";
445
          String docidkey = (String)docidkeys.nextElement();
446
          pstmt = dbconn.prepareStatement(qspec.printRelationSQL(docidkey));
447
          pstmt.execute();
448
          rs = pstmt.getResultSet();
449
          tableHasRows = rs.next();
450
          while(tableHasRows)
451
          {
452
            String sub = rs.getString(1);
453
            String rel = rs.getString(2);
454
            String obj = rs.getString(3);
455
            String subDT = rs.getString(4);
456
            String objDT = rs.getString(5);
457
            
458
            document = new StringBuffer();
459
            document.append("<triple>");
460
            document.append("<subject>").append(MetaCatUtil.normalize(sub));
461
            document.append("</subject>");
462
            if ( subDT != null ) {
463
              document.append("<subjectdoctype>").append(subDT);
464
              document.append("</subjectdoctype>");
465
            }
466
            document.append("<relationship>").
467
                                          append(MetaCatUtil.normalize(rel));
468
            document.append("</relationship>");
469
            document.append("<object>").append(MetaCatUtil.normalize(obj));
470
            document.append("</object>");
471
            if ( objDT != null ) {
472
              document.append("<objectdoctype>").append(objDT);
473
              document.append("</objectdoctype>");
474
            }
475
            document.append("</triple>");
476
            
477
            String removedelement = (String)docListResult.remove(docidkey);
478
            docListResult.put(docidkey, removedelement + 
479
                              document.toString());
480
            tableHasRows = rs.next();
481
          }
482
          rs.close();
483
          pstmt.close();
484
        }
485
        
486
      } catch (SQLException e) {
487
        System.err.println("SQL Error in DBQuery.findDocuments: " + 
488
                           e.getMessage());
489
      } catch (IOException ioe) {
490
        System.err.println("IO error in DBQuery.findDocuments:");
491
        System.err.println(ioe.getMessage());
492
      } catch (Exception ee) {
493
        System.err.println("Exception in DBQuery.findDocuments: " + 
494
                           ee.getMessage());
495
        ee.printStackTrace(System.err);
496
      }
497
      finally 
498
      {
499
        try
500
        {
501
          pstmt.close();
502
        }//try
503
        catch (SQLException sqlE)
504
        {
505
          MetaCatUtil.debugMessage("Error in DBQuery.findDocuments: "
506
                                      +sqlE.getMessage(), 30);
507
        }//catch
508
        finally
509
        {
510
          DBConnectionPool.returnDBConnection(dbconn, serialNumber);
511
        }//finally
512
      }//finally
513
    //System.out.println("docListResult: ");
514
    //System.out.println(docListResult.toString());
515
    return docListResult;
516
  }
517
  
518
  /**
519
   * returns a string array of the contents of a particular node. 
520
   * If the node appears more than once, the contents are returned 
521
   * in the order in which they appearred in the document.
522
   * @param nodename the name or path of the particular node.
523
   * @param docid the docid of the document you want the node from.
524
   */
525
  public static Object[] getNodeContent(String nodename, String docid)
526
  {
527
    DBConnection dbconn = null;
528
    int serialNumber = -1;
529
    StringBuffer query = new StringBuffer();
530
    Vector result = new Vector();
531
    PreparedStatement pstmt = null;
532
    query.append("select nodedata from xml_nodes where parentnodeid in ");
533
    query.append("(select nodeid from xml_index where path like '");
534
    query.append(nodename);
535
    query.append("' and docid like '").append(docid).append("')");
536
    try
537
    {
538
      dbconn=DBConnectionPool.getDBConnection("DBQuery.getNodeContent");
539
        serialNumber=dbconn.getCheckOutSerialNumber();
540
      pstmt = dbconn.prepareStatement(query.toString());
541

    
542
      // Execute the SQL query using the JDBC connection
543
      pstmt.execute();
544
      ResultSet rs = pstmt.getResultSet();
545
      boolean tableHasRows = rs.next();
546
      while (tableHasRows) 
547
      {
548
        result.add(rs.getString(1));
549
        System.out.println(rs.getString(1));
550
        tableHasRows = rs.next();
551
      }
552
    } 
553
    catch (SQLException e) 
554
    {
555
      System.err.println("Error in DBQuery.getNodeContent: " + e.getMessage());
556
    } finally {
557
      try
558
      {
559
        pstmt.close();
560
      }
561
      catch(SQLException sqle) 
562
      {}
563
      finally
564
      {
565
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
566
      }
567
      
568
    }
569
    return result.toArray();
570
  }
571
  
572
  /**
573
   * format a structured query as an XML document that conforms
574
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
575
   * structured query engine
576
   *
577
   * @param params The list of parameters that should be included in the query
578
   */
579
  public static String createSQuery(Hashtable params)
580
  { 
581
    StringBuffer query = new StringBuffer();
582
    Enumeration elements;
583
    Enumeration keys;
584
    String filterDoctype = null;
585
    String casesensitive = null;
586
    String searchmode = null;
587
    Object nextkey;
588
    Object nextelement;
589
    //add the xml headers
590
    query.append("<?xml version=\"1.0\"?>\n");
591
    query.append("<pathquery version=\"1.0\">\n");
592

    
593
    if (params.containsKey("meta_file_id"))
594
    {
595
      query.append("<meta_file_id>");
596
      query.append( ((String[])params.get("meta_file_id"))[0]);
597
      query.append("</meta_file_id>");
598
    }
599
    
600
    if (params.containsKey("returndoctype"))
601
    {
602
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
603
      for(int i=0; i<returnDoctypes.length; i++)
604
      {
605
        String doctype = (String)returnDoctypes[i];
606

    
607
        if (!doctype.equals("any") && 
608
            !doctype.equals("ANY") &&
609
            !doctype.equals("") ) 
610
        {
611
          query.append("<returndoctype>").append(doctype);
612
          query.append("</returndoctype>");
613
        }
614
      }
615
    }
616
    
617
    if (params.containsKey("filterdoctype"))
618
    {
619
      String[] filterDoctypes = ((String[])params.get("filterdoctype"));
620
      for(int i=0; i<filterDoctypes.length; i++)
621
      {
622
        query.append("<filterdoctype>").append(filterDoctypes[i]);
623
        query.append("</filterdoctype>");
624
      }
625
    }
626
    
627
    if (params.containsKey("returnfield"))
628
    {
629
      String[] returnfield = ((String[])params.get("returnfield"));
630
      for(int i=0; i<returnfield.length; i++)
631
      {
632
        query.append("<returnfield>").append(returnfield[i]);
633
        query.append("</returnfield>");
634
      }
635
    }
636
    
637
    if (params.containsKey("owner"))
638
    {
639
      String[] owner = ((String[])params.get("owner"));
640
      for(int i=0; i<owner.length; i++)
641
      {
642
        query.append("<owner>").append(owner[i]);
643
        query.append("</owner>");
644
      }
645
    }
646
    
647
    if (params.containsKey("site"))
648
    {
649
      String[] site = ((String[])params.get("site"));
650
      for(int i=0; i<site.length; i++)
651
      {
652
        query.append("<site>").append(site[i]);
653
        query.append("</site>");
654
      }
655
    }
656
    
657
    //allows the dynamic switching of boolean operators
658
    if (params.containsKey("operator"))
659
    {
660
      query.append("<querygroup operator=\"" + 
661
                ((String[])params.get("operator"))[0] + "\">");
662
    }
663
    else
664
    { //the default operator is UNION
665
      query.append("<querygroup operator=\"UNION\">"); 
666
    }
667
        
668
    if (params.containsKey("casesensitive"))
669
    {
670
      casesensitive = ((String[])params.get("casesensitive"))[0]; 
671
    }
672
    else
673
    {
674
      casesensitive = "false"; 
675
    }
676
    
677
    if (params.containsKey("searchmode"))
678
    {
679
      searchmode = ((String[])params.get("searchmode"))[0]; 
680
    }
681
    else
682
    {
683
      searchmode = "contains"; 
684
    }
685
        
686
    //anyfield is a special case because it does a 
687
    //free text search.  It does not have a <pathexpr>
688
    //tag.  This allows for a free text search within the structured
689
    //query.  This is useful if the INTERSECT operator is used.
690
    if (params.containsKey("anyfield"))
691
    {
692
       String[] anyfield = ((String[])params.get("anyfield"));
693
       //allow for more than one value for anyfield
694
       for(int i=0; i<anyfield.length; i++)
695
       {
696
         if (!anyfield[i].equals(""))
697
         {
698
           query.append("<queryterm casesensitive=\"" + casesensitive + 
699
                        "\" " + "searchmode=\"" + searchmode + "\"><value>" +
700
                        anyfield[i] +
701
                        "</value></queryterm>"); 
702
         }
703
       }
704
    }
705
        
706
    //this while loop finds the rest of the parameters
707
    //and attempts to query for the field specified
708
    //by the parameter.
709
    elements = params.elements();
710
    keys = params.keys();
711
    while(keys.hasMoreElements() && elements.hasMoreElements())
712
    {
713
      nextkey = keys.nextElement();
714
      nextelement = elements.nextElement();
715

    
716
      //make sure we aren't querying for any of these
717
      //parameters since the are already in the query
718
      //in one form or another.
719
      if (!nextkey.toString().equals("returndoctype") && 
720
         !nextkey.toString().equals("filterdoctype")  &&
721
         !nextkey.toString().equals("action")  &&
722
         !nextkey.toString().equals("qformat") && 
723
         !nextkey.toString().equals("anyfield") &&
724
         !nextkey.toString().equals("returnfield") &&
725
         !nextkey.toString().equals("owner") &&
726
         !nextkey.toString().equals("site") &&
727
         !nextkey.toString().equals("operator") )
728
      {
729
        //allow for more than value per field name
730
        for(int i=0; i<((String[])nextelement).length; i++)
731
        {
732
          if (!((String[])nextelement)[i].equals(""))
733
          {
734
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " + 
735
                         "searchmode=\"" + searchmode + "\">" +
736
                         "<value>" +
737
                         //add the query value
738
                         ((String[])nextelement)[i] +
739
                         "</value><pathexpr>" +
740
                         //add the path to query by 
741
                         nextkey.toString() + 
742
                         "</pathexpr></queryterm>");
743
          }
744
        }
745
      }
746
    }
747
    query.append("</querygroup></pathquery>");
748
    //append on the end of the xml and return the result as a string
749
    return query.toString();
750
  }
751
  
752
  /**
753
   * format a simple free-text value query as an XML document that conforms
754
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
755
   * structured query engine
756
   *
757
   * @param value the text string to search for in the xml catalog
758
   * @param doctype the type of documents to include in the result set -- use
759
   *        "any" or "ANY" for unfiltered result sets
760
   */
761
   public static String createQuery(String value, String doctype) {
762
     StringBuffer xmlquery = new StringBuffer();
763
     xmlquery.append("<?xml version=\"1.0\"?>\n");
764
     xmlquery.append("<pathquery version=\"1.0\">");
765

    
766
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
767
       xmlquery.append("<returndoctype>");
768
       xmlquery.append(doctype).append("</returndoctype>");
769
     }
770

    
771
     xmlquery.append("<querygroup operator=\"UNION\">");
772
     //chad added - 8/14
773
     //the if statement allows a query to gracefully handle a null 
774
     //query.  Without this if a nullpointerException is thrown.
775
     if (!value.equals(""))
776
     {
777
       xmlquery.append("<queryterm casesensitive=\"false\" ");
778
       xmlquery.append("searchmode=\"contains\">");
779
       xmlquery.append("<value>").append(value).append("</value>");
780
       xmlquery.append("</queryterm>");
781
     }
782
     xmlquery.append("</querygroup>");
783
     xmlquery.append("</pathquery>");
784

    
785
     
786
     return (xmlquery.toString());
787
   }
788

    
789
  /**
790
   * format a simple free-text value query as an XML document that conforms
791
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
792
   * structured query engine
793
   *
794
   * @param value the text string to search for in the xml catalog
795
   */
796
   public static String createQuery(String value) {
797
     return createQuery(value, "any");
798
   }
799
   
800
  /** 
801
    * Check for "READ" permission on @docid for @user and/or @group 
802
    * from DB connection 
803
    */
804
  private boolean hasPermission (String user,
805
                                  String[] groups, String docid ) 
806
                  throws SQLException, Exception
807
  {
808
    // Check for READ permission on @docid for @user and/or @groups
809
    //AccessControlList aclobj = new AccessControlList();
810
    //return aclobj.hasPermission("READ", user, groups, docid);
811
    return AccessControlList.hasPermission("READ", user, groups, docid);
812
  }
813

    
814
  /**
815
    * Get all docIds list for a data packadge
816
    * @param dataPackageDocid, the string in docId field of xml_relation table
817
    */
818
  private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
819
  {
820
    DBConnection dbConn = null;
821
    int serialNumber = -1;
822
    Vector docIdList=new Vector();//return value
823
    PreparedStatement pStmt = null;
824
    ResultSet rs=null;
825
    String docIdInSubjectField=null;
826
    String docIdInObjectField=null;
827
    //the query stirng
828
    String query="SELECT subject, object from xml_relation where docId = ?";
829
    try
830
    {
831
      dbConn=DBConnectionPool.
832
                  getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
833
      serialNumber=dbConn.getCheckOutSerialNumber();
834
      pStmt=dbConn.prepareStatement(query);
835
      //bind the value to query
836
      pStmt.setString(1, dataPackageDocid);
837

    
838
      //excute the query
839
      pStmt.execute();
840
      //get the result set
841
      rs=pStmt.getResultSet();
842
      //process the result
843
      while (rs.next())
844
      {
845
        //In order to get the whole docIds in a data packadge,
846
        //we need to put the docIds of subject and object field in xml_relation
847
        //into the return vector
848
        docIdInSubjectField=rs.getString(1);//the result docId in subject field
849
        docIdInObjectField=rs.getString(2);//the result docId in object field
850

    
851
        //don't put the duplicate docId into the vector
852
        if (!docIdList.contains(docIdInSubjectField))
853
        {
854
          docIdList.add(docIdInSubjectField);
855
        }
856

    
857
        //don't put the duplicate docId into the vector
858
        if (!docIdList.contains(docIdInObjectField))
859
        {
860
          docIdList.add(docIdInObjectField);
861
        }
862
      }//while
863
      //close the pStmt
864
      pStmt.close();
865
    }//try
866
    catch (SQLException e)
867
    {
868
      util.debugMessage("Error in getDocidListForDataPackage: "
869
                            +e.getMessage(), 30);
870
    }//catch
871
    finally
872
    {
873
      try
874
      {
875
        pStmt.close();
876
      }//try
877
      catch (SQLException ee)
878
      {
879
        util.debugMessage("Error in getDocidListForDataPackage: "
880
                            +ee.getMessage(), 30);
881
      }//catch     
882
      finally
883
      {
884
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
885
      }//fianlly
886
    }//finally
887
    return docIdList;
888
  }//getCurrentDocidListForDataPackadge()
889
  
890
  /**
891
   * Get all docIds list for a data packadge
892
   * @param dataPackageDocid, the string in docId field of xml_relation table
893
   */
894
  private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
895
                                 throws SQLException, McdbException,Exception
896
  {
897
   
898
    Vector docIdList=new Vector();//return value
899
    Vector tripleList=null;
900
    String xml=null;
901
   
902
      //initial a documentImpl object 
903
      DocumentImpl packageDocument = 
904
                  new DocumentImpl(dataPackageDocid);
905
      //transfer to documentImpl object to string
906
      xml=packageDocument.toString();
907
    
908
      //create a tripcollection object
909
      TripleCollection tripleForPackage = new 
910
                                     TripleCollection(new StringReader(xml));
911
      //get the vetor of triples 
912
      tripleList=tripleForPackage.getCollection();
913
    
914
      for (int i= 0; i<tripleList.size(); i++)
915
      {
916
        //put subject docid  into docIdlist without duplicate
917
        if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getSubject()))
918
        {
919
          //put subject docid  into docIdlist
920
          docIdList.add(((Triple)tripleList.get(i)).getSubject());
921
        }
922
        //put object docid into docIdlist without duplicate
923
        if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getObject()))
924
        {
925
          docIdList.add(((Triple)(tripleList.get(i))).getObject());
926
        }
927
      }//for
928
  
929
    
930
    
931
    return docIdList;
932
  }//getDocidListForPackageInXMLRevisions()  
933
  
934
  /**
935
   * Check if the docId is a data packadge id. If the id is a data packadage 
936
   *id, it should be store in the docId fields in xml_relation table.
937
   *So we can use a query to get the entries which the docId equals the given 
938
   *value. If the result is null. The docId is not a packadge id. Otherwise,
939
   * it is.
940
   * @param docId, the id need to be checked
941
   */
942
  private boolean isDataPackageId(String docId)
943
  {
944
    boolean result=false;
945
    PreparedStatement pStmt = null;
946
    ResultSet rs=null;
947
    String query="SELECT docId from xml_relation where docId = ?";
948
    DBConnection dbConn = null;
949
    int serialNumber = -1;
950
    try
951
    {
952
      dbConn=DBConnectionPool.
953
                  getDBConnection("DBQuery.isDataPackageId");
954
      serialNumber=dbConn.getCheckOutSerialNumber();
955
      pStmt=dbConn.prepareStatement(query);
956
      //bind the value to query
957
      pStmt.setString(1, docId);
958
      //execute the query
959
      pStmt.execute();
960
      rs=pStmt.getResultSet();
961
      //process the result
962
      if (rs.next()) //There are some records for the id in docId fields
963
      {
964
        result=true;//It is a data packadge id
965
      }
966
      pStmt.close();
967
    }//try
968
    catch (SQLException e)
969
    {
970
      util.debugMessage("Error in isDataPackageId: "
971
                            +e.getMessage(), 30);
972
    }
973
    finally
974
    {
975
      try
976
      {
977
        pStmt.close();
978
      }//try
979
      catch (SQLException ee)
980
      {
981
        MetaCatUtil.debugMessage("Error in isDataPackageId: "
982
                                                        + ee.getMessage(), 30);
983
      }//catch
984
      finally
985
      {
986
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
987
      }//finally
988
    }//finally
989
    return result;
990
  }//isDataPackageId()
991
  
992
  /**
993
   * Check if the user has the permission to export data package
994
   * @param conn, the connection
995
   * @param docId, the id need to be checked
996
   * @param user, the name of user
997
   * @param groups, the user's group
998
   */ 
999
   private boolean hasPermissionToExportPackage(String docId, 
1000
                                        String user, String[] groups)
1001
                   throws Exception
1002
   {
1003
     //DocumentImpl doc=new DocumentImpl(conn,docId);
1004
     return DocumentImpl.hasReadPermission(user, groups,docId);
1005
   }
1006
   
1007
  /**
1008
   *Get the current Rev for a docid in xml_documents table
1009
   * @param docId, the id need to get version numb
1010
   * If the return value is -5, means no value in rev field for this docid
1011
   */
1012
  private int getCurrentRevFromXMLDoumentsTable(String docId)
1013
  {
1014
    int rev=-5;
1015
    PreparedStatement pStmt = null;
1016
    ResultSet rs=null;
1017
    String query="SELECT rev from xml_documents where docId = ?";
1018
    DBConnection dbConn=null;
1019
    int serialNumber = -1;
1020
    try
1021
    {
1022
      dbConn=DBConnectionPool.
1023
                  getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1024
      serialNumber=dbConn.getCheckOutSerialNumber();
1025
      pStmt=dbConn.prepareStatement(query);
1026
      //bind the value to query
1027
      pStmt.setString(1, docId);
1028
      //execute the query
1029
      pStmt.execute();
1030
      rs=pStmt.getResultSet();
1031
      //process the result
1032
      if (rs.next()) //There are some records for rev
1033
      {
1034
        rev=rs.getInt(1);;//It is the version for given docid
1035
      }
1036
      else
1037
      {
1038
        rev=-5;
1039
      }
1040
      pStmt.close();
1041
    }//try
1042
    catch (SQLException e)
1043
    {
1044
      util.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
1045
                            +e.getMessage(), 30);
1046
    }//catch
1047
    finally
1048
    {
1049
      try
1050
      {
1051
        pStmt.close();
1052
      }//try
1053
      catch (SQLException ee)
1054
      {
1055
        MetaCatUtil.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
1056
                                  +ee.getMessage(), 30);
1057
      }//catch
1058
      finally
1059
      {
1060
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1061
      }//finally
1062
    }//finally
1063
    return rev;
1064
  }//getCurrentRevFromXMLDoumentsTable
1065
 
1066
 /**
1067
   *put a doc into a zip output stream
1068
   *@param docImpl, docmentImpl object which will be sent to zip output stream
1069
   *@param zipOut, zip output stream which the docImpl will be put
1070
   *@param packageZipEntry, the zip entry name for whole package
1071
   */
1072
  private void addDocToZipOutputStream(DocumentImpl docImpl, 
1073
                                ZipOutputStream zipOut, String packageZipEntry)
1074
               throws ClassNotFoundException, IOException, SQLException, 
1075
                      McdbException, Exception
1076
  {
1077
    byte[] byteString = null;
1078
    ZipEntry zEntry = null;
1079

    
1080
    byteString = docImpl.toString().getBytes();
1081
    //use docId as the zip entry's name
1082
    zEntry = new ZipEntry(packageZipEntry+"/metadata/"+docImpl.getDocID());
1083
    zEntry.setSize(byteString.length);
1084
    zipOut.putNextEntry(zEntry);
1085
    zipOut.write(byteString, 0, byteString.length);
1086
    zipOut.closeEntry();
1087
  
1088
  }//addDocToZipOutputStream()
1089

    
1090
  
1091
  /**
1092
   *transfer a docid vetor to a documentImpl vector. The documentImpl vetor 
1093
   *only inlcudes current version
1094
   *@param docIdList, a vetor hold a docid list for a data package. In docid,
1095
   *there is not version number in it.
1096
   */  
1097
  
1098
  private Vector getCurrentAllDocumentImpl( Vector docIdList)
1099
                              throws McdbException,Exception
1100
  {
1101
    //Connection dbConn=null;
1102
    Vector documentImplList=new Vector();
1103
    int rev=0; 
1104
    
1105
    /*if (conn == null || conn.isClosed())
1106
    {
1107
      dbConn = util.openDBConnection();
1108
    }
1109
    else
1110
    {
1111
      dbConn=conn;
1112
    }*/
1113
    //for every docid in vector
1114
    for (int i=0;i<docIdList.size();i++)
1115
    {
1116
      //get newest version for this docId
1117
      rev=getCurrentRevFromXMLDoumentsTable((String)docIdList.elementAt(i));
1118
     
1119
      String docidPlusVersion=((String)docIdList.elementAt(i))
1120
                        +util.getOption("accNumSeparator")+rev;
1121
      //create new documentImpl object
1122
      DocumentImpl documentImplObject = 
1123
                                    new DocumentImpl(docidPlusVersion);
1124
      //add them to vector                            
1125
      documentImplList.add(documentImplObject);
1126
      
1127
    }//for
1128
    return documentImplList;
1129
  }
1130
  
1131
  /**
1132
   *transfer a docid vetor to a documentImpl vector. The documentImpl vetor 
1133
   *does not inlcude old version
1134
   *@param docIdList, a vetor hold a docid list for a data package. In docid,
1135
   *there is version number in it.
1136
   */    
1137
  private Vector getOldVersionAllDocumentImpl( Vector docIdList)
1138
                              throws McdbException,Exception
1139
  {
1140
    //Connection dbConn=null;
1141
    Vector documentImplList=new Vector();
1142
    String siteCode=null;
1143
    String uniqueId=null;
1144
    int rev=0; 
1145
    
1146
    /*if (conn == null || conn.isClosed())
1147
    {
1148
      dbConn = util.openDBConnection();
1149
    }
1150
    else
1151
    {
1152
      dbConn=conn;
1153
    }*/
1154
    //for every docid in vector
1155
    for (int i=0;i<docIdList.size();i++)
1156
    {
1157
      
1158
        String docidPlusVersion=(String)(docIdList.elementAt(i));
1159
        //create new documentImpl object
1160
        DocumentImpl documentImplObject = 
1161
                                    new DocumentImpl(docidPlusVersion);
1162
        //add them to vector                            
1163
        documentImplList.add(documentImplObject);
1164
      
1165
    }//for
1166
    return documentImplList;
1167
  }
1168
  /**
1169
   *put a data file into a zip output stream
1170
   *@param docImpl, docmentImpl object which will be sent to zip output stream
1171
   *@param zipOut, the zip output stream which the docImpl will be put
1172
   *@param packageZipEntry, the zip entry name for whole package
1173
   */
1174
  private void addDataFileToZipOutputStream(DocumentImpl docImpl,
1175
                                ZipOutputStream zipOut, String packageZipEntry)
1176
               throws ClassNotFoundException, IOException, SQLException,
1177
                      McdbException, Exception
1178
  {
1179
    byte[] byteString = null;
1180
    ZipEntry zEntry = null;
1181
    // this is data file; add file to zip
1182
    String filePath = util.getOption("datafilepath");
1183
    if (!filePath.endsWith("/")) 
1184
    {
1185
      filePath += "/";
1186
    }
1187
    String fileName = filePath + docImpl.getDocID();
1188
    zEntry = new ZipEntry(packageZipEntry+"/data/"+docImpl.getDocID());
1189
    zipOut.putNextEntry(zEntry);
1190
    FileInputStream fin = null;
1191
    try
1192
    {
1193
      fin = new FileInputStream(fileName);
1194
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1195
      int b = fin.read(buf);
1196
      while (b != -1)
1197
      {
1198
        zipOut.write(buf, 0, b);
1199
        b = fin.read(buf);
1200
      }//while
1201
      zipOut.closeEntry();
1202
    }//try
1203
    catch (IOException ioe)
1204
    {
1205
      util.debugMessage("There is an exception: "+ioe.getMessage(), 30);
1206
    }//catch
1207
  }//addDataFileToZipOutputStream()
1208

    
1209
  /**
1210
   *create a html summary for data package and put it into zip output stream
1211
   *@param docImplList, the documentImpl ojbects in data package
1212
   *@param zipOut, the zip output stream which the html should be put
1213
   *@param packageZipEntry, the zip entry name for whole package
1214
   */
1215
   private void addHtmlSummaryToZipOutputStream(Vector docImplList,
1216
                                ZipOutputStream zipOut, String packageZipEntry)
1217
                                           throws Exception
1218
  {
1219
    StringBuffer htmlDoc = new StringBuffer();
1220
    ZipEntry zEntry = null;
1221
    byte[] byteString=null;
1222
    InputStream source;
1223
    DBTransform xmlToHtml;
1224
    //Connection dbConn;
1225

    
1226
    //get the connection to the database
1227
    /*if (conn == null || conn.isClosed())
1228
    {
1229
      dbConn = util.openDBConnection();
1230
    }
1231
    else
1232
    {
1233
      dbConn=conn;
1234
    }*/
1235

    
1236
    //create a DBTransform ojbect
1237
    xmlToHtml = new DBTransform();
1238
    //head of html
1239
    htmlDoc.append("<html><head></head><body>");
1240
    for (int i=0; i<docImplList.size(); i++)
1241
    {
1242
      if ((((DocumentImpl)docImplList.elementAt(i)).getDoctype()).
1243
                                                         compareTo("BIN")!=0)
1244
      { //this is an xml file so we can transform it.
1245
        //transform each file individually then concatenate all of the
1246
        //transformations together.
1247

    
1248
        //for metadata xml title
1249
        htmlDoc.append("<h2>");
1250
        htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getDocID());
1251
        //htmlDoc.append(".");
1252
        //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
1253
        htmlDoc.append("</h2>");
1254
        //do the actual transform
1255
        StringWriter docString = new StringWriter();
1256
        xmlToHtml.transformXMLDocument(
1257
                        ((DocumentImpl)docImplList.elementAt(i)).toString(),
1258
           "-//NCEAS//eml-generic//EN", "-//W3C//HTML//EN", "html", docString);
1259
        htmlDoc.append(docString.toString());
1260
        htmlDoc.append("<br><br><hr><br><br>");
1261
      }//if
1262
      else
1263
      { //this is a data file so we should link to it in the html
1264
        htmlDoc.append("<a href=\"");
1265
        String dataFileName = null;
1266
        String dataFileid =((DocumentImpl)docImplList.elementAt(i)).getDocID();
1267
        htmlDoc.append("./data/").append(dataFileid).append("\">");
1268
        htmlDoc.append("Data File: ");
1269
        htmlDoc.append(dataFileid).append("</a><br>");
1270
        htmlDoc.append("<br><hr><br>");
1271
      }//else
1272
    }//for
1273
    htmlDoc.append("</body></html>");
1274
    byteString = htmlDoc.toString().getBytes();
1275
    zEntry = new ZipEntry(packageZipEntry+"/metadata.html");
1276
    zEntry.setSize(byteString.length);
1277
    zipOut.putNextEntry(zEntry);
1278
    zipOut.write(byteString, 0, byteString.length);
1279
    zipOut.closeEntry();
1280
    //dbConn.close();
1281
        
1282
  }//addHtmlSummaryToZipOutputStream
1283
  
1284
  
1285
  
1286
  /**
1287
   * put a data packadge into a zip output stream
1288
   * @param docId, which the user want to put into zip output stream
1289
   * @param out, a servletoutput stream which the zip output stream will be put 
1290
   * @param user, the username of the user
1291
   * @param groups, the group of the user
1292
   */
1293
  public ZipOutputStream getZippedPackage(String docIdString, 
1294
                    ServletOutputStream out, String user, String[] groups)
1295
                    throws ClassNotFoundException, IOException, SQLException, 
1296
                      McdbException, NumberFormatException, Exception
1297
  { 
1298
    ZipOutputStream zOut = null;
1299
    String elementDocid=null;
1300
    DocumentImpl docImpls=null;
1301
    //Connection dbConn = null;
1302
    Vector docIdList=new Vector();
1303
    Vector documentImplList=new Vector();
1304
    Vector htmlDocumentImplList=new Vector();
1305
    String packageId=null;
1306
    String rootName="package";//the package zip entry name
1307
    
1308
    String docId=null;
1309
    int version=-5;
1310
    docId=MetaCatUtil.getDocIdFromString(docIdString);
1311
    version=MetaCatUtil.getVersionFromString(docIdString);
1312
 
1313
    //get the connection to the database
1314
    /*if (conn == null || conn.isClosed())
1315
    {
1316
      dbConn = util.openDBConnection();
1317
    }
1318
    else
1319
    {
1320
      dbConn=conn;
1321
    }*/
1322

    
1323
    //check if the reqused docId is a data package id
1324
    if (!isDataPackageId(docId))//if it is not, throw a exception
1325
    {
1326
      Exception e = new Exception("The request the doc id " +docIdString+
1327
                                    " is not a data package id");
1328
      //dbConn.close();
1329
      throw e;
1330
    }
1331
    else if(!hasPermissionToExportPackage(docId, user, groups))
1332
    {
1333
      Exception e = new Exception("User " + user + " does not have permission"
1334
                       +" to export the data package " + docIdString);
1335
      //dbConn.close();
1336
      throw e;
1337
    }
1338
    else //it is a packadge id
1339
    { 
1340
      //store the package id
1341
      packageId=docId;
1342
      //If it is for current version
1343
      if ((version ==-1)||version==getCurrentRevFromXMLDoumentsTable(packageId))
1344
      { 
1345
        //get current version number
1346
        version=getCurrentRevFromXMLDoumentsTable(packageId);
1347
        //get package zip entry name
1348
        //it should be docId.revsion.package
1349
        rootName=packageId+util.getOption("accNumSeparator")+version+
1350
                                  util.getOption("accNumSeparator")+"package";
1351
        //get the whole id list for data packadge
1352
        docIdList=getCurrentDocidListForDataPackage(packageId);
1353
        //get the whole documentImple object
1354
        documentImplList=getCurrentAllDocumentImpl(docIdList);
1355
       
1356
      }//if
1357
      else  //for an old version
1358
      {
1359
       
1360
        rootName=docIdString+util.getOption("accNumSeparator")+"package";
1361
        //get the whole id list for data packadge
1362
        docIdList=getOldVersionDocidListForDataPackage(docIdString);
1363

    
1364
        //get the whole documentImple object
1365
        documentImplList=getOldVersionAllDocumentImpl(docIdList);
1366
      }//else  
1367
      
1368
      
1369
      zOut = new ZipOutputStream(out);
1370

    
1371
      //put every element into zip output stream
1372
      for (int i=0; i < documentImplList.size(); i++ )
1373
      {
1374
        //create a docmentImpls object (represent xml doc) base on the docId
1375
        docImpls=(DocumentImpl)documentImplList.elementAt(i);
1376
        
1377
        //checking if the user has the permission to read the documents
1378
        if (docImpls.hasReadPermission(user,groups,docImpls.getDocID()))
1379
        { 
1380
            //if the docImpls is metadata 
1381
          if ((docImpls.getDoctype()).compareTo("BIN")!=0)  
1382
          {
1383
              //add metadata into zip output stream
1384
              addDocToZipOutputStream(docImpls, zOut, rootName);
1385
              //add the documentImpl into the vetor which will be used in html
1386
              htmlDocumentImplList.add(docImpls);
1387
           
1388
          }//if
1389
          
1390
          else 
1391
          {
1392
           
1393
           //it is data file 
1394
           addDataFileToZipOutputStream(docImpls, zOut, rootName);
1395
           htmlDocumentImplList.add(docImpls);
1396
          }//else
1397
        }//if
1398

    
1399
      }//for
1400

    
1401
      //add html summary file
1402
      addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut, rootName);
1403
      zOut.finish(); //terminate the zip file
1404
      //dbConn.close();
1405
      return zOut;
1406
    }//else
1407
  }//getZippedPackage()
1408
   
1409
}
(17-17/43)