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: 2003-03-04 12:05:18 -0800 (Tue, 04 Mar 2003) $'
15
 * '$Revision: 1450 $'
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
       
223
        
224
        dbconn=DBConnectionPool.getDBConnection("DBQuery.findDocuments");
225
        serialNumber=dbconn.getCheckOutSerialNumber();
226
      
227
        // Get the XML query and covert it into a SQL statment
228
        QuerySpecification qspec = new QuerySpecification(xmlquery, 
229
                                   parserName, 
230
                                   util.getOption("accNumSeparator"));
231
       
232
        String query = qspec.printSQL(useXMLIndex);
233
        String ownerQuery = getOwnerQuery(user);
234
        MetaCatUtil.debugMessage("query: "+query, 30);
235
        //MetaCatUtil.debugMessage("query: "+ownerQuery, 30);
236
        // if query is not the owner query, we need to check the permission
237
        // otherwise we don't need (owner has all permission by default)
238
        if (!query.equals(ownerQuery))
239
        {
240
          // set user name and group
241
          qspec.setUserName(user);
242
          qspec.setGroup(groups);
243
          // Get access query
244
          String accessQuery = qspec.getAccessQuery();
245
          query = query + accessQuery;
246
          MetaCatUtil.debugMessage(" final query: "+query, 30);
247
        }
248
        
249
        double startTime = System.currentTimeMillis()/1000;
250
        pstmt = dbconn.prepareStatement(query);
251
  
252
        // Execute the SQL query using the JDBC connection
253
        pstmt.execute();
254
        ResultSet rs = pstmt.getResultSet();
255
        double queryExecuteTime =System.currentTimeMillis()/1000; 
256
        MetaCatUtil.debugMessage("Time for execute query: "+ 
257
                                            (queryExecuteTime -startTime), 30);
258
        boolean tableHasRows = rs.next();
259
        while (tableHasRows) 
260
        {
261
          docid = rs.getString(1).trim();
262
          //long checkTimeStart = System.currentTimeMillis();
263
          //boolean permit =hasPermission(user, groups, docid);
264
          //long checkTimeEnd = System.currentTimeMillis();
265
          //MetaCatUtil.debugMessage("check permission time: "+
266
                                  //(checkTimeEnd - checkTimeStart), 30);
267
          //if ( !permit ) {
268
            // Advance to the next record in the cursor
269
            //tableHasRows = rs.next();
270
            //continue;
271
          //}
272
          
273
          docname = rs.getString(2);
274
          doctype = rs.getString(3);
275
          createDate = rs.getString(4);
276
          updateDate = rs.getString(5);
277
          rev = rs.getInt(6);
278

    
279
          // if there are returndocs to match, backtracking can be performed
280
          // otherwise, just return the document that was hit
281
          Vector returndocVec = qspec.getReturnDocList();
282
          if (returndocVec.size() != 0 && !returndocVec.contains(doctype) 
283
              && !qspec.isPercentageSearch())
284
          { 
285
            MetaCatUtil.debugMessage("Back tracing now...", 20);
286
            String sep = util.getOption("accNumSeparator");
287
            StringBuffer btBuf = new StringBuffer();
288
            btBuf.append("select docid from xml_relation where ");
289

    
290
            //build the doctype list for the backtracking sql statement
291
            btBuf.append("packagetype in (");
292
            for(int i=0; i<returndocVec.size(); i++)
293
            {
294
              btBuf.append("'").append((String)returndocVec.get(i)).append("'");
295
              if (i != (returndocVec.size() - 1))
296
              {
297
                btBuf.append(", ");
298
              } 
299
            }
300
            btBuf.append(") ");
301

    
302
            btBuf.append("and (subject like '");
303
            btBuf.append(docid).append("'");
304
            btBuf.append("or object like '");
305
            btBuf.append(docid).append("')");
306
            
307
            PreparedStatement npstmt = dbconn.
308
                                       prepareStatement(btBuf.toString());
309
            //should incease usage count
310
            dbconn.increaseUsageCount(1);
311
            npstmt.execute();
312
            ResultSet btrs = npstmt.getResultSet();
313
            boolean hasBtRows = btrs.next();
314
            while (hasBtRows)
315
            { //there was a backtrackable document found
316
              DocumentImpl xmldoc = null;
317
              String packageDocid = btrs.getString(1);
318
              util.debugMessage("Getting document for docid: "+packageDocid,40);
319
              try
320
              {
321
                //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not needed here
322
                // xmldoc = new DocumentImpl(dbconn, packageDocid);
323
                //  thus use the following to get the doc info only
324
                //  xmldoc = new DocumentImpl(dbconn);
325
                xmldoc = new DocumentImpl(packageDocid, false);
326
                if (xmldoc == null) {
327
                  util.debugMessage("Document was null for: "+packageDocid, 50);
328
                }
329
              }
330
              catch(Exception e)
331
              {
332
                System.out.println("Error getting document in " + 
333
                                   "DBQuery.findDocuments: " + e.getMessage());
334
              }
335
              
336
              String docid_org = xmldoc.getDocID();
337
              if (docid_org == null) {
338
                util.debugMessage("Docid_org was null.", 40);
339
              }
340
              docid   = docid_org.trim();
341
              docname = xmldoc.getDocname();
342
              doctype = xmldoc.getDoctype();
343
              createDate = xmldoc.getCreateDate();
344
              updateDate = xmldoc.getUpdateDate();
345
              rev = xmldoc.getRev();
346

    
347
              document = new StringBuffer();
348

    
349
              String completeDocid = docid + util.getOption("accNumSeparator");
350
              completeDocid += rev;
351
              document.append("<docid>").append(completeDocid);
352
              document.append("</docid>");
353
              if (docname != null) {
354
                document.append("<docname>" + docname + "</docname>");
355
              }
356
              if (doctype != null) {
357
                document.append("<doctype>" + doctype + "</doctype>");
358
              }
359
              if (createDate != null) {
360
                document.append("<createdate>" + createDate + "</createdate>");
361
              }
362
              if (updateDate != null) {
363
                document.append("<updatedate>" + updateDate + "</updatedate>");
364
              }
365
              // Store the document id and the root node id
366
              docListResult.put(docid,(String)document.toString());
367
         
368
              // Get the next package document linked to our hit
369
              hasBtRows = btrs.next();
370
            }
371
            npstmt.close();
372
            btrs.close();
373
          } 
374
          else if (returndocVec.size() != 0 && returndocVec.contains(doctype)) 
375
          {
376
          
377
            document = new StringBuffer();
378

    
379
            String completeDocid = docid + util.getOption("accNumSeparator");
380
            completeDocid += rev;
381
            document.append("<docid>").append(completeDocid).append("</docid>");
382
            if (docname != null) {
383
              document.append("<docname>" + docname + "</docname>");
384
            }
385
            if (doctype != null) {
386
              document.append("<doctype>" + doctype + "</doctype>");
387
            }
388
            if (createDate != null) {
389
              document.append("<createdate>" + createDate + "</createdate>");
390
            }
391
            if (updateDate != null) {
392
              document.append("<updatedate>" + updateDate + "</updatedate>");
393
            }
394
            // Store the document id and the root node id
395
            docListResult.put(docid,(String)document.toString());
396
  
397
          }
398

    
399
          // Advance to the next record in the cursor
400
          tableHasRows = rs.next();
401
        }
