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

    
699
    self.append("SELECT docid,docname,doctype,");
700
    self.append("date_created, date_updated, rev ");
701
    self.append("FROM xml_documents WHERE docid IN (");
702
    self.append("(");
703
    self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
704
    self.append("nodedata LIKE '%%%' ");
705
    self.append(") \n");
706
    self.append(") ");
707
    self.append(" AND (");
708
    self.append(" user_owner = '" + owner + "'");
709
    self.append(") ");
710
    return self.toString();
711
  }
712
  /**
713
   * returns a string array of the contents of a particular node. 
714
   * If the node appears more than once, the contents are returned 
715
   * in the order in which they appearred in the document.
716
   * @param nodename the name or path of the particular node.
717
   * @param docid the docid of the document you want the node from.
718
   */
719
  public static Object[] getNodeContent(String nodename, String docid)
720
  {
721
    DBConnection dbconn = null;
722
    int serialNumber = -1;
723
    StringBuffer query = new StringBuffer();
724
    Vector result = new Vector();
725
    PreparedStatement pstmt = null;
726
    query.append("select nodedata from xml_nodes where parentnodeid in ");
727
    query.append("(select nodeid from xml_index where path like '");
728
    query.append(nodename);
729
    query.append("' and docid like '").append(docid).append("')");
730
    try
731
    {
732
      dbconn=DBConnectionPool.getDBConnection("DBQuery.getNodeContent");
733
        serialNumber=dbconn.getCheckOutSerialNumber();
734
      pstmt = dbconn.prepareStatement(query.toString());
735

    
736
      // Execute the SQL query using the JDBC connection
737
      pstmt.execute();
738
      ResultSet rs = pstmt.getResultSet();
739
      boolean tableHasRows = rs.next();
740
      while (tableHasRows) 
741
      {
742
        result.add(rs.getString(1));
743
        //System.out.println(rs.getString(1));
744
        tableHasRows = rs.next();
745
      }
746
    } 
747
    catch (SQLException e) 
748
    {
749
      System.err.println("Error in DBQuery.getNodeContent: " + e.getMessage());
750
    } finally {
751
      try
752
      {
753
        pstmt.close();
754
      }
755
      catch(SQLException sqle) 
756
      {}
757
      finally
758
      {
759
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
760
      }
761
      
762
    }
763
    return result.toArray();
764
  }
765
  
766
  /**
767
   * format a structured query as an XML document that conforms
768
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
769
   * structured query engine
770
   *
771
   * @param params The list of parameters that should be included in the query
772
   */
773
  public static String createSQuery(Hashtable params)
774
  { 
775
    StringBuffer query = new StringBuffer();
776
    Enumeration elements;
777
    Enumeration keys;
778
    String filterDoctype = null;
779
    String casesensitive = null;
780
    String searchmode = null;
781
    Object nextkey;
782
    Object nextelement;
783
    //add the xml headers
784
    query.append("<?xml version=\"1.0\"?>\n");
785
    query.append("<pathquery version=\"1.0\">\n");
786

    
787
    if (params.containsKey("meta_file_id"))
788
    {
789
      query.append("<meta_file_id>");
790
      query.append( ((String[])params.get("meta_file_id"))[0]);
791
      query.append("</meta_file_id>");
792
    }
793
    
794
    if (params.containsKey("returndoctype"))
795
    {
796
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
797
      for(int i=0; i<returnDoctypes.length; i++)
798
      {
799
        String doctype = (String)returnDoctypes[i];
800

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

    
910
      //make sure we aren't querying for any of these
911
      //parameters since the are already in the query
912
      //in one form or another.
913
      if (!nextkey.toString().equals("returndoctype") && 
914
         !nextkey.toString().equals("filterdoctype")  &&
915
         !nextkey.toString().equals("action")  &&
916
         !nextkey.toString().equals("qformat") && 
917
         !nextkey.toString().equals("anyfield") &&
918
         !nextkey.toString().equals("returnfield") &&
919
         !nextkey.toString().equals("owner") &&
920
         !nextkey.toString().equals("site") &&
921
         !nextkey.toString().equals("operator") )
922
      {
923
        //allow for more than value per field name
924
        for(int i=0; i<((String[])nextelement).length; i++)
925
        {
926
          if (!((String[])nextelement)[i].equals(""))
927
          {
928
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " + 
929
                         "searchmode=\"" + searchmode + "\">" +
930
                         "<value>" +
931
                         //add the query value
932
                         ((String[])nextelement)[i] +
933
                         "</value><pathexpr>" +
934
                         //add the path to query by 
935
                         nextkey.toString() + 
936
                         "</pathexpr></queryterm>");
937
          }
938
        }
939
      }
940
    }
941
    query.append("</querygroup></pathquery>");
942
    //append on the end of the xml and return the result as a string
943
    return query.toString();
944
  }
945
  
946
  /**
947
   * format a simple free-text value query as an XML document that conforms
948
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
949
   * structured query engine
950
   *
951
   * @param value the text string to search for in the xml catalog
952
   * @param doctype the type of documents to include in the result set -- use
953
   *        "any" or "ANY" for unfiltered result sets
954
   */
