Project

General

Profile

1 155 jones
/**
2 203 jones
 *  '$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 349 jones
 *    Release: @release@
12 155 jones
 *
13 203 jones
 *   '$Author$'
14
 *     '$Date$'
15
 * '$Revision$'
16 669 jones
 *
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 155 jones
 */
31
32 607 bojilova
package edu.ucsb.nceas.metacat;
33 155 jones
34 940 tao
import edu.ucsb.nceas.morpho.datapackage.*;
35 155 jones
import java.io.*;
36 401 berkley
import java.util.Vector;
37 940 tao
import java.util.zip.*;
38 155 jones
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 706 bojilova
import java.io.File;
45
import java.io.FileWriter;
46
import java.io.BufferedWriter;
47 940 tao
import javax.servlet.ServletOutputStream;
48 155 jones
49
/**
50 172 jones
 * 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 155 jones
 */
56
public class DBQuery {
57
58 441 bojilova
  static final int ALL = 1;
59
  static final int WRITE = 2;
60
  static final int READ = 4;
61 940 tao
62 1217 tao
  //private Connection  conn = null;
63 535 jones
  private String  parserName = null;
64 465 berkley
  private MetaCatUtil util = new MetaCatUtil();
65 155 jones
  /**
66
   * the main routine used to test the DBQuery utility.
67 184 jones
   * <p>
68
   * Usage: java DBQuery <xmlfile>
69 155 jones
   *
70 170 jones
   * @param xmlfile the filename of the xml file containing the query
71 155 jones
   */
72
  static public void main(String[] args) {
73
74 184 jones
     if (args.length < 1)
75 155 jones
     {
76
        System.err.println("Wrong number of arguments!!!");
77 706 bojilova
        System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
78 155 jones
        return;
79
     } else {
80
        try {
81
82 706 bojilova
          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 155 jones
          // Open a connection to the database
99 184 jones
          MetaCatUtil   util = new MetaCatUtil();
100 1217 tao
          //Connection dbconn = util.openDBConnection();
101 706 bojilova
102 705 berkley
          double connTime = System.currentTimeMillis();
103 706 bojilova
104 170 jones
          // Execute the query
105 1217 tao
          DBQuery queryobj = new DBQuery(util.getOption("saxparser"));
106 170 jones
          FileReader xml = new FileReader(new File(xmlfile));
107 155 jones
          Hashtable nodelist = null;
108 706 bojilova
          nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
109
110 172 jones
          // Print the reulting document listing
111 155 jones
          StringBuffer result = new StringBuffer();
112
          String document = null;
113 170 jones
          String docid = null;
114 155 jones
          result.append("<?xml version=\"1.0\"?>\n");
115 296 higgins
          result.append("<resultset>\n");
116 940 tao
117 743 jones
          if (!showRuntime)
118 710 berkley
          {
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 155 jones
          }
129 706 bojilova
          // Time the request if asked for
130
          double stopTime = System.currentTimeMillis();
131 705 berkley
          double dbOpenTime = (connTime - startTime)/1000;
132 706 bojilova
          double readTime = (stopTime - connTime)/1000;
133 705 berkley
          double executionTime = (stopTime - startTime)/1000;
134 706 bojilova
          if (showRuntime) {
135 710 berkley
            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 706 bojilova
          }
141
          //System.out.println(result);
142
          //write into a file "result.txt"
143 743 jones
          if (!showRuntime)
144 710 berkley
          {
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 675 berkley
          System.err.println("Error in DBQuery.main");
157 155 jones
          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 172 jones
   * @param parserName the fully qualified name of a Java class implementing
171 185 jones
   *                   the org.xml.sax.XMLReader interface
172 155 jones
   */
173 1217 tao
  public DBQuery(String parserName )
174 155 jones
                  throws IOException,
175
                         SQLException,
176 172 jones
                         ClassNotFoundException {
177 1217 tao
    //this.conn = conn;
178 172 jones
    this.parserName = parserName;
179 155 jones
  }
180
181 745 jones
  /**
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 802 bojilova
  public Hashtable findDocuments(Reader xmlquery, String user, String[] groups)
189 465 berkley
  {
190 802 bojilova
    return findDocuments(xmlquery, user, groups, true);
191 465 berkley
  }
192 706 bojilova
193 155 jones
  /**
194
   * routine to search the elements and attributes looking to match query
195
   *
196 178 jones
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
197 465 berkley
   * @param user the username of the user
198
   * @param group the group of the user
199 745 jones
   * @param useXMLIndex flag whether to search using the path index
200 155 jones
   */
201 802 bojilova
  public Hashtable findDocuments(Reader xmlquery, String user, String[] groups,
202 745 jones
                                 boolean useXMLIndex)
203 453 berkley
  {
204 535 jones
      Hashtable   docListResult = new Hashtable();
205 667 berkley
      PreparedStatement pstmt = null;
206 170 jones
      String docid = null;
207 155 jones
      String docname = null;
208
      String doctype = null;
209 401 berkley
      String createDate = null;
210
      String updateDate = null;
211
      String fieldname = null;
212
      String fielddata = null;
213 453 berkley
      String relation = null;
214 1217 tao
      //Connection dbconn = null;
215
      //Connection dbconn2 = null;
216 624 berkley
      int rev = 0;
217 1217 tao
      StringBuffer document = null;
218
      DBConnection dbconn = null;
219
      int serialNumber = -1;
220 465 berkley
221 155 jones
      try {
222 1300 tao
223 1217 tao
224
        dbconn=DBConnectionPool.getDBConnection("DBQuery.findDocuments");
225
        serialNumber=dbconn.getCheckOutSerialNumber();
226 1300 tao
227 172 jones
        // Get the XML query and covert it into a SQL statment
228 178 jones
        QuerySpecification qspec = new QuerySpecification(xmlquery,
229 535 jones
                                   parserName,
230 624 berkley
                                   util.getOption("accNumSeparator"));
231 1303 tao
232 1297 tao
        String query = qspec.printSQL(useXMLIndex);
233 1303 tao
        String ownerQuery = getOwnerQuery(user);
234 1297 tao
        MetaCatUtil.debugMessage("query: "+query, 30);
235 1303 tao
        //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 1300 tao
249 1297 tao
        double startTime = System.currentTimeMillis()/1000;
250
        pstmt = dbconn.prepareStatement(query);
251 790 bojilova
252 172 jones
        // Execute the SQL query using the JDBC connection
253 155 jones
        pstmt.execute();
254
        ResultSet rs = pstmt.getResultSet();
255 1297 tao
        double queryExecuteTime =System.currentTimeMillis()/1000;
256
        MetaCatUtil.debugMessage("Time for execute query: "+
257
                                            (queryExecuteTime -startTime), 30);
258 155 jones
        boolean tableHasRows = rs.next();
259 667 berkley
        while (tableHasRows)
260
        {
261 768 bojilova
          docid = rs.getString(1).trim();
262 1300 tao
          //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 612 bojilova
            // Advance to the next record in the cursor
269 1300 tao
            //tableHasRows = rs.next();
270
            //continue;
271
          //}
272 1297 tao
273 155 jones
          docname = rs.getString(2);
274
          doctype = rs.getString(3);
275 692 bojilova
          createDate = rs.getString(4);
276
          updateDate = rs.getString(5);
277
          rev = rs.getInt(6);
278 743 jones
279 745 jones
          // 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 1349 tao
          if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
283
              && !qspec.isPercentageSearch())
284 743 jones
          {
285 1349 tao
            MetaCatUtil.debugMessage("Back tracing now...", 20);
286 743 jones
            String sep = util.getOption("accNumSeparator");
287 465 berkley
            StringBuffer btBuf = new StringBuffer();
288 743 jones
            btBuf.append("select docid from xml_relation where ");
289
290 465 berkley
            //build the doctype list for the backtracking sql statement
291 743 jones
            btBuf.append("packagetype in (");
292 465 berkley
            for(int i=0; i<returndocVec.size(); i++)
293
            {
294
              btBuf.append("'").append((String)returndocVec.get(i)).append("'");
295 743 jones
              if (i != (returndocVec.size() - 1))
296 465 berkley
              {
297
                btBuf.append(", ");
298 475 berkley
              }
299 465 berkley
            }
300
            btBuf.append(") ");
301 743 jones
302
            btBuf.append("and (subject like '");
303 1347 tao
            btBuf.append(docid).append("'");
304 743 jones
            btBuf.append("or object like '");
305 1347 tao
            btBuf.append(docid).append("')");
306 667 berkley
307 743 jones
            PreparedStatement npstmt = dbconn.
308
                                       prepareStatement(btBuf.toString());
309 1217 tao
            //should incease usage count
310
            dbconn.increaseUsageCount(1);
311 671 berkley
            npstmt.execute();
312
            ResultSet btrs = npstmt.getResultSet();
313 465 berkley
            boolean hasBtRows = btrs.next();
314 743 jones
            while (hasBtRows)
315 465 berkley
            { //there was a backtrackable document found
316
              DocumentImpl xmldoc = null;
317 743 jones
              String packageDocid = btrs.getString(1);
318 1096 tao
              util.debugMessage("Getting document for docid: "+packageDocid,40);
319 465 berkley
              try
320
              {
321 800 jones
                //  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 1217 tao
                xmldoc = new DocumentImpl(packageDocid, false);
326 800 jones
                if (xmldoc == null) {
327 1096 tao
                  util.debugMessage("Document was null for: "+packageDocid, 50);
328 800 jones
                }
329 465 berkley
              }
330
              catch(Exception e)
331
              {
332 675 berkley
                System.out.println("Error getting document in " +
333
                                   "DBQuery.findDocuments: " + e.getMessage());
334 465 berkley
              }
335
336 800 jones
              String docid_org = xmldoc.getDocID();
337
              if (docid_org == null) {
338 1096 tao
                util.debugMessage("Docid_org was null.", 40);
339 800 jones
              }
340
              docid   = docid_org.trim();
341 465 berkley
              docname = xmldoc.getDocname();
342
              doctype = xmldoc.getDoctype();
343
              createDate = xmldoc.getCreateDate();
344
              updateDate = xmldoc.getUpdateDate();
345 743 jones
              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 465 berkley
            }
371 671 berkley
            npstmt.close();
372 465 berkley
            btrs.close();
373 1349 tao
          }
374
          else if (returndocVec.size() != 0 && returndocVec.contains(doctype))
375
          {
376 465 berkley
377 743 jones
            document = new StringBuffer();
378
379 624 berkley
            String completeDocid = docid + util.getOption("accNumSeparator");
380
            completeDocid += rev;
381
            document.append("<docid>").append(completeDocid).append("</docid>");
382 465 berkley
            if (docname != null) {
383
              document.append("<docname>" + docname + "</docname>");
384
            }
385
            if (doctype != null) {
386
              document.append("<doctype>" + doctype + "</doctype>");
387
            }
388 743 jones
            if (createDate != null) {
389 465 berkley
              document.append("<createdate>" + createDate + "</createdate>");
390
            }
391 743 jones
            if (updateDate != null) {
392 465 berkley
              document.append("<updatedate>" + updateDate + "</updatedate>");
393
            }
394
            // Store the document id and the root node id
395
            docListResult.put(docid,(String)document.toString());
396 743 jones
397 155 jones
          }
398
399
          // Advance to the next record in the cursor
400
          tableHasRows = rs.next();
401
        }
402 667 berkley
        rs.close();
403 818 berkley
        pstmt.close();
404 1297 tao
        double docListTime =System.currentTimeMillis()/1000;
405
        MetaCatUtil.debugMessage("prepare docid list time: "
406
                                          +(docListTime-queryExecuteTime), 30);
407 401 berkley
408 743 jones
        if (qspec.containsExtendedSQL())
409 401 berkley
        {
410
          Vector extendedFields = new Vector(qspec.getReturnFieldList());
411
          Vector results = new Vector();
412 465 berkley
          Enumeration keylist = docListResult.keys();
413
          StringBuffer doclist = new StringBuffer();
414 1361 tao
          Hashtable parentidList = new Hashtable();
415
          Hashtable returnFieldValue = new Hashtable();
416 465 berkley
          while(keylist.hasMoreElements())
417
          {
418
            doclist.append("'");
419
            doclist.append((String)keylist.nextElement());
420
            doclist.append("',");
421
          }
422 834 jones
          if (doclist.length() > 0) {
423
            doclist.deleteCharAt(doclist.length()-1); //remove the last comma
424
            //pstmt.close();
425 1297 tao
            double extendedQueryStart = System.currentTimeMillis()/1000;
426
            String extendedQuery = qspec.printExtendedSQL(doclist.toString());
427 1353 tao
            MetaCatUtil.debugMessage("Extended query: "+ extendedQuery, 30);
428 1297 tao
            pstmt = dbconn.prepareStatement(extendedQuery);
429 1217 tao
            //increase dbconnection usage count
430
            dbconn.increaseUsageCount(1);
431 834 jones
            pstmt.execute();
432
            rs = pstmt.getResultSet();
433 1297 tao
            double extendedQueryEnd = System.currentTimeMillis()/1000;
434
            MetaCatUtil.debugMessage("Time for execute extended query: "
435
                                    +(extendedQueryEnd-extendedQueryStart), 30);
436 401 berkley
            tableHasRows = rs.next();
437 834 jones
            while(tableHasRows)
438 401 berkley
            {
439 1361 tao
              ReturnFieldValue returnValue = new ReturnFieldValue();
440 834 jones
              docid = rs.getString(1).trim();
441
              fieldname = rs.getString(2);
442
              fielddata = rs.getString(3);
443 1361 tao
              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 1353 tao
485 1361 tao
            // 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 834 jones
              if (docListResult.containsKey(docid))
493
              {
494 1361 tao
                  String removedelement = (String)docListResult.remove(docid);
495
                  docListResult.put(docid, removedelement +
496
                                    object.getXMLFieldValue());
497 834 jones
              }
498
              else
499
              {
500 1361 tao
                  docListResult.put(docid, object.getXMLFieldValue());
501 834 jones
              }
502 1361 tao
            }//while
503 1297 tao
            double docListResultEnd = System.currentTimeMillis()/1000;
504
            MetaCatUtil.debugMessage("Time for prepare doclistresult after"+
505
                                      " execute extended query: "
506
                                    +(docListResultEnd-extendedQueryEnd), 30);
507 1353 tao
508 1361 tao
509 1353 tao
            // 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 818 berkley
516 1353 tao
517 465 berkley
        //this loop adds the relation data to the resultdoc
518
        //this code might be able to be added to the backtracking code above
519 1297 tao
        double startRelation = System.currentTimeMillis()/1000;
520 465 berkley
        Enumeration docidkeys = docListResult.keys();
521
        while(docidkeys.hasMoreElements())
522 453 berkley
        {
523 602 berkley
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
524
          String connstring = "%docid=";
525 465 berkley
          String docidkey = (String)docidkeys.nextElement();
526 743 jones
          pstmt = dbconn.prepareStatement(qspec.printRelationSQL(docidkey));
527 465 berkley
          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 489 berkley
            String subDT = rs.getString(4);
536
            String objDT = rs.getString(5);
537
538 894 berkley
            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 940 tao
            document.append("<relationship>").
547
                                          append(MetaCatUtil.normalize(rel));
548 894 berkley
            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 465 berkley
            tableHasRows = rs.next();
561 453 berkley
          }
562 667 berkley
          rs.close();
563
          pstmt.close();
564 453 berkley
        }
565 1297 tao
        double endRelation = System.currentTimeMillis()/1000;
566
        MetaCatUtil.debugMessage("Time for adding relation to docListResult: "+
567
                                (endRelation-startRelation), 30);
568 667 berkley
569 155 jones
      } catch (SQLException e) {
570 667 berkley
        System.err.println("SQL Error in DBQuery.findDocuments: " +
571
                           e.getMessage());
572 170 jones
      } catch (IOException ioe) {
573 675 berkley
        System.err.println("IO error in DBQuery.findDocuments:");
574 170 jones
        System.err.println(ioe.getMessage());
575 667 berkley
      } catch (Exception ee) {
576 800 jones
        System.err.println("Exception in DBQuery.findDocuments: " +
577 667 berkley
                           ee.getMessage());
578 800 jones
        ee.printStackTrace(System.err);
579 155 jones
      }
580 1217 tao
      finally
581
      {
582 667 berkley
        try
583
        {
584 1217 tao
          pstmt.close();
585
        }//try
586
        catch (SQLException sqlE)
587 667 berkley
        {
588 1217 tao
          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 423 berkley
    //System.out.println("docListResult: ");
597
    //System.out.println(docListResult.toString());
598 155 jones
    return docListResult;
599
  }
600 342 berkley
601 1303 tao
  /*
602 1353 tao
   * 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 1303 tao
   * 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 342 berkley
  /**
713 436 berkley
   * 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 1217 tao
  public static Object[] getNodeContent(String nodename, String docid)
720 436 berkley
  {
721 1217 tao
    DBConnection dbconn = null;
722
    int serialNumber = -1;
723 436 berkley
    StringBuffer query = new StringBuffer();
724
    Vector result = new Vector();
725 667 berkley
    PreparedStatement pstmt = null;
726 436 berkley
    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 1217 tao
      dbconn=DBConnectionPool.getDBConnection("DBQuery.getNodeContent");
733
        serialNumber=dbconn.getCheckOutSerialNumber();
734
      pstmt = dbconn.prepareStatement(query.toString());
735 436 berkley
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 1297 tao
        //System.out.println(rs.getString(1));
744 436 berkley
        tableHasRows = rs.next();
745
      }
746
    }
747
    catch (SQLException e)
748
    {
749 675 berkley
      System.err.println("Error in DBQuery.getNodeContent: " + e.getMessage());
750 667 berkley
    } finally {
751
      try
752
      {
753
        pstmt.close();
754
      }
755 1217 tao
      catch(SQLException sqle)
756
      {}
757
      finally
758
      {
759
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
760
      }
761
762 667 berkley
    }
763 436 berkley
    return result.toArray();
764
  }
765
766
  /**
767 342 berkley
   * 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 743 jones
   * @param params The list of parameters that should be included in the query
772 342 berkley
   */
773 372 berkley
  public static String createSQuery(Hashtable params)
774 350 berkley
  {
775
    StringBuffer query = new StringBuffer();
776 342 berkley
    Enumeration elements;
777
    Enumeration keys;
778 743 jones
    String filterDoctype = null;
779 372 berkley
    String casesensitive = null;
780
    String searchmode = null;
781 342 berkley
    Object nextkey;
782
    Object nextelement;
783 350 berkley
    //add the xml headers
784
    query.append("<?xml version=\"1.0\"?>\n");
785 743 jones
    query.append("<pathquery version=\"1.0\">\n");
786
787
    if (params.containsKey("meta_file_id"))
788 342 berkley
    {
789 743 jones
      query.append("<meta_file_id>");
790 342 berkley
      query.append( ((String[])params.get("meta_file_id"))[0]);
791 535 jones
      query.append("</meta_file_id>");
792 342 berkley
    }
793 350 berkley
794 743 jones
    if (params.containsKey("returndoctype"))
795 372 berkley
    {
796 744 jones
      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 372 berkley
    }
810 744 jones
811 743 jones
    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 372 berkley
821 743 jones
    if (params.containsKey("returnfield"))
822 401 berkley
    {
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 743 jones
    if (params.containsKey("owner"))
832 535 jones
    {
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 743 jones
    if (params.containsKey("site"))
842 535 jones
    {
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 350 berkley
    //allows the dynamic switching of boolean operators
852 743 jones
    if (params.containsKey("operator"))
853 350 berkley
    {
854
      query.append("<querygroup operator=\"" +
855 535 jones
                ((String[])params.get("operator"))[0] + "\">");
856 350 berkley
    }
857
    else
858
    { //the default operator is UNION
859
      query.append("<querygroup operator=\"UNION\">");
860
    }
861 535 jones
862 743 jones
    if (params.containsKey("casesensitive"))
863 372 berkley
    {
864
      casesensitive = ((String[])params.get("casesensitive"))[0];
865
    }
866
    else
867
    {
868
      casesensitive = "false";
869
    }
870
871 743 jones
    if (params.containsKey("searchmode"))
872 372 berkley
    {
873
      searchmode = ((String[])params.get("searchmode"))[0];
874
    }
875
    else
876
    {
877
      searchmode = "contains";
878
    }
879 535 jones
880 342 berkley
    //anyfield is a special case because it does a
881
    //free text search.  It does not have a <pathexpr>
882 350 berkley
    //tag.  This allows for a free text search within the structured
883
    //query.  This is useful if the INTERSECT operator is used.
884 743 jones
    if (params.containsKey("anyfield"))
885 342 berkley
    {
886 372 berkley
       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 350 berkley
       {
890 743 jones
         if (!anyfield[i].equals(""))
891 372 berkley
         {
892
           query.append("<queryterm casesensitive=\"" + casesensitive +
893
                        "\" " + "searchmode=\"" + searchmode + "\"><value>" +
894 535 jones
                        anyfield[i] +
895
                        "</value></queryterm>");
896 372 berkley
         }
897 350 berkley
       }
898 342 berkley
    }
899 535 jones
900 342 berkley
    //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 535 jones
      nextelement = elements.nextElement();
909 372 berkley
910 535 jones
      //make sure we aren't querying for any of these
911
      //parameters since the are already in the query
912 342 berkley
      //in one form or another.
913 743 jones
      if (!nextkey.toString().equals("returndoctype") &&
914
         !nextkey.toString().equals("filterdoctype")  &&
915 535 jones
         !nextkey.toString().equals("action")  &&
916
         !nextkey.toString().equals("qformat") &&
917
         !nextkey.toString().equals("anyfield") &&
918 401 berkley
         !nextkey.toString().equals("returnfield") &&
919 535 jones
         !nextkey.toString().equals("owner") &&
920
         !nextkey.toString().equals("site") &&
921
         !nextkey.toString().equals("operator") )
922
      {
923 372 berkley
        //allow for more than value per field name
924
        for(int i=0; i<((String[])nextelement).length; i++)
925
        {
926 743 jones
          if (!((String[])nextelement)[i].equals(""))
927 372 berkley
          {
928
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " +
929 535 jones
                         "searchmode=\"" + searchmode + "\">" +
930
                         "<value>" +
931 372 berkley
                         //add the query value
932 535 jones
                         ((String[])nextelement)[i] +
933
                         "</value><pathexpr>" +
934
                         //add the path to query by
935 372 berkley
                         nextkey.toString() +
936
                         "</pathexpr></queryterm>");
937
          }
938
        }
939 535 jones
      }
940 342 berkley
    }
941
    query.append("</querygroup></pathquery>");
942 350 berkley
    //append on the end of the xml and return the result as a string
943 342 berkley
    return query.toString();
944
  }
945
946 181 jones
  /**
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 350 berkley
     //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 743 jones
     if (!value.equals(""))
970 350 berkley
     {
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 181 jones
     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 441 bojilova
994 570 bojilova
  /**
995
    * Check for "READ" permission on @docid for @user and/or @group
996
    * from DB connection
997
    */
998 1217 tao
  private boolean hasPermission (String user,
999 802 bojilova
                                  String[] groups, String docid )
1000 957 tao
                  throws SQLException, Exception
1001 570 bojilova
  {
1002 802 bojilova
    // Check for READ permission on @docid for @user and/or @groups
1003 1427 tao
   PermissionController controller = new PermissionController(docid);
1004
   return controller.hasPermission(user,groups,
1005
                                 AccessControlInterface.READSTRING);
1006 441 bojilova
  }
1007 940 tao
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 1217 tao
    DBConnection dbConn = null;
1015
    int serialNumber = -1;
1016 940 tao
    Vector docIdList=new Vector();//return value
1017 1217 tao
    PreparedStatement pStmt = null;
1018 940 tao
    ResultSet rs=null;
1019
    String docIdInSubjectField=null;
1020
    String docIdInObjectField=null;
1021 1292 tao
1022
    // Check the parameter
1023
    if (dataPackageDocid == null || dataPackageDocid.equals(""))
1024
    {
1025
      return docIdList;
1026
    }//if
1027
1028 940 tao
    //the query stirng
1029
    String query="SELECT subject, object from xml_relation where docId = ?";
1030
    try
1031
    {
1032 1217 tao
      dbConn=DBConnectionPool.
1033
                  getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1034
      serialNumber=dbConn.getCheckOutSerialNumber();
1035
      pStmt=dbConn.prepareStatement(query);
1036 940 tao
      //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 1292 tao
      MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1070 1096 tao
                            +e.getMessage(), 30);
1071 940 tao
    }//catch
1072 1217 tao
    finally
1073
    {
1074
      try
1075
      {
1076
        pStmt.close();
1077
      }//try
1078
      catch (SQLException ee)
1079
      {
1080 1292 tao
        MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1081 1217 tao
                            +ee.getMessage(), 30);
1082
      }//catch
1083
      finally
1084
      {
1085
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1086
      }//fianlly
1087
    }//finally
1088 940 tao
    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 441 bojilova
1098 940 tao
    Vector docIdList=new Vector();//return value
1099
    Vector tripleList=null;
1100
    String xml=null;
1101 1292 tao
1102
     // Check the parameter
1103
    if (dataPackageDocid == null || dataPackageDocid.equals(""))
1104
    {
1105
      return docIdList;
1106
    }//if
1107
1108
    try
1109
    {
1110 1217 tao
      //initial a documentImpl object
1111
      DocumentImpl packageDocument =
1112
                  new DocumentImpl(dataPackageDocid);
1113
      //transfer to documentImpl object to string
1114
      xml=packageDocument.toString();
1115 940 tao
1116 1217 tao
      //create a tripcollection object
1117
      TripleCollection tripleForPackage = new
1118 940 tao
                                     TripleCollection(new StringReader(xml));
1119 1217 tao
      //get the vetor of triples
1120
      tripleList=tripleForPackage.getCollection();
1121 940 tao
1122 1217 tao
      for (int i= 0; i<tripleList.size(); i++)
1123 940 tao
      {
1124 1217 tao
        //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 1292 tao
    }//try
1137
    catch (Exception e)
1138
    {
1139
      MetaCatUtil.debugMessage("Error in getOldVersionAllDocumentImpl: "
1140
                            +e.getMessage(), 30);
1141
    }//catch
1142 1217 tao
1143 1292 tao
    // return result
1144 940 tao
    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 1217 tao
    PreparedStatement pStmt = null;
1159 940 tao
    ResultSet rs=null;
1160
    String query="SELECT docId from xml_relation where docId = ?";
1161 1217 tao
    DBConnection dbConn = null;
1162
    int serialNumber = -1;
1163 940 tao
    try
1164
    {
1165 1217 tao
      dbConn=DBConnectionPool.
1166
                  getDBConnection("DBQuery.isDataPackageId");
1167
      serialNumber=dbConn.getCheckOutSerialNumber();
1168
      pStmt=dbConn.prepareStatement(query);
1169 940 tao
      //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 1217 tao
      util.debugMessage("Error in isDataPackageId: "
1184 1096 tao
                            +e.getMessage(), 30);
1185 940 tao
    }
1186 1217 tao
    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 940 tao
    return result;
1203
  }//isDataPackageId()
1204
1205
  /**
1206 945 tao
   * 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 1217 tao
   private boolean hasPermissionToExportPackage(String docId,
1213 945 tao
                                        String user, String[] groups)
1214
                   throws Exception
1215
   {
1216 1217 tao
     //DocumentImpl doc=new DocumentImpl(conn,docId);
1217
     return DocumentImpl.hasReadPermission(user, groups,docId);
1218 945 tao
   }
1219
1220
  /**
1221 940 tao
   *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 1292 tao
                                                throws SQLException
1227 940 tao
  {
1228
    int rev=-5;
1229 1217 tao
    PreparedStatement pStmt = null;
1230 940 tao
    ResultSet rs=null;
1231
    String query="SELECT rev from xml_documents where docId = ?";
1232 1217 tao
    DBConnection dbConn=null;
1233
    int serialNumber = -1;
1234 940 tao
    try
1235
    {
1236 1217 tao
      dbConn=DBConnectionPool.
1237
                  getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1238
      serialNumber=dbConn.getCheckOutSerialNumber();
1239
      pStmt=dbConn.prepareStatement(query);
1240 940 tao
      //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 1292 tao
1255 940 tao
    }//try
1256
    catch (SQLException e)
1257
    {
1258 1292 tao
      MetaCatUtil.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
1259 1096 tao
                            +e.getMessage(), 30);
1260 1292 tao
      throw e;
1261 1217 tao
    }//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 940 tao
    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 1292 tao
   * 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 940 tao
   */
1314
1315
  private Vector getCurrentAllDocumentImpl( Vector docIdList)
1316
                              throws McdbException,Exception
1317
  {
1318 1217 tao
    //Connection dbConn=null;
1319 940 tao
    Vector documentImplList=new Vector();
1320
    int rev=0;
1321
1322 1292 tao
    // Check the parameter
1323
    if (docIdList.isEmpty())
1324 940 tao
    {
1325 1292 tao
      return documentImplList;
1326
    }//if
1327
1328 940 tao
    //for every docid in vector
1329
    for (int i=0;i<docIdList.size();i++)
1330
    {
1331 1292 tao
      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 948 tao
1346 1292 tao
        String docidPlusVersion=((String)docIdList.elementAt(i))
1347 948 tao
                        +util.getOption("accNumSeparator")+rev;
1348 1292 tao
1349
1350
        //create new documentImpl object
1351
        DocumentImpl documentImplObject =
1352 1217 tao
                                    new DocumentImpl(docidPlusVersion);
1353 1292 tao
       //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 940 tao
    }//for
1364
    return documentImplList;
1365
  }
1366
1367
  /**
1368 1292 tao
   * 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 940 tao
   */
1374
  private Vector getOldVersionAllDocumentImpl( Vector docIdList)
1375
  {
1376 1217 tao
    //Connection dbConn=null;
1377 940 tao
    Vector documentImplList=new Vector();
1378
    String siteCode=null;
1379
    String uniqueId=null;
1380
    int rev=0;
1381
1382 1292 tao
    // Check the parameter
1383
    if (docIdList.isEmpty())
1384 940 tao
    {
1385 1292 tao
      return documentImplList;
1386
    }//if
1387
1388 940 tao
    //for every docid in vector
1389
    for (int i=0;i<docIdList.size();i++)
1390
    {
1391
1392 948 tao
        String docidPlusVersion=(String)(docIdList.elementAt(i));
1393 1292 tao
1394
        try
1395
        {
1396
          //create new documentImpl object
1397
          DocumentImpl documentImplObject =
1398 1217 tao
                                    new DocumentImpl(docidPlusVersion);
1399 1292 tao
          //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 948 tao
1421 940 tao
    }//for
1422
    return documentImplList;
1423 1292 tao
  }//getOldVersionAllDocumentImple
1424
1425 940 tao
  /**
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 963 berkley
    zEntry = new ZipEntry(packageZipEntry+"/data/"+docImpl.getDocID());
1446 940 tao
    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 1096 tao
      util.debugMessage("There is an exception: "+ioe.getMessage(), 30);
1463 940 tao
    }//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 1292 tao
1482 940 tao
    //create a DBTransform ojbect
1483 1217 tao
    xmlToHtml = new DBTransform();
1484 940 tao
    //head of html
1485
    htmlDoc.append("<html><head></head><body>");
1486
    for (int i=0; i<docImplList.size(); i++)
1487
    {
1488 1292 tao
      // 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 940 tao
                                                         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 1217 tao
    //dbConn.close();
1539 940 tao
1540
  }//addHtmlSummaryToZipOutputStream
1541
1542 945 tao
1543
1544 940 tao
  /**
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 1292 tao
        ServletOutputStream out, String user, String[] groups, String passWord)
1553 940 tao
                    throws ClassNotFoundException, IOException, SQLException,
1554
                      McdbException, NumberFormatException, Exception
1555
  {
1556
    ZipOutputStream zOut = null;
1557
    String elementDocid=null;
1558
    DocumentImpl docImpls=null;
1559 1217 tao
    //Connection dbConn = null;
1560 940 tao
    Vector docIdList=new Vector();
1561 945 tao
    Vector documentImplList=new Vector();
1562
    Vector htmlDocumentImplList=new Vector();
1563 940 tao
    String packageId=null;
1564
    String rootName="package";//the package zip entry name
1565
1566
    String docId=null;
1567
    int version=-5;
1568 1292 tao
    // Docid without revision
1569 940 tao
    docId=MetaCatUtil.getDocIdFromString(docIdString);
1570 1292 tao
    // revision number
1571 940 tao
    version=MetaCatUtil.getVersionFromString(docIdString);
1572
1573
    //check if the reqused docId is a data package id
1574 1356 tao
    if (!isDataPackageId(docId))
1575 940 tao
    {
1576 1356 tao
1577
      /*Exception e = new Exception("The request the doc id " +docIdString+
1578 940 tao
                                    " is not a data package id");
1579 1356 tao
      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 940 tao
    }
1615 1292 tao
    // Check the permission of user
1616 1217 tao
    else if(!hasPermissionToExportPackage(docId, user, groups))
1617 945 tao
    {
1618 1292 tao
1619 945 tao
      Exception e = new Exception("User " + user + " does not have permission"
1620
                       +" to export the data package " + docIdString);
1621
      throw e;
1622
    }
1623 940 tao
    else //it is a packadge id
1624
    {
1625
      //store the package id
1626
      packageId=docId;
1627 1292 tao
      //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 940 tao
      {
1632
        //get current version number
1633 1292 tao
        version=currentVersion;
1634 940 tao
        //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 1292 tao
      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 940 tao
      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 1292 tao
      // 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 940 tao
1667 1292 tao
1668
       zOut = new ZipOutputStream(out);
1669 940 tao
      //put every element into zip output stream
1670
      for (int i=0; i < documentImplList.size(); i++ )
1671
      {
1672 1292 tao
        // 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 948 tao
            //if the docImpls is metadata
1718 1292 tao
            if ((docImpls.getDoctype()).compareTo("BIN")!=0)
1719
            {
1720 948 tao
              //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 953 tao
1725 1292 tao
            }//if
1726
            else
1727
            {
1728
              //it is data file
1729
              addDataFileToZipOutputStream(docImpls, zOut, rootName);
1730
              htmlDocumentImplList.add(docImpls);
1731
            }//else
1732 948 tao
          }//if
1733 1292 tao
        }//else
1734 940 tao
      }//for
1735
1736
      //add html summary file
1737 945 tao
      addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut, rootName);
1738 940 tao
      zOut.finish(); //terminate the zip file
1739 1217 tao
      //dbConn.close();
1740 940 tao
      return zOut;
1741
    }//else
1742
  }//getZippedPackage()
1743 1361 tao
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 940 tao
1782 1361 tao
  }
1783
1784 155 jones
}