402
        rs.close();
403
        pstmt.close();
404
        double docListTime =System.currentTimeMillis()/1000;
405
        MetaCatUtil.debugMessage("prepare docid list time: "
406
                                          +(docListTime-queryExecuteTime), 30);
407
        
408
        if (qspec.containsExtendedSQL())
409
        {
410
          Vector extendedFields = new Vector(qspec.getReturnFieldList());
411
          Vector results = new Vector();
412
          Enumeration keylist = docListResult.keys();
413
          StringBuffer doclist = new StringBuffer();
414
          Hashtable parentidList = new Hashtable();
415
          Hashtable returnFieldValue = new Hashtable();
416
          while(keylist.hasMoreElements())
417
          {
418
            doclist.append("'");
419
            doclist.append((String)keylist.nextElement());
420
            doclist.append("',");
421
          }
422
          if (doclist.length() > 0) 
423
          {
424
            Hashtable controlPairs = new Hashtable();
425
            double extendedQueryStart = System.currentTimeMillis()/1000;
426
            doclist.deleteCharAt(doclist.length()-1); //remove the last comma
427
            // check if user has permission to see the return field data
428
            String accessControlSQL = qspec.
429
                        printAccessControlSQLForReturnField(doclist.toString());
430
            pstmt = dbconn.prepareStatement(accessControlSQL);
431
            //increase dbconnection usage count
432
            dbconn.increaseUsageCount(1);
433
            pstmt.execute();
434
            rs = pstmt.getResultSet();
435
            tableHasRows = rs.next();
436
            while(tableHasRows)
437
            {
438
              long startNodeId = rs.getLong(1);
439
              long endNodeId = rs.getLong(2);
440
              controlPairs.put(new Long(startNodeId), new Long(endNodeId));
441
              tableHasRows = rs.next();
442
            }
443
            
444
            double extendedAccessQueryEnd = System.currentTimeMillis()/1000;
445
            MetaCatUtil.debugMessage("Time for execute access extended query: "
446
                              +(extendedAccessQueryEnd-extendedQueryStart), 30);
447
            
448
            String extendedQuery = qspec.printExtendedSQL(doclist.toString(), 
449
                                                          controlPairs);
450
            MetaCatUtil.debugMessage("Extended query: "+ extendedQuery, 30);
451
            pstmt = dbconn.prepareStatement(extendedQuery);
452
            //increase dbconnection usage count
453
            dbconn.increaseUsageCount(1);
454
            pstmt.execute();
455
            rs = pstmt.getResultSet();
456
            double extendedQueryEnd = System.currentTimeMillis()/1000;
457
            MetaCatUtil.debugMessage("Time for execute extended query: "
458
                                    +(extendedQueryEnd-extendedQueryStart), 30);
459
            tableHasRows = rs.next();
460
            while(tableHasRows) 
461
            {
462
              ReturnFieldValue returnValue = new ReturnFieldValue();
463
              docid = rs.getString(1).trim();
464
              fieldname = rs.getString(2);
465
              fielddata = rs.getString(3);
466
              String parentId = rs.getString(4);
467
                         
468
              StringBuffer value = new StringBuffer();
469
              if (!parentidList.containsKey(parentId))
470
              {
471
                // don't need to merger nodedata 
472
                value.append("<param name=\"");
473
                value.append(fieldname);
474
                value.append("\">");
475
                value.append(fielddata);
476
                value.append("</param>");
477
                //set returnvalue
478
                returnValue.setDocid(docid);
479
                returnValue.setFieldValue(fielddata);
480
                returnValue.setXMLFieldValue(value.toString());
481
                // Store it in hastable
482
                parentidList.put(parentId, returnValue);
483
              }
484
              else
485
              {
486
                // need to merge nodedata if they have same parent id ant
487
                // node type is text
488
                fielddata = (String)((ReturnFieldValue)
489
                       parentidList.get(parentId)).getFieldValue() +  fielddata;
490
                value.append("<param name=\"");
491
                value.append(fieldname);
492
                value.append("\">");
493
                value.append(fielddata);
494
                value.append("</param>");
495
                returnValue.setDocid(docid);
496
                returnValue.setFieldValue(fielddata);
497
                returnValue.setXMLFieldValue(value.toString());
498
                // remove the old return value from paretnidList
499
                parentidList.remove(parentId);
500
                // store the new return value in parentidlit
501
                parentidList.put(parentId, returnValue);
502
              }
503
               tableHasRows = rs.next();
504
            }//while
505
            rs.close();
506
            pstmt.close();
507
            
508
            // put the merger node data info into doclistReult
509
            Enumeration xmlFieldValue = parentidList.elements();
510
            while( xmlFieldValue.hasMoreElements() )
511
            {
512
              ReturnFieldValue object = (ReturnFieldValue)
513
                                         xmlFieldValue.nextElement();
514
              docid = object.getDocid();
515
              if (docListResult.containsKey(docid))
516
              {
517
                  String removedelement = (String)docListResult.remove(docid);
518
                  docListResult.put(docid, removedelement +
519
                                    object.getXMLFieldValue());
520
              }
521
              else
522
              {
523
                  docListResult.put(docid, object.getXMLFieldValue()); 
524
              }
525
            }//while
526
            double docListResultEnd = System.currentTimeMillis()/1000;
527
            MetaCatUtil.debugMessage("Time for prepare doclistresult after"+
528
                                      " execute extended query: "
529
                                    +(docListResultEnd-extendedQueryEnd), 30);
530
            
531
            
532
            // get attribures return
533
            docListResult = getAttributeValueForReturn
534
                                      (qspec,docListResult, doclist.toString());
535
          }//if doclist lenght is great than zero
536
          
537
        }//if has extended query
538
        
539
        
540
        //this loop adds the relation data to the resultdoc
541
        //this code might be able to be added to the backtracking code above
542
        double startRelation = System.currentTimeMillis()/1000;
543
        Enumeration docidkeys = docListResult.keys();
544
        while(docidkeys.hasMoreElements())
545
        {
546
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
547
          String connstring = "%docid=";
548
          String docidkey = (String)docidkeys.nextElement();
549
          pstmt = dbconn.prepareStatement(qspec.printRelationSQL(docidkey));
550
          pstmt.execute();
551
          rs = pstmt.getResultSet();
552
          tableHasRows = rs.next();
553
          while(tableHasRows)
554
          {
555
            String sub = rs.getString(1);
556
            String rel = rs.getString(2);
557
            String obj = rs.getString(3);
558
            String subDT = rs.getString(4);
559
            String objDT = rs.getString(5);
560
            
561
            document = new StringBuffer();
562
            document.append("<triple>");
563
            document.append("<subject>").append(MetaCatUtil.normalize(sub));
564
            document.append("</subject>");
565
            if ( subDT != null ) {
566
              document.append("<subjectdoctype>").append(subDT);
567
              document.append("</subjectdoctype>");
568
            }
569
            document.append("<relationship>").
570
                                          append(MetaCatUtil.normalize(rel));
571
            document.append("</relationship>");
572
            document.append("<object>").append(MetaCatUtil.normalize(obj));
573
            document.append("</object>");
574
            if ( objDT != null ) {
575
              document.append("<objectdoctype>").append(objDT);
576
              document.append("</objectdoctype>");
577
            }
578
            document.append("</triple>");
579
            
580
            String removedelement = (String)docListResult.remove(docidkey);
581
            docListResult.put(docidkey, removedelement + 
582
                              document.toString());
583
            tableHasRows = rs.next();
584
          }
585
          rs.close();
586
          pstmt.close();
587
        }