955
   public static String createQuery(String value, String doctype) {
956
     StringBuffer xmlquery = new StringBuffer();
957
     xmlquery.append("<?xml version=\"1.0\"?>\n");
958
     xmlquery.append("<pathquery version=\"1.0\">");
959

    
960
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
961
       xmlquery.append("<returndoctype>");
962
       xmlquery.append(doctype).append("</returndoctype>");
963
     }
964

    
965
     xmlquery.append("<querygroup operator=\"UNION\">");
966
     //chad added - 8/14
967
     //the if statement allows a query to gracefully handle a null 
968
     //query.  Without this if a nullpointerException is thrown.
969
     if (!value.equals(""))
970
     {
971
       xmlquery.append("<queryterm casesensitive=\"false\" ");
972
       xmlquery.append("searchmode=\"contains\">");
973
       xmlquery.append("<value>").append(value).append("</value>");
974
       xmlquery.append("</queryterm>");
975
     }
976
     xmlquery.append("</querygroup>");
977
     xmlquery.append("</pathquery>");
978

    
979
     
980
     return (xmlquery.toString());
981
   }
982

    
983
  /**
984
   * format a simple free-text value query as an XML document that conforms
985
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
986
   * structured query engine
987
   *
988
   * @param value the text string to search for in the xml catalog
989
   */
990
   public static String createQuery(String value) {
991
     return createQuery(value, "any");
992
   }
993
   
994
  /** 
995
    * Check for "READ" permission on @docid for @user and/or @group 
996
    * from DB connection 
997
    */
998
  private boolean hasPermission (String user,
999
                                  String[] groups, String docid ) 
1000
                  throws SQLException, Exception
1001
  {
1002
    // Check for READ permission on @docid for @user and/or @groups
1003
    //AccessControlList aclobj = new AccessControlList();
1004
    //return aclobj.hasPermission("READ", user, groups, docid);
1005
    return AccessControlList.hasPermission("READ", user, groups, docid);
1006
  }
1007

    
1008
  /**
1009
    * Get all docIds list for a data packadge
1010
    * @param dataPackageDocid, the string in docId field of xml_relation table
1011
    */
