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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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