588
        double endRelation = System.currentTimeMillis()/1000;
589
        MetaCatUtil.debugMessage("Time for adding relation to docListResult: "+
590
                                (endRelation-startRelation), 30);
591
        
592
      } catch (SQLException e) {
593
        System.err.println("SQL Error in DBQuery.findDocuments: " + 
594
                           e.getMessage());
595
      } catch (IOException ioe) {
596
        System.err.println("IO error in DBQuery.findDocuments:");
597
        System.err.println(ioe.getMessage());
598
      } catch (Exception ee) {
599
        System.err.println("Exception in DBQuery.findDocuments: " + 
600
                           ee.getMessage());
601
        ee.printStackTrace(System.err);
602
      }
603
      finally 
604
      {
605
        try
606
        {
607
          pstmt.close();
608
        }//try
609
        catch (SQLException sqlE)
610
        {
611
          MetaCatUtil.debugMessage("Error in DBQuery.findDocuments: "
612
                                      +sqlE.getMessage(), 30);
613
        }//catch
614
        finally
615
        {
616
          DBConnectionPool.returnDBConnection(dbconn, serialNumber);
617
        }//finally
618
      }//finally
619
    //System.out.println("docListResult: ");
620
    //System.out.println(docListResult.toString());
621
    return docListResult;
622
  }
623
  
624
  /*
625
   * A method to return search result after running a query which return
626
   * field have attribue
627
   */
628
  private Hashtable getAttributeValueForReturn(QuerySpecification squery,
629
                                               Hashtable docInformationList,
630
                                               String docList)
631
  {
632
    StringBuffer XML = null;
633
    String sql = null;
634
    DBConnection dbconn = null;
635
    PreparedStatement pstmt = null;
636
    ResultSet rs = null;
637
    int serialNumber = -1;
638
    boolean tableHasRows =false;
639
    
640
    //check the parameter
641
    if (squery == null || docList==null || docList.length() <0)
642
    {
643
      return docInformationList;
644
    }
645
    
646
    // if has attribute as return field
647
    if (squery.containAttributeReturnField())
648
    {
649
      sql = squery.printAttributeQuery(docList);
650
      try 
651
      {
652
        dbconn=DBConnectionPool.getDBConnection("DBQuery.getAttributeValue");
653
        serialNumber=dbconn.getCheckOutSerialNumber();
654
        pstmt = dbconn.prepareStatement(sql);
655
        pstmt.execute();
656
        rs = pstmt.getResultSet();
657
        tableHasRows = rs.next();
658
        while(tableHasRows) 
659
        {
660
          String docid = rs.getString(1).trim();
661
          String fieldname = rs.getString(2);
662
          String fielddata = rs.getString(3);
663
          String attirbuteName = rs.getString(4);
664
          XML = new StringBuffer();
665
  
666
          XML.append("<param name=\"");
667
          XML.append(fieldname);
668
          XML.append(QuerySpecification.ATTRIBUTESYMBOL);
669
          XML.append(attirbuteName);
670
          XML.append("\">");
671
          XML.append(fielddata);
672
          XML.append("</param>");
673
          tableHasRows = rs.next();
674
          
675
          if (docInformationList.containsKey(docid))
676
          {
677
            String removedelement = (String)docInformationList.remove(docid);
678
            docInformationList.put(docid, removedelement + XML.toString());
679
          }
680
          else
681
          {
682
            docInformationList.put(docid, XML.toString()); 
683
          }
684
        }//while
685
        rs.close();
686
        pstmt.close();
687
      }
688
      catch(Exception se)
689
      {
690
        MetaCatUtil.debugMessage("Error in DBQuery.getAttributeValue1: "
691
                                      +se.getMessage(), 30);
692
      }
693
      finally
694
      {
695
        try
696
        {
697
          pstmt.close();
698
        }//try
699
        catch (SQLException sqlE)
700
        {
701
          MetaCatUtil.debugMessage("Error in DBQuery.getAttributeValue2: "
702
                                      +sqlE.getMessage(), 30);
703
        }//catch
704
        finally
705
        {
706
          DBConnectionPool.returnDBConnection(dbconn, serialNumber);
707
        }//finally
708
      }//finally
709
    }//if
710
    return docInformationList;
711
      
712
  }
713
   
714
  
715
  /*
716
   * A method to create a query to get owner's docid list
717
   */
718
  private String getOwnerQuery(String owner)
719
  {
720
    StringBuffer self = new StringBuffer();
721

    
722
    self.append("SELECT docid,docname,doctype,");
723
    self.append("date_created, date_updated, rev ");
724
    self.append("FROM xml_documents WHERE docid IN (");
725
    self.append("(");
726
    self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
727
    self.append("nodedata LIKE '%%%' ");
728
    self.append(") \n");
729
    self.append(") ");
730
    self.append(" AND (");
731
    self.append(" user_owner = '" + owner + "'");
732
    self.append(") ");
733
    return self.toString();
734
  }
735
  /**
736
   * returns a string array of the contents of a particular node. 
737
   * If the node appears more than once, the contents are returned 
738
   * in the order in which they appearred in the document.
739
   * @param nodename the name or path of the particular node.
740
   * @param docid the docid of the document you want the node from.
741
   */
742
  public static Object[] getNodeContent(String nodename, String docid)
743
  {
744
    DBConnection dbconn = null;
745
    int serialNumber = -1;
746
    StringBuffer query = new StringBuffer();
747
    Vector result = new Vector();
748
    PreparedStatement pstmt = null;
749
    query.append("select nodedata from xml_nodes where parentnodeid in ");
750
    query.append("(select nodeid from xml_index where path like '");
751
    query.append(nodename);
752
    query.append("' and docid like '").append(docid).append("')");
753
    try
754
    {
755
      dbconn=DBConnectionPool.getDBConnection("DBQuery.getNodeContent");
756
        serialNumber=dbconn.getCheckOutSerialNumber();
757
      pstmt = dbconn.prepareStatement(query.toString());
758

    
759
      // Execute the SQL query using the JDBC connection
760
      pstmt.execute();
761
      ResultSet rs = pstmt.getResultSet();
762
      boolean tableHasRows = rs.next();
763
      while (tableHasRows) 
764
      {
765
        result.add(rs.getString(1));
766
        //System.out.println(rs.getString(1));
767
        tableHasRows = rs.next();
768
      }
769
    } 
770
    catch (SQLException e) 
771
    {
772
      System.err.println("Error in DBQuery.getNodeContent: " + e.getMessage());
773
    } finally {
774
      try
775
      {
776
        pstmt.close();
777
      }
778
      catch(SQLException sqle) 
779
      {}
780
      finally
781
      {
782
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
783
      }
784
      
785
    }
786
    return result.toArray();
787
  }
788
  
789
  /**
790
   * format a structured 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 params The list of parameters that should be included in the query
795
   */
796
  public static String createSQuery(Hashtable params)