1012
  private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1013
  {
1014
    DBConnection dbConn = null;
1015
    int serialNumber = -1;
1016
    Vector docIdList=new Vector();//return value
1017
    PreparedStatement pStmt = null;
1018
    ResultSet rs=null;
1019
    String docIdInSubjectField=null;
1020
    String docIdInObjectField=null;
1021
    
1022
    // Check the parameter
1023
    if (dataPackageDocid == null || dataPackageDocid.equals(""))
1024
    {
1025
      return docIdList;
1026
    }//if
1027
    
1028
    //the query stirng
1029
    String query="SELECT subject, object from xml_relation where docId = ?";
1030
    try
1031
    {
1032
      dbConn=DBConnectionPool.
1033
                  getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1034
      serialNumber=dbConn.getCheckOutSerialNumber();
1035
      pStmt=dbConn.prepareStatement(query);
1036
      //bind the value to query
1037
      pStmt.setString(1, dataPackageDocid);
1038

    
1039
      //excute the query
1040
      pStmt.execute();
1041
      //get the result set
1042
      rs=pStmt.getResultSet();
1043
      //process the result
1044
      while (rs.next())
1045
      {
1046
        //In order to get the whole docIds in a data packadge,
1047
        //we need to put the docIds of subject and object field in xml_relation
1048
        //into the return vector
1049
        docIdInSubjectField=rs.getString(1);//the result docId in subject field
1050
        docIdInObjectField=rs.getString(2);//the result docId in object field
1051

    
1052
        //don't put the duplicate docId into the vector
1053
        if (!docIdList.contains(docIdInSubjectField))
1054
        {
1055
          docIdList.add(docIdInSubjectField);
1056
        }
1057

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

    
1295
    byteString = docImpl.toString().getBytes();
1296
    //use docId as the zip entry's name
1297
    zEntry = new ZipEntry(packageZipEntry+"/metadata/"+docImpl.getDocID());
1298
    zEntry.setSize(byteString.length);
1299
    zipOut.putNextEntry(zEntry);
1300
    zipOut.write(byteString, 0, byteString.length);
1301
    zipOut.closeEntry();
1302
  
1303
  }//addDocToZipOutputStream()
1304

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

    
1466
  /**
1467
   *create a html summary for data package and put it into zip output stream
1468
   *@param docImplList, the documentImpl ojbects in data package
1469
   *@param zipOut, the zip output stream which the html should be put
1470
   *@param packageZipEntry, the zip entry name for whole package
1471
   */
1472
   private void addHtmlSummaryToZipOutputStream(Vector docImplList,
1473
                                ZipOutputStream zipOut, String packageZipEntry)
1474
                                           throws Exception
1475
  {
1476
    StringBuffer htmlDoc = new StringBuffer();
1477
    ZipEntry zEntry = null;
1478
    byte[] byteString=null;
1479
    InputStream source;
1480
    DBTransform xmlToHtml;
1481
  
1482
    //create a DBTransform ojbect
1483
    xmlToHtml = new DBTransform();
1484
    //head of html
1485
    htmlDoc.append("<html><head></head><body>");
1486
    for (int i=0; i<docImplList.size(); i++)
1487
    {
1488
      // If this String object, this means it is missed data file
1489
      if ((((docImplList.elementAt(i)).getClass()).toString())
1490
                                             .equals("class java.lang.String"))
1491
      {
1492
        
1493
        htmlDoc.append("<a href=\"");
1494
        String dataFileid =(String)docImplList.elementAt(i);
1495
        htmlDoc.append("./data/").append(dataFileid).append("\">");
1496
        htmlDoc.append("Data File: ");
1497
        htmlDoc.append(dataFileid).append("</a><br>");
1498
        htmlDoc.append("<br><hr><br>");
1499
        
1500
      }//if
1501
      else if ((((DocumentImpl)docImplList.elementAt(i)).getDoctype()).
1502
                                                         compareTo("BIN")!=0)
1503
      { //this is an xml file so we can transform it.
1504
        //transform each file individually then concatenate all of the
1505
        //transformations together.
1506

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

    
1585
      if(!hasPermissionToExportPackage(docId, user, groups))
1586
      {
1587

    
1588
        Exception e = new Exception("User " + user + " does not have permission"
1589
                         +" to export the data package " + docIdString);
1590
        throw e;
1591
      }
1592

    
1593
      docImpls=new DocumentImpl(docId);
1594
      //checking if the user has the permission to read the documents
1595
      if (docImpls.hasReadPermission(user,groups,docImpls.getDocID()))
1596
      {
1597
        zOut = new ZipOutputStream(out);
1598
        //if the docImpls is metadata
1599
        if ((docImpls.getDoctype()).compareTo("BIN")!=0)
1600
        {
1601
          //add metadata into zip output stream
1602
          addDocToZipOutputStream(docImpls, zOut, rootName);
1603
        }//if
1604
        else
1605
        {
1606
          //it is data file
1607
          addDataFileToZipOutputStream(docImpls, zOut, rootName);
1608
          htmlDocumentImplList.add(docImpls);
1609
        }//else
1610
      }//if
1611

    
1612
      zOut.finish(); //terminate the zip file
1613
      return zOut;
1614
    }
1615
    // Check the permission of user
1616
    else if(!hasPermissionToExportPackage(docId, user, groups))
1617
    {
1618
      
1619
      Exception e = new Exception("User " + user + " does not have permission"
1620
                       +" to export the data package " + docIdString);
1621
      throw e;
1622
    }
1623
    else //it is a packadge id
1624
    { 
1625
      //store the package id
1626
      packageId=docId;
1627
      //get current version in database
1628
      int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
1629
      //If it is for current version (-1 means user didn't specify revision)
1630
      if ((version ==-1)||version==currentVersion)
1631
      { 
1632
        //get current version number
1633
        version=currentVersion;
1634
        //get package zip entry name
1635
        //it should be docId.revsion.package
1636
        rootName=packageId+util.getOption("accNumSeparator")+version+
1637
                                  util.getOption("accNumSeparator")+"package";
1638
        //get the whole id list for data packadge
1639
        docIdList=getCurrentDocidListForDataPackage(packageId);
1640
        //get the whole documentImple object
1641
        documentImplList=getCurrentAllDocumentImpl(docIdList);
1642
       
1643
      }//if
1644
      else if (version > currentVersion || version < -1)
1645
      {
1646
        throw new Exception ("The user specified docid: "+docId+"."+version
1647
                                              +" doesn't exist");
1648
      }//else if
1649
      else  //for an old version
1650
      {
1651
       
1652
        rootName=docIdString+util.getOption("accNumSeparator")+"package";
1653
        //get the whole id list for data packadge
1654
        docIdList=getOldVersionDocidListForDataPackage(docIdString);
1655

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

    
1736
      //add html summary file
1737
      addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut, rootName);
1738
      zOut.finish(); //terminate the zip file
1739
      //dbConn.close();
1740
      return zOut;
1741
    }//else
1742
  }//getZippedPackage()
1743
  
1744
   private class ReturnFieldValue
1745
  {
1746
    private String docid          = null; //return field value for this docid
1747
    private String fieldValue     = null;
1748
    private String xmlFieldValue  = null; //return field value in xml format
1749

    
1750
    
1751
    public void setDocid(String myDocid)
1752
    {
1753
      docid = myDocid;
1754
    }
1755
    
1756
    public String getDocid()
1757
    {
1758
      return docid;
1759
    }
1760
    
1761
    public void setFieldValue(String myValue)
1762
    {
1763
      fieldValue = myValue;
1764
    }
1765
    
1766
    public String getFieldValue()
1767
    {
1768
      return fieldValue;
1769
    }
1770
    
1771
    public void setXMLFieldValue(String xml)
1772
    {
1773
      xmlFieldValue = xml;
1774
    }
1775
    
1776
    public String getXMLFieldValue()
1777
    {
1778
      return xmlFieldValue;
1779
    }
1780
    
1781
   
1782
  }
1783
   
1784
}
(18-18/47)