797
  { 
798
    StringBuffer query = new StringBuffer();
799
    Enumeration elements;
800
    Enumeration keys;
801
    String filterDoctype = null;
802
    String casesensitive = null;
803
    String searchmode = null;
804
    Object nextkey;
805
    Object nextelement;
806
    //add the xml headers
807
    query.append("<?xml version=\"1.0\"?>\n");
808
    query.append("<pathquery version=\"1.0\">\n");
809

    
810
    if (params.containsKey("meta_file_id"))
811
    {
812
      query.append("<meta_file_id>");
813
      query.append( ((String[])params.get("meta_file_id"))[0]);
814
      query.append("</meta_file_id>");
815
    }
816
    
817
    if (params.containsKey("returndoctype"))
818
    {
819
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
820
      for(int i=0; i<returnDoctypes.length; i++)
821
      {
822
        String doctype = (String)returnDoctypes[i];
823

    
824
        if (!doctype.equals("any") && 
825
            !doctype.equals("ANY") &&
826
            !doctype.equals("") ) 
827
        {
828
          query.append("<returndoctype>").append(doctype);
829
          query.append("</returndoctype>");
830
        }
831
      }
832
    }
833
    
834
    if (params.containsKey("filterdoctype"))
835
    {
836
      String[] filterDoctypes = ((String[])params.get("filterdoctype"));
837
      for(int i=0; i<filterDoctypes.length; i++)
838
      {
839
        query.append("<filterdoctype>").append(filterDoctypes[i]);
840
        query.append("</filterdoctype>");
841
      }
842
    }
843
    
844
    if (params.containsKey("returnfield"))
845
    {
846
      String[] returnfield = ((String[])params.get("returnfield"));
847
      for(int i=0; i<returnfield.length; i++)
848
      {
849
        query.append("<returnfield>").append(returnfield[i]);
850
        query.append("</returnfield>");
851
      }
852
    }
853
    
854
    if (params.containsKey("owner"))
855
    {
856
      String[] owner = ((String[])params.get("owner"));
857
      for(int i=0; i<owner.length; i++)
858
      {
859
        query.append("<owner>").append(owner[i]);
860
        query.append("</owner>");
861
      }
862
    }
863
    
864
    if (params.containsKey("site"))
865
    {
866
      String[] site = ((String[])params.get("site"));
867
      for(int i=0; i<site.length; i++)
868
      {
869
        query.append("<site>").append(site[i]);
870
        query.append("</site>");
871
      }
872
    }
873
    
874
    //allows the dynamic switching of boolean operators
875
    if (params.containsKey("operator"))
876
    {
877
      query.append("<querygroup operator=\"" + 
878
                ((String[])params.get("operator"))[0] + "\">");
879
    }
880
    else
881
    { //the default operator is UNION
882
      query.append("<querygroup operator=\"UNION\">"); 
883
    }
884
        
885
    if (params.containsKey("casesensitive"))
886
    {
887
      casesensitive = ((String[])params.get("casesensitive"))[0]; 
888
    }
889
    else
890
    {
891
      casesensitive = "false"; 
892
    }
893
    
894
    if (params.containsKey("searchmode"))
895
    {
896
      searchmode = ((String[])params.get("searchmode"))[0]; 
897
    }
898
    else
899
    {
900
      searchmode = "contains"; 
901
    }
902
        
903
    //anyfield is a special case because it does a 
904
    //free text search.  It does not have a <pathexpr>
905
    //tag.  This allows for a free text search within the structured
906
    //query.  This is useful if the INTERSECT operator is used.
907
    if (params.containsKey("anyfield"))
908
    {
909
       String[] anyfield = ((String[])params.get("anyfield"));
910
       //allow for more than one value for anyfield
911
       for(int i=0; i<anyfield.length; i++)
912
       {
913
         if (!anyfield[i].equals(""))
914
         {
915
           query.append("<queryterm casesensitive=\"" + casesensitive + 
916
                        "\" " + "searchmode=\"" + searchmode + "\"><value>" +
917
                        anyfield[i] +
918
                        "</value></queryterm>"); 
919
         }
920
       }
921
    }
922
        
923
    //this while loop finds the rest of the parameters
924
    //and attempts to query for the field specified
925
    //by the parameter.
926
    elements = params.elements();
927
    keys = params.keys();
928
    while(keys.hasMoreElements() && elements.hasMoreElements())
929
    {
930
      nextkey = keys.nextElement();
931
      nextelement = elements.nextElement();
932

    
933
      //make sure we aren't querying for any of these
934
      //parameters since the are already in the query
935
      //in one form or another.
936
      if (!nextkey.toString().equals("returndoctype") && 
937
         !nextkey.toString().equals("filterdoctype")  &&
938
         !nextkey.toString().equals("action")  &&
939
         !nextkey.toString().equals("qformat") && 
940
         !nextkey.toString().equals("anyfield") &&
941
         !nextkey.toString().equals("returnfield") &&
942
         !nextkey.toString().equals("owner") &&
943
         !nextkey.toString().equals("site") &&
944
         !nextkey.toString().equals("operator") )
945
      {
946
        //allow for more than value per field name
947
        for(int i=0; i<((String[])nextelement).length; i++)
948
        {
949
          if (!((String[])nextelement)[i].equals(""))
950
          {
951
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " + 
952
                         "searchmode=\"" + searchmode + "\">" +
953
                         "<value>" +
954
                         //add the query value
955
                         ((String[])nextelement)[i] +
956
                         "</value><pathexpr>" +
957
                         //add the path to query by 
958
                         nextkey.toString() + 
959
                         "</pathexpr></queryterm>");
960
          }
961
        }
962
      }
963
    }
964
    query.append("</querygroup></pathquery>");
965
    //append on the end of the xml and return the result as a string
966
    return query.toString();
967
  }
968
  
969
  /**
970
   * format a simple free-text value query as an XML document that conforms
971
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
972
   * structured query engine
973
   *
974
   * @param value the text string to search for in the xml catalog
975
   * @param doctype the type of documents to include in the result set -- use
976
   *        "any" or "ANY" for unfiltered result sets
977
   */
978
   public static String createQuery(String value, String doctype) {
979
     StringBuffer xmlquery = new StringBuffer();
980
     xmlquery.append("<?xml version=\"1.0\"?>\n");
981
     xmlquery.append("<pathquery version=\"1.0\">");
982

    
983
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
984
       xmlquery.append("<returndoctype>");
985
       xmlquery.append(doctype).append("</returndoctype>");
986
     }
987

    
988
     xmlquery.append("<querygroup operator=\"UNION\">");
989
     //chad added - 8/14
990
     //the if statement allows a query to gracefully handle a null 
991
     //query.  Without this if a nullpointerException is thrown.
992
     if (!value.equals(""))
993
     {
994
       xmlquery.append("<queryterm casesensitive=\"false\" ");
995
       xmlquery.append("searchmode=\"contains\">");
996
       xmlquery.append("<value>").append(value).append("</value>");
997
       xmlquery.append("</queryterm>");
998
     }
999
     xmlquery.append("</querygroup>");
1000
     xmlquery.append("</pathquery>");
1001

    
1002
     
1003
     return (xmlquery.toString());
1004
   }
1005

    
1006
  /**
1007
   * format a simple free-text value query as an XML document that conforms
1008
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
1009
   * structured query engine
1010
   *
1011
   * @param value the text string to search for in the xml catalog
1012
   */
1013
   public static String createQuery(String value) {
1014
     return createQuery(value, "any");
1015
   }
1016
   
1017
  /** 
1018
    * Check for "READ" permission on @docid for @user and/or @group 
1019
    * from DB connection 
1020
    */
1021
  private boolean hasPermission (String user,
1022
                                  String[] groups, String docid ) 
1023
                  throws SQLException, Exception
1024
  {
1025
    // Check for READ permission on @docid for @user and/or @groups
1026
   PermissionController controller = new PermissionController(docid);
1027
   return controller.hasPermission(user,groups,
1028
                                 AccessControlInterface.READSTRING);
1029
  }
1030

    
1031
  /**
1032
    * Get all docIds list for a data packadge
1033
    * @param dataPackageDocid, the string in docId field of xml_relation table
1034
    */
1035
  private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1036
  {
1037
    DBConnection dbConn = null;
1038
    int serialNumber = -1;
1039
    Vector docIdList=new Vector();//return value
1040
    PreparedStatement pStmt = null;
1041
    ResultSet rs=null;
1042
    String docIdInSubjectField=null;
1043
    String docIdInObjectField=null;
1044
    
1045
    // Check the parameter
1046
    if (dataPackageDocid == null || dataPackageDocid.equals(""))
1047
    {
1048
      return docIdList;
1049
    }//if
1050
    
1051
    //the query stirng
1052
    String query="SELECT subject, object from xml_relation where docId = ?";
1053
    try
1054
    {
1055
      dbConn=DBConnectionPool.
1056
                  getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1057
      serialNumber=dbConn.getCheckOutSerialNumber();
1058
      pStmt=dbConn.prepareStatement(query);
1059
      //bind the value to query
1060
      pStmt.setString(1, dataPackageDocid);
1061

    
1062
      //excute the query
1063
      pStmt.execute();
1064
      //get the result set
1065
      rs=pStmt.getResultSet();
1066
      //process the result
1067
      while (rs.next())
1068
      {
1069
        //In order to get the whole docIds in a data packadge,
1070
        //we need to put the docIds of subject and object field in xml_relation
1071
        //into the return vector
1072
        docIdInSubjectField=rs.getString(1);//the result docId in subject field
1073
        docIdInObjectField=rs.getString(2);//the result docId in object field
1074

    
1075
        //don't put the duplicate docId into the vector
1076
        if (!docIdList.contains(docIdInSubjectField))
1077
        {
1078
          docIdList.add(docIdInSubjectField);
1079
        }
1080

    
1081
        //don't put the duplicate docId into the vector
1082
        if (!docIdList.contains(docIdInObjectField))
1083
        {
1084
          docIdList.add(docIdInObjectField);
1085
        }
1086
      }//while
1087
      //close the pStmt
1088
      pStmt.close();
1089
    }//try
1090
    catch (SQLException e)
1091
    {
1092
      MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1093
                            +e.getMessage(), 30);
1094
    }//catch
1095
    finally
1096
    {
1097
      try
1098
      {
1099
        pStmt.close();
1100
      }//try
1101
      catch (SQLException ee)
1102
      {
1103
        MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1104
                            +ee.getMessage(), 30);
1105
      }//catch     
1106
      finally
1107
      {
1108
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1109
      }//fianlly
1110
    }//finally
1111
    return docIdList;
1112
  }//getCurrentDocidListForDataPackadge()
1113
  
1114
  /**
1115
   * Get all docIds list for a data packadge
1116
   * @param dataPackageDocid, the string in docId field of xml_relation table
1117
   */
1118
  private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1119
  {
1120
   
1121
    Vector docIdList=new Vector();//return value
1122
    Vector tripleList=null;
1123
    String xml=null;
1124
    
1125
     // Check the parameter
1126
    if (dataPackageDocid == null || dataPackageDocid.equals(""))
1127
    {
1128
      return docIdList;
1129
    }//if
1130
    
1131
    try
1132
    {
1133
      //initial a documentImpl object 
1134
      DocumentImpl packageDocument = 
1135
                  new DocumentImpl(dataPackageDocid);
1136
      //transfer to documentImpl object to string
1137
      xml=packageDocument.toString();
1138
    
1139
      //create a tripcollection object
1140
      TripleCollection tripleForPackage = new 
1141
                                     TripleCollection(new StringReader(xml));
1142
      //get the vetor of triples 
1143
      tripleList=tripleForPackage.getCollection();
1144
    
1145
      for (int i= 0; i<tripleList.size(); i++)
1146
      {
1147
        //put subject docid  into docIdlist without duplicate
1148
        if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getSubject()))
1149
        {
1150
          //put subject docid  into docIdlist
1151
          docIdList.add(((Triple)tripleList.get(i)).getSubject());
1152
        }
1153
        //put object docid into docIdlist without duplicate
1154
        if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getObject()))
1155
        {
1156
          docIdList.add(((Triple)(tripleList.get(i))).getObject());
1157
        }
1158
      }//for
1159
    }//try
1160
    catch (Exception e)
1161
    {
1162
      MetaCatUtil.debugMessage("Error in getOldVersionAllDocumentImpl: "
1163
                            +e.getMessage(), 30);
1164
    }//catch
1165
  
1166
    // return result
1167
    return docIdList;
1168
  }//getDocidListForPackageInXMLRevisions()  
1169
  
1170
  /**
1171
   * Check if the docId is a data packadge id. If the id is a data packadage 
1172
   *id, it should be store in the docId fields in xml_relation table.
1173
   *So we can use a query to get the entries which the docId equals the given 
1174
   *value. If the result is null. The docId is not a packadge id. Otherwise,
1175
   * it is.
1176
   * @param docId, the id need to be checked
1177
   */
1178
  private boolean isDataPackageId(String docId)
1179
  {
1180
    boolean result=false;
1181
    PreparedStatement pStmt = null;
1182
    ResultSet rs=null;
1183
    String query="SELECT docId from xml_relation where docId = ?";
1184
    DBConnection dbConn = null;
1185
    int serialNumber = -1;
1186
    try
1187
    {
1188
      dbConn=DBConnectionPool.
1189
                  getDBConnection("DBQuery.isDataPackageId");
1190
      serialNumber=dbConn.getCheckOutSerialNumber();
1191
      pStmt=dbConn.prepareStatement(query);
1192
      //bind the value to query
1193
      pStmt.setString(1, docId);
1194
      //execute the query
1195
      pStmt.execute();
1196
      rs=pStmt.getResultSet();
1197
      //process the result
1198
      if (rs.next()) //There are some records for the id in docId fields
1199
      {
1200
        result=true;//It is a data packadge id
1201
      }
1202
      pStmt.close();
1203
    }//try
1204
    catch (SQLException e)
1205
    {
1206
      util.debugMessage("Error in isDataPackageId: "
1207
                            +e.getMessage(), 30);
1208
    }
1209
    finally
1210
    {
1211
      try
1212
      {
1213
        pStmt.close();
1214
      }//try
1215
      catch (SQLException ee)
1216
      {
1217
        MetaCatUtil.debugMessage("Error in isDataPackageId: "
1218
                                                        + ee.getMessage(), 30);
1219
      }//catch
1220
      finally
1221
      {
1222
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1223
      }//finally
1224
    }//finally
1225
    return result;
1226
  }//isDataPackageId()
1227
  
1228
  /**
1229
   * Check if the user has the permission to export data package
1230
   * @param conn, the connection
1231
   * @param docId, the id need to be checked
1232
   * @param user, the name of user
1233
   * @param groups, the user's group
1234
   */ 
1235
   private boolean hasPermissionToExportPackage(String docId, 
1236
                                        String user, String[] groups)
1237
                   throws Exception
1238
   {
1239
     //DocumentImpl doc=new DocumentImpl(conn,docId);
1240
     return DocumentImpl.hasReadPermission(user, groups,docId);
1241
   }
1242
   
1243
  /**
1244
   *Get the current Rev for a docid in xml_documents table
1245
   * @param docId, the id need to get version numb
1246
   * If the return value is -5, means no value in rev field for this docid
1247
   */
1248
  private int getCurrentRevFromXMLDoumentsTable(String docId)
1249
                                                throws SQLException
1250
  {
1251
    int rev=-5;
1252
    PreparedStatement pStmt = null;
1253
    ResultSet rs=null;
1254
    String query="SELECT rev from xml_documents where docId = ?";
1255
    DBConnection dbConn=null;
1256
    int serialNumber = -1;
1257
    try
1258
    {
1259
      dbConn=DBConnectionPool.
1260
                  getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1261
      serialNumber=dbConn.getCheckOutSerialNumber();
1262
      pStmt=dbConn.prepareStatement(query);
1263
      //bind the value to query
1264
      pStmt.setString(1, docId);
1265
      //execute the query
1266
      pStmt.execute();
1267
      rs=pStmt.getResultSet();
1268
      //process the result
1269
      if (rs.next()) //There are some records for rev
1270
      {
1271
        rev=rs.getInt(1);;//It is the version for given docid
1272
      }
1273
      else
1274
      {
1275
        rev=-5;
1276
      }
1277
     
1278
    }//try
1279
    catch (SQLException e)
1280
    {
1281
      MetaCatUtil.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
1282
                            +e.getMessage(), 30);
1283
      throw e;
1284
    }//catch
1285
    finally
1286
    {
1287
      try
1288
      {
1289
        pStmt.close();
1290
      }//try
1291
      catch (SQLException ee)
1292
      {
1293
        MetaCatUtil.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
1294
                                  +ee.getMessage(), 30);
1295
      }//catch
1296
      finally
1297
      {
1298
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1299
      }//finally
1300
    }//finally
1301
    return rev;
1302
  }//getCurrentRevFromXMLDoumentsTable
1303
 
1304
 /**
1305
   *put a doc into a zip output stream
1306
   *@param docImpl, docmentImpl object which will be sent to zip output stream
1307
   *@param zipOut, zip output stream which the docImpl will be put
1308
   *@param packageZipEntry, the zip entry name for whole package
1309
   */
1310
  private void addDocToZipOutputStream(DocumentImpl docImpl, 
1311
                                ZipOutputStream zipOut, String packageZipEntry)
1312
               throws ClassNotFoundException, IOException, SQLException, 
1313
                      McdbException, Exception
1314
  {
1315
    byte[] byteString = null;
1316
    ZipEntry zEntry = null;
1317

    
1318
    byteString = docImpl.toString().getBytes();
1319
    //use docId as the zip entry's name
1320
    zEntry = new ZipEntry(packageZipEntry+"/metadata/"+docImpl.getDocID());
1321
    zEntry.setSize(byteString.length);
1322
    zipOut.putNextEntry(zEntry);
1323
    zipOut.write(byteString, 0, byteString.length);
1324
    zipOut.closeEntry();
1325
  
1326
  }//addDocToZipOutputStream()
1327

    
1328
  
1329
  /**
1330
   * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor 
1331
   * only inlcudes current version. If a DocumentImple object
1332
   * couldn't find for a docid, then the String of this docid was added to vetor
1333
   * rather than DocumentImple object.
1334
   * @param docIdList, a vetor hold a docid list for a data package. In docid,
1335
   * there is not version number in it.
1336
   */  
1337
  
1338
  private Vector getCurrentAllDocumentImpl( Vector docIdList)
1339
                              throws McdbException,Exception
1340
  {
1341
    //Connection dbConn=null;
1342
    Vector documentImplList=new Vector();
1343
    int rev=0; 
1344
    
1345
    // Check the parameter
1346
    if (docIdList.isEmpty())
1347
    {
1348
      return documentImplList;
1349
    }//if
1350
  
1351
    //for every docid in vector
1352
    for (int i=0;i<docIdList.size();i++)
1353
    {
1354
      try
1355
      {
1356
        //get newest version for this docId
1357
        rev=getCurrentRevFromXMLDoumentsTable((String)docIdList.elementAt(i));
1358
      
1359
        // There is no record for this docId in xml_documents table
1360
        if (rev ==-5)
1361
        {
1362
          // Rather than put DocumentImple object, put a String Object(docid)
1363
          // into the documentImplList
1364
          documentImplList.add((String)docIdList.elementAt(i));
1365
          // Skip other code
1366
          continue;
1367
        }
1368
     
1369
        String docidPlusVersion=((String)docIdList.elementAt(i))
1370
                        +util.getOption("accNumSeparator")+rev;
1371
      
1372
      
1373
        //create new documentImpl object
1374
        DocumentImpl documentImplObject = 
1375
                                    new DocumentImpl(docidPlusVersion);
1376
       //add them to vector                            
1377
        documentImplList.add(documentImplObject);
1378
      }//try
1379
      catch (Exception e)
1380
      {
1381
        MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1382
                            +e.getMessage(), 30);
1383
        // continue the for loop
1384
        continue;
1385
      }
1386
    }//for
1387
    return documentImplList;
1388
  }
1389
  
1390
  /**
1391
   * Transfer a docid vetor to a documentImpl vector. If a DocumentImple object
1392
   * couldn't find for a docid, then the String of this docid was added to vetor
1393
   * rather than DocumentImple object.
1394
   * @param docIdList, a vetor hold a docid list for a data package. In docid,
1395
   *t here is version number in it.
1396
   */    
1397
  private Vector getOldVersionAllDocumentImpl( Vector docIdList)
1398
  {
1399
    //Connection dbConn=null;
1400
    Vector documentImplList=new Vector();
1401
    String siteCode=null;
1402
    String uniqueId=null;
1403
    int rev=0; 
1404
    
1405
    // Check the parameter
1406
    if (docIdList.isEmpty())
1407
    {
1408
      return documentImplList;
1409
    }//if
1410
    
1411
    //for every docid in vector
1412
    for (int i=0;i<docIdList.size();i++)
1413
    {
1414
      
1415
        String docidPlusVersion=(String)(docIdList.elementAt(i));
1416
        
1417
        try
1418
        {
1419
          //create new documentImpl object
1420
          DocumentImpl documentImplObject = 
1421
                                    new DocumentImpl(docidPlusVersion);
1422
          //add them to vector                            
1423
          documentImplList.add(documentImplObject);
1424
        }//try
1425
        catch (McdbDocNotFoundException notFoundE)
1426
        {
1427
          MetaCatUtil.debugMessage("Error in DBQuery.getOldVersionAllDocument"+
1428
                                  "Imple" + notFoundE.getMessage(), 30);
1429
          // Rather than add a DocumentImple object into vetor, a String object
1430
          // - the doicd was added to the vector
1431
          documentImplList.add(docidPlusVersion);
1432
          // Continue the for loop
1433
          continue;
1434
        }//catch
1435
        catch (Exception e)
1436
        {
1437
          MetaCatUtil.debugMessage("Error in DBQuery.getOldVersionAllDocument"+
1438
                                  "Imple" + e.getMessage(), 30);
1439
          // Continue the for loop
1440
          continue;
1441
        }//catch
1442
          
1443
      
1444
    }//for
1445
    return documentImplList;
1446
  }//getOldVersionAllDocumentImple
1447
  
1448
  /**
1449
   *put a data file into a zip output stream
1450
   *@param docImpl, docmentImpl object which will be sent to zip output stream
1451
   *@param zipOut, the zip output stream which the docImpl will be put
1452
   *@param packageZipEntry, the zip entry name for whole package
1453
   */
1454
  private void addDataFileToZipOutputStream(DocumentImpl docImpl,
1455
                                ZipOutputStream zipOut, String packageZipEntry)
1456
               throws ClassNotFoundException, IOException, SQLException,
1457
                      McdbException, Exception
1458
  {
1459
    byte[] byteString = null;
1460
    ZipEntry zEntry = null;
1461
    // this is data file; add file to zip
1462
    String filePath = util.getOption("datafilepath");
1463
    if (!filePath.endsWith("/")) 
1464
    {
1465
      filePath += "/";
1466
    }
1467
    String fileName = filePath + docImpl.getDocID();
1468
    zEntry = new ZipEntry(packageZipEntry+"/data/"+docImpl.getDocID());
1469
    zipOut.putNextEntry(zEntry);
1470
    FileInputStream fin = null;
1471
    try
1472
    {
1473
      fin = new FileInputStream(fileName);
1474
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1475
      int b = fin.read(buf);
1476
      while (b != -1)
1477
      {
1478
        zipOut.write(buf, 0, b);
1479
        b = fin.read(buf);
1480
      }//while
1481
      zipOut.closeEntry();
1482
    }//try
1483
    catch (IOException ioe)
1484
    {
1485
      util.debugMessage("There is an exception: "+ioe.getMessage(), 30);
1486
    }//catch
1487
  }//addDataFileToZipOutputStream()
1488

    
1489
  /**
1490
   *create a html summary for data package and put it into zip output stream
1491
   *@param docImplList, the documentImpl ojbects in data package
1492
   *@param zipOut, the zip output stream which the html should be put
1493
   *@param packageZipEntry, the zip entry name for whole package
1494
   */
1495
   private void addHtmlSummaryToZipOutputStream(Vector docImplList,
1496
                                ZipOutputStream zipOut, String packageZipEntry)
1497
                                           throws Exception
1498
  {
1499
    StringBuffer htmlDoc = new StringBuffer();
1500
    ZipEntry zEntry = null;
1501
    byte[] byteString=null;
1502
    InputStream source;
1503
    DBTransform xmlToHtml;
1504
  
1505
    //create a DBTransform ojbect
1506
    xmlToHtml = new DBTransform();
1507
    //head of html
1508
    htmlDoc.append("<html><head></head><body>");
1509
    for (int i=0; i<docImplList.size(); i++)
1510
    {
1511
      // If this String object, this means it is missed data file
1512
      if ((((docImplList.elementAt(i)).getClass()).toString())
1513
                                             .equals("class java.lang.String"))
1514
      {
1515
        
1516
        htmlDoc.append("<a href=\"");
1517
        String dataFileid =(String)docImplList.elementAt(i);
1518
        htmlDoc.append("./data/").append(dataFileid).append("\">");
1519
        htmlDoc.append("Data File: ");
1520
        htmlDoc.append(dataFileid).append("</a><br>");
1521
        htmlDoc.append("<br><hr><br>");
1522
        
1523
      }//if
1524
      else if ((((DocumentImpl)docImplList.elementAt(i)).getDoctype()).
1525
                                                         compareTo("BIN")!=0)
1526
      { //this is an xml file so we can transform it.
1527
        //transform each file individually then concatenate all of the
1528
        //transformations together.
1529

    
1530
        //for metadata xml title
1531
        htmlDoc.append("<h2>");
1532
        htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getDocID());
1533
        //htmlDoc.append(".");
1534
        //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
1535
        htmlDoc.append("</h2>");
1536
        //do the actual transform
1537
        StringWriter docString = new StringWriter();
1538
        xmlToHtml.transformXMLDocument(
1539
                        ((DocumentImpl)docImplList.elementAt(i)).toString(),
1540
           "-//NCEAS//eml-generic//EN", "-//W3C//HTML//EN", "html", docString);
1541
        htmlDoc.append(docString.toString());
1542
        htmlDoc.append("<br><br><hr><br><br>");
1543
      }//if
1544
      else
1545
      { //this is a data file so we should link to it in the html
1546
        htmlDoc.append("<a href=\"");
1547
        String dataFileid =((DocumentImpl)docImplList.elementAt(i)).getDocID();
1548
        htmlDoc.append("./data/").append(dataFileid).append("\">");
1549
        htmlDoc.append("Data File: ");
1550
        htmlDoc.append(dataFileid).append("</a><br>");
1551
        htmlDoc.append("<br><hr><br>");
1552
      }//else
1553
    }//for
1554
    htmlDoc.append("</body></html>");
1555
    byteString = htmlDoc.toString().getBytes();
1556
    zEntry = new ZipEntry(packageZipEntry+"/metadata.html");
1557
    zEntry.setSize(byteString.length);
1558
    zipOut.putNextEntry(zEntry);
1559
    zipOut.write(byteString, 0, byteString.length);
1560
    zipOut.closeEntry();
1561
    //dbConn.close();
1562
        
1563
  }//addHtmlSummaryToZipOutputStream
1564
  
1565
  
1566
  
1567
  /**
1568
   * put a data packadge into a zip output stream
1569
   * @param docId, which the user want to put into zip output stream
1570
   * @param out, a servletoutput stream which the zip output stream will be put 
1571
   * @param user, the username of the user
1572
   * @param groups, the group of the user
1573
   */
1574
  public ZipOutputStream getZippedPackage(String docIdString, 
1575
        ServletOutputStream out, String user, String[] groups, String passWord)
1576
                    throws ClassNotFoundException, IOException, SQLException, 
1577
                      McdbException, NumberFormatException, Exception
1578
  { 
1579
    ZipOutputStream zOut = null;
1580
    String elementDocid=null;
1581
    DocumentImpl docImpls=null;
1582
    //Connection dbConn = null;
1583
    Vector docIdList=new Vector();
1584
    Vector documentImplList=new Vector();
1585
    Vector htmlDocumentImplList=new Vector();
1586
    String packageId=null;
1587
    String rootName="package";//the package zip entry name
1588
    
1589
    String docId=null;
1590
    int version=-5;
1591
    // Docid without revision
1592
    docId=MetaCatUtil.getDocIdFromString(docIdString);
1593
    // revision number
1594
    version=MetaCatUtil.getVersionFromString(docIdString);
1595
 
1596
    //check if the reqused docId is a data package id
1597
    if (!isDataPackageId(docId))
1598
    {
1599
      
1600
      /*Exception e = new Exception("The request the doc id " +docIdString+
1601
                                    " is not a data package id");
1602
      throw e;*/
1603
      
1604
      
1605
      //CB 1/6/03: if the requested docid is not a datapackage, we just zip
1606
      //up the single document and return the zip file.
1607

    
1608
      if(!hasPermissionToExportPackage(docId, user, groups))
1609
      {
1610

    
1611
        Exception e = new Exception("User " + user + " does not have permission"
1612
                         +" to export the data package " + docIdString);
1613
        throw e;
1614
      }
1615

    
1616
      docImpls=new DocumentImpl(docId);
1617
      //checking if the user has the permission to read the documents
1618
      if (docImpls.hasReadPermission(user,groups,docImpls.getDocID()))
1619
      {
1620
        zOut = new ZipOutputStream(out);
1621
        //if the docImpls is metadata
1622
        if ((docImpls.getDoctype()).compareTo("BIN")!=0)
1623
        {
1624
          //add metadata into zip output stream
1625
          addDocToZipOutputStream(docImpls, zOut, rootName);
1626
        }//if
1627
        else
1628
        {
1629
          //it is data file
1630
          addDataFileToZipOutputStream(docImpls, zOut, rootName);
1631
          htmlDocumentImplList.add(docImpls);
1632
        }//else
1633
      }//if
1634

    
1635
      zOut.finish(); //terminate the zip file
1636
      return zOut;
1637
    }
1638
    // Check the permission of user
1639
    else if(!hasPermissionToExportPackage(docId, user, groups))
1640
    {
1641
      
1642
      Exception e = new Exception("User " + user + " does not have permission"
1643
                       +" to export the data package " + docIdString);
1644
      throw e;
1645
    }
1646
    else //it is a packadge id
1647
    { 
1648
      //store the package id
1649
      packageId=docId;
1650
      //get current version in database
1651
      int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
1652
      //If it is for current version (-1 means user didn't specify revision)
1653
      if ((version ==-1)||version==currentVersion)
1654
      { 
1655
        //get current version number
1656
        version=currentVersion;
1657
        //get package zip entry name
1658
        //it should be docId.revsion.package
1659
        rootName=packageId+util.getOption("accNumSeparator")+version+
1660
                                  util.getOption("accNumSeparator")+"package";
1661
        //get the whole id list for data packadge
1662
        docIdList=getCurrentDocidListForDataPackage(packageId);
1663
        //get the whole documentImple object
1664
        documentImplList=getCurrentAllDocumentImpl(docIdList);
1665
       
1666
      }//if
1667
      else if (version > currentVersion || version < -1)
1668
      {
1669
        throw new Exception ("The user specified docid: "+docId+"."+version
1670
                                              +" doesn't exist");
1671
      }//else if
1672
      else  //for an old version
1673
      {
1674
       
1675
        rootName=docIdString+util.getOption("accNumSeparator")+"package";
1676
        //get the whole id list for data packadge
1677
        docIdList=getOldVersionDocidListForDataPackage(docIdString);
1678

    
1679
        //get the whole documentImple object
1680
        documentImplList=getOldVersionAllDocumentImpl(docIdList);
1681
      }//else  
1682
      
1683
      // Make sure documentImplist is not empty
1684
      if (documentImplList.isEmpty())
1685
      {
1686
        throw new Exception ("Couldn't find component for data package: "
1687
                                              + packageId);
1688
      }//if
1689
      
1690
     
1691
       zOut = new ZipOutputStream(out);
1692
      //put every element into zip output stream
1693
      for (int i=0; i < documentImplList.size(); i++ )
1694
      {
1695
        // if the object in the vetor is String, this means we couldn't find
1696
        // the document locally, we need find it remote
1697
       if ((((documentImplList.elementAt(i)).getClass()).toString())
1698
                                             .equals("class java.lang.String"))
1699
        {
1700
          // Get String object from vetor
1701
          String documentId = (String) documentImplList.elementAt(i);
1702
          MetaCatUtil.debugMessage("docid: "+documentId, 30);
1703
          // Get doicd without revision
1704
          String docidWithoutRevision = 
1705
                                     MetaCatUtil.getDocIdFromString(documentId);
1706
          MetaCatUtil.debugMessage("docidWithoutRevsion: "
1707
                                                     +docidWithoutRevision, 30);
1708
          // Get revision
1709
          String revision = MetaCatUtil.getRevisionStringFromString(documentId);
1710
          MetaCatUtil.debugMessage("revsion from docIdentifier: "+revision, 30);
1711
          // Zip entry string
1712
          String zipEntryPath = rootName+"/data/"; 
1713
          // Create a RemoteDocument object
1714
          RemoteDocument remoteDoc = 
1715
                          new RemoteDocument(docidWithoutRevision,revision,user, 
1716
                                                     passWord, zipEntryPath);
1717
          // Here we only read data file from remote metacat
1718
          String docType = remoteDoc.getDocType();
1719
          if (docType!=null)
1720
          {
1721
            if (docType.equals("BIN"))
1722
            {
1723
              // Put remote document to zip output
1724
              remoteDoc.readDocumentFromRemoteServerByZip(zOut);
1725
              // Add String object to htmlDocumentImplList
1726
              String elementInHtmlList = remoteDoc.getDocIdWithoutRevsion()+
1727
               MetaCatUtil.getOption("accNumSeparator")+remoteDoc.getRevision();
1728
              htmlDocumentImplList.add(elementInHtmlList);
1729
            }//if
1730
          }//if
1731
         
1732
        }//if
1733
        else
1734
        {
1735
          //create a docmentImpls object (represent xml doc) base on the docId
1736
          docImpls=(DocumentImpl)documentImplList.elementAt(i);
1737
          //checking if the user has the permission to read the documents
1738
          if (docImpls.hasReadPermission(user,groups,docImpls.getDocID()))
1739
          {  
1740
            //if the docImpls is metadata 
1741
            if ((docImpls.getDoctype()).compareTo("BIN")!=0)  
1742
            {
1743
              //add metadata into zip output stream
1744
              addDocToZipOutputStream(docImpls, zOut, rootName);
1745
              //add the documentImpl into the vetor which will be used in html
1746
              htmlDocumentImplList.add(docImpls);
1747
           
1748
            }//if
1749
            else 
1750
            {
1751
              //it is data file 
1752
              addDataFileToZipOutputStream(docImpls, zOut, rootName);
1753
              htmlDocumentImplList.add(docImpls);
1754
            }//else
1755
          }//if
1756
        }//else
1757
      }//for
1758

    
1759
      //add html summary file
1760
      addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut, rootName);
1761
      zOut.finish(); //terminate the zip file
1762
      //dbConn.close();
1763
      return zOut;
1764
    }//else
1765
  }//getZippedPackage()
1766
  
1767
   private class ReturnFieldValue
1768
  {
1769
    private String docid          = null; //return field value for this docid
1770
    private String fieldValue     = null;
1771
    private String xmlFieldValue  = null; //return field value in xml format
1772

    
1773
    
1774
    public void setDocid(String myDocid)
1775
    {
1776
      docid = myDocid;
1777
    }
1778
    
1779
    public String getDocid()
1780
    {
1781
      return docid;
1782
    }
1783
    
1784
    public void setFieldValue(String myValue)
1785
    {
1786
      fieldValue = myValue;
1787
    }
1788
    
1789
    public String getFieldValue()
1790
    {
1791
      return fieldValue;
1792
    }
1793
    
1794
    public void setXMLFieldValue(String xml)
1795
    {
1796
      xmlFieldValue = xml;
1797
    }
1798
    
1799
    public String getXMLFieldValue()
1800
    {
1801
      return xmlFieldValue;
1802
    }
1803
    
1804
   
1805
  }
1806
   
1807
}
(20-20/54)