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 1445 tao
          if (doclist.length() > 0)
423
          {
424
            Hashtable controlPairs = new Hashtable();
425
            double extendedQueryStart = System.currentTimeMillis()/1000;
426 834 jones
            doclist.deleteCharAt(doclist.length()-1); //remove the last comma
427 1445 tao
            // check if user has permission to see the return field data
428
            String accessControlSQL = qspec.
429
                        printAccessControlSQLForReturnField(doclist.toString());
430
            pstmt = dbconn.prepareStatement(accessControlSQL);
431
            //increase dbconnection usage count
432
            dbconn.increaseUsageCount(1);
433
            pstmt.execute();
434
            rs = pstmt.getResultSet();
435
            tableHasRows = rs.next();
436
            while(tableHasRows)
437
            {
438
              long startNodeId = rs.getLong(1);
439
              long endNodeId = rs.getLong(2);
440
              controlPairs.put(new Long(startNodeId), new Long(endNodeId));
441
            }
442
443
            double extendedAccessQueryEnd = System.currentTimeMillis()/1000;
444
            MetaCatUtil.debugMessage("Time for execute access extended query: "
445
                              +(extendedAccessQueryEnd-extendedQueryStart), 30);
446
447 1448 tao
            String extendedQuery = qspec.printExtendedSQL(doclist.toString(),
448
                                                          controlPairs);
449 1353 tao
            MetaCatUtil.debugMessage("Extended query: "+ extendedQuery, 30);
450 1297 tao
            pstmt = dbconn.prepareStatement(extendedQuery);
451 1217 tao
            //increase dbconnection usage count
452
            dbconn.increaseUsageCount(1);
453 834 jones
            pstmt.execute();
454
            rs = pstmt.getResultSet();
455 1297 tao
            double extendedQueryEnd = System.currentTimeMillis()/1000;
456
            MetaCatUtil.debugMessage("Time for execute extended query: "
457
                                    +(extendedQueryEnd-extendedQueryStart), 30);
458 401 berkley
            tableHasRows = rs.next();
459 834 jones
            while(tableHasRows)
460 401 berkley
            {
461 1361 tao
              ReturnFieldValue returnValue = new ReturnFieldValue();
462 834 jones
              docid = rs.getString(1).trim();
463
              fieldname = rs.getString(2);
464
              fielddata = rs.getString(3);
465 1361 tao
              String parentId = rs.getString(4);
466
467
              StringBuffer value = new StringBuffer();
468
              if (!parentidList.containsKey(parentId))
469
              {
470
                // don't need to merger nodedata
471
                value.append("<param name=\"");
472
                value.append(fieldname);
473
                value.append("\">");
474
                value.append(fielddata);
475
                value.append("</param>");
476
                //set returnvalue
477
                returnValue.setDocid(docid);
478
                returnValue.setFieldValue(fielddata);
479
                returnValue.setXMLFieldValue(value.toString());
480
                // Store it in hastable
481
                parentidList.put(parentId, returnValue);
482
              }
483
              else
484
              {
485
                // need to merge nodedata if they have same parent id ant
486
                // node type is text
487
                fielddata = (String)((ReturnFieldValue)
488
                       parentidList.get(parentId)).getFieldValue() +  fielddata;
489
                value.append("<param name=\"");
490
                value.append(fieldname);
491
                value.append("\">");
492
                value.append(fielddata);
493
                value.append("</param>");
494
                returnValue.setDocid(docid);
495
                returnValue.setFieldValue(fielddata);
496
                returnValue.setXMLFieldValue(value.toString());
497
                // remove the old return value from paretnidList
498
                parentidList.remove(parentId);
499
                // store the new return value in parentidlit
500
                parentidList.put(parentId, returnValue);
501
              }
502
               tableHasRows = rs.next();
503
            }//while
504
            rs.close();
505
            pstmt.close();
506 1353 tao
507 1361 tao
            // put the merger node data info into doclistReult
508
            Enumeration xmlFieldValue = parentidList.elements();
509
            while( xmlFieldValue.hasMoreElements() )
510
            {
511
              ReturnFieldValue object = (ReturnFieldValue)
512
                                         xmlFieldValue.nextElement();
513
              docid = object.getDocid();
514 834 jones
              if (docListResult.containsKey(docid))
515
              {
516 1361 tao
                  String removedelement = (String)docListResult.remove(docid);
517
                  docListResult.put(docid, removedelement +
518
                                    object.getXMLFieldValue());
519 834 jones
              }
520
              else
521
              {
522 1361 tao
                  docListResult.put(docid, object.getXMLFieldValue());
523 834 jones
              }
524 1361 tao
            }//while
525 1297 tao
            double docListResultEnd = System.currentTimeMillis()/1000;
526
            MetaCatUtil.debugMessage("Time for prepare doclistresult after"+
527
                                      " execute extended query: "
528
                                    +(docListResultEnd-extendedQueryEnd), 30);
529 1353 tao
530 1361 tao
531 1353 tao
            // get attribures return
532
            docListResult = getAttributeValueForReturn
533
                                      (qspec,docListResult, doclist.toString());
534
          }//if doclist lenght is great than zero
535
536
        }//if has extended query
537 818 berkley
538 1353 tao
539 465 berkley
        //this loop adds the relation data to the resultdoc
540
        //this code might be able to be added to the backtracking code above
541 1297 tao
        double startRelation = System.currentTimeMillis()/1000;
542 465 berkley
        Enumeration docidkeys = docListResult.keys();
543
        while(docidkeys.hasMoreElements())
544 453 berkley
        {
545 602 berkley
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
546
          String connstring = "%docid=";
547 465 berkley
          String docidkey = (String)docidkeys.nextElement();
548 743 jones
          pstmt = dbconn.prepareStatement(qspec.printRelationSQL(docidkey));
549 465 berkley
          pstmt.execute();
550
          rs = pstmt.getResultSet();
551
          tableHasRows = rs.next();
552
          while(tableHasRows)
553
          {
554
            String sub = rs.getString(1);
555
            String rel = rs.getString(2);
556
            String obj = rs.getString(3);
557 489 berkley
            String subDT = rs.getString(4);
558
            String objDT = rs.getString(5);
559
560 894 berkley
            document = new StringBuffer();
561
            document.append("<triple>");
562
            document.append("<subject>").append(MetaCatUtil.normalize(sub));
563
            document.append("</subject>");
564
            if ( subDT != null ) {
565
              document.append("<subjectdoctype>").append(subDT);
566
              document.append("</subjectdoctype>");
567
            }
568 940 tao
            document.append("<relationship>").
569
                                          append(MetaCatUtil.normalize(rel));
570 894 berkley
            document.append("</relationship>");
571
            document.append("<object>").append(MetaCatUtil.normalize(obj));
572
            document.append("</object>");
573
            if ( objDT != null ) {
574
              document.append("<objectdoctype>").append(objDT);
575
              document.append("</objectdoctype>");
576
            }
577
            document.append("</triple>");
578
579
            String removedelement = (String)docListResult.remove(docidkey);
580
            docListResult.put(docidkey, removedelement +
581
                              document.toString());
582 465 berkley
            tableHasRows = rs.next();
583 453 berkley
          }
584 667 berkley
          rs.close();
585
          pstmt.close();
586 453 berkley
        }
587 1297 tao
        double endRelation = System.currentTimeMillis()/1000;
588
        MetaCatUtil.debugMessage("Time for adding relation to docListResult: "+
589
                                (endRelation-startRelation), 30);
590 667 berkley
591 155 jones
      } catch (SQLException e) {
592 667 berkley
        System.err.println("SQL Error in DBQuery.findDocuments: " +
593
                           e.getMessage());
594 170 jones
      } catch (IOException ioe) {
595 675 berkley
        System.err.println("IO error in DBQuery.findDocuments:");
596 170 jones
        System.err.println(ioe.getMessage());
597 667 berkley
      } catch (Exception ee) {
598 800 jones
        System.err.println("Exception in DBQuery.findDocuments: " +
599 667 berkley
                           ee.getMessage());
600 800 jones
        ee.printStackTrace(System.err);
601 155 jones
      }
602 1217 tao
      finally
603
      {
604 667 berkley
        try
605
        {
606 1217 tao
          pstmt.close();
607
        }//try
608
        catch (SQLException sqlE)
609 667 berkley
        {
610 1217 tao
          MetaCatUtil.debugMessage("Error in DBQuery.findDocuments: "
611
                                      +sqlE.getMessage(), 30);
612
        }//catch
613
        finally
614
        {
615
          DBConnectionPool.returnDBConnection(dbconn, serialNumber);
616
        }//finally
617
      }//finally
618 423 berkley
    //System.out.println("docListResult: ");
619
    //System.out.println(docListResult.toString());
620 155 jones
    return docListResult;
621
  }
622 342 berkley
623 1303 tao
  /*
624 1353 tao
   * A method to return search result after running a query which return
625
   * field have attribue
626
   */
627
  private Hashtable getAttributeValueForReturn(QuerySpecification squery,
628
                                               Hashtable docInformationList,
629
                                               String docList)
630
  {
631
    StringBuffer XML = null;
632
    String sql = null;
633
    DBConnection dbconn = null;
634
    PreparedStatement pstmt = null;
635
    ResultSet rs = null;
636
    int serialNumber = -1;
637
    boolean tableHasRows =false;
638
639
    //check the parameter
640
    if (squery == null || docList==null || docList.length() <0)
641
    {
642
      return docInformationList;
643
    }
644
645
    // if has attribute as return field
646
    if (squery.containAttributeReturnField())
647
    {
648
      sql = squery.printAttributeQuery(docList);
649
      try
650
      {
651
        dbconn=DBConnectionPool.getDBConnection("DBQuery.getAttributeValue");
652
        serialNumber=dbconn.getCheckOutSerialNumber();
653
        pstmt = dbconn.prepareStatement(sql);
654
        pstmt.execute();
655
        rs = pstmt.getResultSet();
656
        tableHasRows = rs.next();
657
        while(tableHasRows)
658
        {
659
          String docid = rs.getString(1).trim();
660
          String fieldname = rs.getString(2);
661
          String fielddata = rs.getString(3);
662
          String attirbuteName = rs.getString(4);
663
          XML = new StringBuffer();
664
665
          XML.append("<param name=\"");
666
          XML.append(fieldname);
667
          XML.append(QuerySpecification.ATTRIBUTESYMBOL);
668
          XML.append(attirbuteName);
669
          XML.append("\">");
670
          XML.append(fielddata);
671
          XML.append("</param>");
672
          tableHasRows = rs.next();
673
674
          if (docInformationList.containsKey(docid))
675
          {
676
            String removedelement = (String)docInformationList.remove(docid);
677
            docInformationList.put(docid, removedelement + XML.toString());
678
          }
679
          else
680
          {
681
            docInformationList.put(docid, XML.toString());
682
          }
683
        }//while
684
        rs.close();
685
        pstmt.close();
686
      }
687
      catch(Exception se)
688
      {
689
        MetaCatUtil.debugMessage("Error in DBQuery.getAttributeValue1: "
690
                                      +se.getMessage(), 30);
691
      }
692
      finally
693
      {
694
        try
695
        {
696
          pstmt.close();
697
        }//try
698
        catch (SQLException sqlE)
699
        {
700
          MetaCatUtil.debugMessage("Error in DBQuery.getAttributeValue2: "
701
                                      +sqlE.getMessage(), 30);
702
        }//catch
703
        finally
704
        {
705
          DBConnectionPool.returnDBConnection(dbconn, serialNumber);
706
        }//finally
707
      }//finally
708
    }//if
709
    return docInformationList;
710
711
  }
712
713
714
  /*
715 1303 tao
   * A method to create a query to get owner's docid list
716
   */
717
  private String getOwnerQuery(String owner)
718
  {
719
    StringBuffer self = new StringBuffer();
720
721
    self.append("SELECT docid,docname,doctype,");
722
    self.append("date_created, date_updated, rev ");
723
    self.append("FROM xml_documents WHERE docid IN (");
724
    self.append("(");
725
    self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
726
    self.append("nodedata LIKE '%%%' ");
727
    self.append(") \n");
728
    self.append(") ");
729
    self.append(" AND (");
730
    self.append(" user_owner = '" + owner + "'");
731
    self.append(") ");
732
    return self.toString();
733
  }
734 342 berkley
  /**
735 436 berkley
   * returns a string array of the contents of a particular node.
736
   * If the node appears more than once, the contents are returned
737
   * in the order in which they appearred in the document.
738
   * @param nodename the name or path of the particular node.
739
   * @param docid the docid of the document you want the node from.
740
   */
741 1217 tao
  public static Object[] getNodeContent(String nodename, String docid)
742 436 berkley
  {
743 1217 tao
    DBConnection dbconn = null;
744
    int serialNumber = -1;
745 436 berkley
    StringBuffer query = new StringBuffer();
746
    Vector result = new Vector();
747 667 berkley
    PreparedStatement pstmt = null;
748 436 berkley
    query.append("select nodedata from xml_nodes where parentnodeid in ");
749
    query.append("(select nodeid from xml_index where path like '");
750
    query.append(nodename);
751
    query.append("' and docid like '").append(docid).append("')");
752
    try
753
    {
754 1217 tao
      dbconn=DBConnectionPool.getDBConnection("DBQuery.getNodeContent");
755
        serialNumber=dbconn.getCheckOutSerialNumber();
756
      pstmt = dbconn.prepareStatement(query.toString());
757 436 berkley
758
      // Execute the SQL query using the JDBC connection
759
      pstmt.execute();
760
      ResultSet rs = pstmt.getResultSet();
761
      boolean tableHasRows = rs.next();
762
      while (tableHasRows)
763
      {
764
        result.add(rs.getString(1));
765 1297 tao
        //System.out.println(rs.getString(1));
766 436 berkley
        tableHasRows = rs.next();
767
      }
768
    }
769
    catch (SQLException e)
770
    {
771 675 berkley
      System.err.println("Error in DBQuery.getNodeContent: " + e.getMessage());
772 667 berkley
    } finally {
773
      try
774
      {
775
        pstmt.close();
776
      }
777 1217 tao
      catch(SQLException sqle)
778
      {}
779
      finally
780
      {
781
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
782
      }
783
784 667 berkley
    }
785 436 berkley
    return result.toArray();
786
  }
787
788
  /**
789 342 berkley
   * format a structured query as an XML document that conforms
790
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
791
   * structured query engine
792
   *
793 743 jones
   * @param params The list of parameters that should be included in the query
794 342 berkley
   */
795 372 berkley
  public static String createSQuery(Hashtable params)
796 350 berkley
  {
797
    StringBuffer query = new StringBuffer();
798 342 berkley
    Enumeration elements;
799
    Enumeration keys;
800 743 jones
    String filterDoctype = null;
801 372 berkley
    String casesensitive = null;
802
    String searchmode = null;
803 342 berkley
    Object nextkey;
804
    Object nextelement;
805 350 berkley
    //add the xml headers
806
    query.append("<?xml version=\"1.0\"?>\n");
807 743 jones
    query.append("<pathquery version=\"1.0\">\n");
808
809
    if (params.containsKey("meta_file_id"))
810 342 berkley
    {
811 743 jones
      query.append("<meta_file_id>");
812 342 berkley
      query.append( ((String[])params.get("meta_file_id"))[0]);
813 535 jones
      query.append("</meta_file_id>");
814 342 berkley
    }
815 350 berkley
816 743 jones
    if (params.containsKey("returndoctype"))
817 372 berkley
    {
818 744 jones
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
819
      for(int i=0; i<returnDoctypes.length; i++)
820
      {
821
        String doctype = (String)returnDoctypes[i];
822
823
        if (!doctype.equals("any") &&
824
            !doctype.equals("ANY") &&
825
            !doctype.equals("") )
826
        {
827
          query.append("<returndoctype>").append(doctype);
828
          query.append("</returndoctype>");
829
        }
830
      }
831 372 berkley
    }
832 744 jones
833 743 jones
    if (params.containsKey("filterdoctype"))
834
    {
835
      String[] filterDoctypes = ((String[])params.get("filterdoctype"));
836
      for(int i=0; i<filterDoctypes.length; i++)
837
      {
838
        query.append("<filterdoctype>").append(filterDoctypes[i]);
839
        query.append("</filterdoctype>");
840
      }
841
    }
842 372 berkley
843 743 jones
    if (params.containsKey("returnfield"))
844 401 berkley
    {
845
      String[] returnfield = ((String[])params.get("returnfield"));
846
      for(int i=0; i<returnfield.length; i++)
847
      {
848
        query.append("<returnfield>").append(returnfield[i]);
849
        query.append("</returnfield>");
850
      }
851
    }
852
853 743 jones
    if (params.containsKey("owner"))
854 535 jones
    {
855
      String[] owner = ((String[])params.get("owner"));
856
      for(int i=0; i<owner.length; i++)
857
      {
858
        query.append("<owner>").append(owner[i]);
859
        query.append("</owner>");
860
      }
861
    }
862
863 743 jones
    if (params.containsKey("site"))
864 535 jones
    {
865
      String[] site = ((String[])params.get("site"));
866
      for(int i=0; i<site.length; i++)
867
      {
868
        query.append("<site>").append(site[i]);
869
        query.append("</site>");
870
      }
871
    }
872
873 350 berkley
    //allows the dynamic switching of boolean operators
874 743 jones
    if (params.containsKey("operator"))
875 350 berkley
    {
876
      query.append("<querygroup operator=\"" +
877 535 jones
                ((String[])params.get("operator"))[0] + "\">");
878 350 berkley
    }
879
    else
880
    { //the default operator is UNION
881
      query.append("<querygroup operator=\"UNION\">");
882
    }
883 535 jones
884 743 jones
    if (params.containsKey("casesensitive"))
885 372 berkley
    {
886
      casesensitive = ((String[])params.get("casesensitive"))[0];
887
    }
888
    else
889
    {
890
      casesensitive = "false";
891
    }
892
893 743 jones
    if (params.containsKey("searchmode"))
894 372 berkley
    {
895
      searchmode = ((String[])params.get("searchmode"))[0];
896
    }
897
    else
898
    {
899
      searchmode = "contains";
900
    }
901 535 jones
902 342 berkley
    //anyfield is a special case because it does a
903
    //free text search.  It does not have a <pathexpr>
904 350 berkley
    //tag.  This allows for a free text search within the structured
905
    //query.  This is useful if the INTERSECT operator is used.
906 743 jones
    if (params.containsKey("anyfield"))
907 342 berkley
    {
908 372 berkley
       String[] anyfield = ((String[])params.get("anyfield"));
909
       //allow for more than one value for anyfield
910
       for(int i=0; i<anyfield.length; i++)
911 350 berkley
       {
912 743 jones
         if (!anyfield[i].equals(""))
913 372 berkley
         {
914
           query.append("<queryterm casesensitive=\"" + casesensitive +
915
                        "\" " + "searchmode=\"" + searchmode + "\"><value>" +
916 535 jones
                        anyfield[i] +
917
                        "</value></queryterm>");
918 372 berkley
         }
919 350 berkley
       }
920 342 berkley
    }
921 535 jones
922 342 berkley
    //this while loop finds the rest of the parameters
923
    //and attempts to query for the field specified
924
    //by the parameter.
925
    elements = params.elements();
926
    keys = params.keys();
927
    while(keys.hasMoreElements() && elements.hasMoreElements())
928
    {
929
      nextkey = keys.nextElement();
930 535 jones
      nextelement = elements.nextElement();
931 372 berkley
932 535 jones
      //make sure we aren't querying for any of these
933
      //parameters since the are already in the query
934 342 berkley
      //in one form or another.
935 743 jones
      if (!nextkey.toString().equals("returndoctype") &&
936
         !nextkey.toString().equals("filterdoctype")  &&
937 535 jones
         !nextkey.toString().equals("action")  &&
938
         !nextkey.toString().equals("qformat") &&
939
         !nextkey.toString().equals("anyfield") &&
940 401 berkley
         !nextkey.toString().equals("returnfield") &&
941 535 jones
         !nextkey.toString().equals("owner") &&
942
         !nextkey.toString().equals("site") &&
943
         !nextkey.toString().equals("operator") )
944
      {
945 372 berkley
        //allow for more than value per field name
946
        for(int i=0; i<((String[])nextelement).length; i++)
947
        {
948 743 jones
          if (!((String[])nextelement)[i].equals(""))
949 372 berkley
          {
950
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " +
951 535 jones
                         "searchmode=\"" + searchmode + "\">" +
952
                         "<value>" +
953 372 berkley
                         //add the query value
954 535 jones
                         ((String[])nextelement)[i] +
955
                         "</value><pathexpr>" +
956
                         //add the path to query by
957 372 berkley
                         nextkey.toString() +
958
                         "</pathexpr></queryterm>");
959
          }
960
        }
961 535 jones
      }
962 342 berkley
    }
963
    query.append("</querygroup></pathquery>");
964 350 berkley
    //append on the end of the xml and return the result as a string
965 342 berkley
    return query.toString();
966
  }
967
968 181 jones
  /**
969
   * format a simple free-text value query as an XML document that conforms
970
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
971
   * structured query engine
972
   *
973
   * @param value the text string to search for in the xml catalog
974
   * @param doctype the type of documents to include in the result set -- use
975
   *        "any" or "ANY" for unfiltered result sets
976
   */
977
   public static String createQuery(String value, String doctype) {
978
     StringBuffer xmlquery = new StringBuffer();
979
     xmlquery.append("<?xml version=\"1.0\"?>\n");
980
     xmlquery.append("<pathquery version=\"1.0\">");
981
982
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
983
       xmlquery.append("<returndoctype>");
984
       xmlquery.append(doctype).append("</returndoctype>");
985
     }
986
987
     xmlquery.append("<querygroup operator=\"UNION\">");
988 350 berkley
     //chad added - 8/14
989
     //the if statement allows a query to gracefully handle a null
990
     //query.  Without this if a nullpointerException is thrown.
991 743 jones
     if (!value.equals(""))
992 350 berkley
     {
993
       xmlquery.append("<queryterm casesensitive=\"false\" ");
994
       xmlquery.append("searchmode=\"contains\">");
995
       xmlquery.append("<value>").append(value).append("</value>");
996
       xmlquery.append("</queryterm>");
997
     }
998 181 jones
     xmlquery.append("</querygroup>");
999
     xmlquery.append("</pathquery>");
1000
1001
1002
     return (xmlquery.toString());
1003
   }
1004
1005
  /**
1006
   * format a simple free-text value query as an XML document that conforms
1007
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
1008
   * structured query engine
1009
   *
1010
   * @param value the text string to search for in the xml catalog
1011
   */
1012
   public static String createQuery(String value) {
1013
     return createQuery(value, "any");
1014
   }
1015 441 bojilova
1016 570 bojilova
  /**
1017
    * Check for "READ" permission on @docid for @user and/or @group
1018
    * from DB connection
1019
    */
1020 1217 tao
  private boolean hasPermission (String user,
1021 802 bojilova
                                  String[] groups, String docid )
1022 957 tao
                  throws SQLException, Exception
1023 570 bojilova
  {
1024 802 bojilova
    // Check for READ permission on @docid for @user and/or @groups
1025 1427 tao
   PermissionController controller = new PermissionController(docid);
1026
   return controller.hasPermission(user,groups,
1027
                                 AccessControlInterface.READSTRING);
1028 441 bojilova
  }
1029 940 tao
1030
  /**
1031
    * Get all docIds list for a data packadge
1032
    * @param dataPackageDocid, the string in docId field of xml_relation table
1033
    */
1034
  private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1035
  {
1036 1217 tao
    DBConnection dbConn = null;
1037
    int serialNumber = -1;
1038 940 tao
    Vector docIdList=new Vector();//return value
1039 1217 tao
    PreparedStatement pStmt = null;
1040 940 tao
    ResultSet rs=null;
1041
    String docIdInSubjectField=null;
1042
    String docIdInObjectField=null;
1043 1292 tao
1044
    // Check the parameter
1045
    if (dataPackageDocid == null || dataPackageDocid.equals(""))
1046
    {
1047
      return docIdList;
1048
    }//if
1049
1050 940 tao
    //the query stirng
1051
    String query="SELECT subject, object from xml_relation where docId = ?";
1052
    try
1053
    {
1054 1217 tao
      dbConn=DBConnectionPool.
1055
                  getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1056
      serialNumber=dbConn.getCheckOutSerialNumber();
1057
      pStmt=dbConn.prepareStatement(query);
1058 940 tao
      //bind the value to query
1059
      pStmt.setString(1, dataPackageDocid);
1060
1061
      //excute the query
1062
      pStmt.execute();
1063
      //get the result set
1064
      rs=pStmt.getResultSet();
1065
      //process the result
1066
      while (rs.next())
1067
      {
1068
        //In order to get the whole docIds in a data packadge,
1069
        //we need to put the docIds of subject and object field in xml_relation
1070
        //into the return vector
1071
        docIdInSubjectField=rs.getString(1);//the result docId in subject field
1072
        docIdInObjectField=rs.getString(2);//the result docId in object field
1073
1074
        //don't put the duplicate docId into the vector
1075
        if (!docIdList.contains(docIdInSubjectField))
1076
        {
1077
          docIdList.add(docIdInSubjectField);
1078
        }
1079
1080
        //don't put the duplicate docId into the vector
1081
        if (!docIdList.contains(docIdInObjectField))
1082
        {
1083
          docIdList.add(docIdInObjectField);
1084
        }
1085
      }//while
1086
      //close the pStmt
1087
      pStmt.close();
1088
    }//try
1089
    catch (SQLException e)
1090
    {
1091 1292 tao
      MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1092 1096 tao
                            +e.getMessage(), 30);
1093 940 tao
    }//catch
1094 1217 tao
    finally
1095
    {
1096
      try
1097
      {
1098
        pStmt.close();
1099
      }//try
1100
      catch (SQLException ee)
1101
      {
1102 1292 tao
        MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1103 1217 tao
                            +ee.getMessage(), 30);
1104
      }//catch
1105
      finally
1106
      {
1107
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1108
      }//fianlly
1109
    }//finally
1110 940 tao
    return docIdList;
1111
  }//getCurrentDocidListForDataPackadge()
1112
1113
  /**
1114
   * Get all docIds list for a data packadge
1115
   * @param dataPackageDocid, the string in docId field of xml_relation table
1116
   */
1117
  private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1118
  {
1119 441 bojilova
1120 940 tao
    Vector docIdList=new Vector();//return value
1121
    Vector tripleList=null;
1122
    String xml=null;
1123 1292 tao
1124
     // Check the parameter
1125
    if (dataPackageDocid == null || dataPackageDocid.equals(""))
1126
    {
1127
      return docIdList;
1128
    }//if
1129
1130
    try
1131
    {
1132 1217 tao
      //initial a documentImpl object
1133
      DocumentImpl packageDocument =
1134
                  new DocumentImpl(dataPackageDocid);
1135
      //transfer to documentImpl object to string
1136
      xml=packageDocument.toString();
1137 940 tao
1138 1217 tao
      //create a tripcollection object
1139
      TripleCollection tripleForPackage = new
1140 940 tao
                                     TripleCollection(new StringReader(xml));
1141 1217 tao
      //get the vetor of triples
1142
      tripleList=tripleForPackage.getCollection();
1143 940 tao
1144 1217 tao
      for (int i= 0; i<tripleList.size(); i++)
1145 940 tao
      {
1146 1217 tao
        //put subject docid  into docIdlist without duplicate
1147
        if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getSubject()))
1148
        {
1149
          //put subject docid  into docIdlist
1150
          docIdList.add(((Triple)tripleList.get(i)).getSubject());
1151
        }
1152
        //put object docid into docIdlist without duplicate
1153
        if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getObject()))
1154
        {
1155
          docIdList.add(((Triple)(tripleList.get(i))).getObject());
1156
        }
1157
      }//for
1158 1292 tao
    }//try
1159
    catch (Exception e)
1160
    {
1161
      MetaCatUtil.debugMessage("Error in getOldVersionAllDocumentImpl: "
1162
                            +e.getMessage(), 30);
1163
    }//catch
1164 1217 tao
1165 1292 tao
    // return result
1166 940 tao
    return docIdList;
1167
  }//getDocidListForPackageInXMLRevisions()
1168
1169
  /**
1170
   * Check if the docId is a data packadge id. If the id is a data packadage
1171
   *id, it should be store in the docId fields in xml_relation table.
1172
   *So we can use a query to get the entries which the docId equals the given
1173
   *value. If the result is null. The docId is not a packadge id. Otherwise,
1174
   * it is.
1175
   * @param docId, the id need to be checked
1176
   */
1177
  private boolean isDataPackageId(String docId)
1178
  {
1179
    boolean result=false;
1180 1217 tao
    PreparedStatement pStmt = null;
1181 940 tao
    ResultSet rs=null;
1182
    String query="SELECT docId from xml_relation where docId = ?";
1183 1217 tao
    DBConnection dbConn = null;
1184
    int serialNumber = -1;
1185 940 tao
    try
1186
    {
1187 1217 tao
      dbConn=DBConnectionPool.
1188
                  getDBConnection("DBQuery.isDataPackageId");
1189
      serialNumber=dbConn.getCheckOutSerialNumber();
1190
      pStmt=dbConn.prepareStatement(query);
1191 940 tao
      //bind the value to query
1192
      pStmt.setString(1, docId);
1193
      //execute the query
1194
      pStmt.execute();
1195
      rs=pStmt.getResultSet();
1196
      //process the result
1197
      if (rs.next()) //There are some records for the id in docId fields
1198
      {
1199
        result=true;//It is a data packadge id
1200
      }
1201
      pStmt.close();
1202
    }//try
1203
    catch (SQLException e)
1204
    {
1205 1217 tao
      util.debugMessage("Error in isDataPackageId: "
1206 1096 tao
                            +e.getMessage(), 30);
1207 940 tao
    }
1208 1217 tao
    finally
1209
    {
1210
      try
1211
      {
1212
        pStmt.close();
1213
      }//try
1214
      catch (SQLException ee)
1215
      {
1216
        MetaCatUtil.debugMessage("Error in isDataPackageId: "
1217
                                                        + ee.getMessage(), 30);
1218
      }//catch
1219
      finally
1220
      {
1221
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1222
      }//finally
1223
    }//finally
1224 940 tao
    return result;
1225
  }//isDataPackageId()
1226
1227
  /**
1228 945 tao
   * Check if the user has the permission to export data package
1229
   * @param conn, the connection
1230
   * @param docId, the id need to be checked
1231
   * @param user, the name of user
1232
   * @param groups, the user's group
1233
   */
1234 1217 tao
   private boolean hasPermissionToExportPackage(String docId,
1235 945 tao
                                        String user, String[] groups)
1236
                   throws Exception
1237
   {
1238 1217 tao
     //DocumentImpl doc=new DocumentImpl(conn,docId);
1239
     return DocumentImpl.hasReadPermission(user, groups,docId);
1240 945 tao
   }
1241
1242
  /**
1243 940 tao
   *Get the current Rev for a docid in xml_documents table
1244
   * @param docId, the id need to get version numb
1245
   * If the return value is -5, means no value in rev field for this docid
1246
   */
1247
  private int getCurrentRevFromXMLDoumentsTable(String docId)
1248 1292 tao
                                                throws SQLException
1249 940 tao
  {
1250
    int rev=-5;
1251 1217 tao
    PreparedStatement pStmt = null;
1252 940 tao
    ResultSet rs=null;
1253
    String query="SELECT rev from xml_documents where docId = ?";
1254 1217 tao
    DBConnection dbConn=null;
1255
    int serialNumber = -1;
1256 940 tao
    try
1257
    {
1258 1217 tao
      dbConn=DBConnectionPool.
1259
                  getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1260
      serialNumber=dbConn.getCheckOutSerialNumber();
1261
      pStmt=dbConn.prepareStatement(query);
1262 940 tao
      //bind the value to query
1263
      pStmt.setString(1, docId);
1264
      //execute the query
1265
      pStmt.execute();
1266
      rs=pStmt.getResultSet();
1267
      //process the result
1268
      if (rs.next()) //There are some records for rev
1269
      {
1270
        rev=rs.getInt(1);;//It is the version for given docid
1271
      }
1272
      else
1273
      {
1274
        rev=-5;
1275
      }
1276 1292 tao
1277 940 tao
    }//try
1278
    catch (SQLException e)
1279
    {
1280 1292 tao
      MetaCatUtil.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
1281 1096 tao
                            +e.getMessage(), 30);
1282 1292 tao
      throw e;
1283 1217 tao
    }//catch
1284
    finally
1285
    {
1286
      try
1287
      {
1288
        pStmt.close();
1289
      }//try
1290
      catch (SQLException ee)
1291
      {
1292
        MetaCatUtil.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
1293
                                  +ee.getMessage(), 30);
1294
      }//catch
1295
      finally
1296
      {
1297
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1298
      }//finally
1299
    }//finally
1300 940 tao
    return rev;
1301
  }//getCurrentRevFromXMLDoumentsTable
1302
1303
 /**
1304
   *put a doc into a zip output stream
1305
   *@param docImpl, docmentImpl object which will be sent to zip output stream
1306
   *@param zipOut, zip output stream which the docImpl will be put
1307
   *@param packageZipEntry, the zip entry name for whole package
1308
   */
1309
  private void addDocToZipOutputStream(DocumentImpl docImpl,
1310
                                ZipOutputStream zipOut, String packageZipEntry)
1311
               throws ClassNotFoundException, IOException, SQLException,
1312
                      McdbException, Exception
1313
  {
1314
    byte[] byteString = null;
1315
    ZipEntry zEntry = null;
1316
1317
    byteString = docImpl.toString().getBytes();
1318
    //use docId as the zip entry's name
1319
    zEntry = new ZipEntry(packageZipEntry+"/metadata/"+docImpl.getDocID());
1320
    zEntry.setSize(byteString.length);
1321
    zipOut.putNextEntry(zEntry);
1322
    zipOut.write(byteString, 0, byteString.length);
1323
    zipOut.closeEntry();
1324
1325
  }//addDocToZipOutputStream()
1326
1327
1328
  /**
1329 1292 tao
   * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1330
   * only inlcudes current version. If a DocumentImple object
1331
   * couldn't find for a docid, then the String of this docid was added to vetor
1332
   * rather than DocumentImple object.
1333
   * @param docIdList, a vetor hold a docid list for a data package. In docid,
1334
   * there is not version number in it.
1335 940 tao
   */
1336
1337
  private Vector getCurrentAllDocumentImpl( Vector docIdList)
1338
                              throws McdbException,Exception
1339
  {
1340 1217 tao
    //Connection dbConn=null;
1341 940 tao
    Vector documentImplList=new Vector();
1342
    int rev=0;
1343
1344 1292 tao
    // Check the parameter
1345
    if (docIdList.isEmpty())
1346 940 tao
    {
1347 1292 tao
      return documentImplList;
1348
    }//if
1349
1350 940 tao
    //for every docid in vector
1351
    for (int i=0;i<docIdList.size();i++)
1352
    {
1353 1292 tao
      try
1354
      {
1355
        //get newest version for this docId
1356
        rev=getCurrentRevFromXMLDoumentsTable((String)docIdList.elementAt(i));
1357
1358
        // There is no record for this docId in xml_documents table
1359
        if (rev ==-5)
1360
        {
1361
          // Rather than put DocumentImple object, put a String Object(docid)
1362
          // into the documentImplList
1363
          documentImplList.add((String)docIdList.elementAt(i));
1364
          // Skip other code
1365
          continue;
1366
        }
1367 948 tao
1368 1292 tao
        String docidPlusVersion=((String)docIdList.elementAt(i))
1369 948 tao
                        +util.getOption("accNumSeparator")+rev;
1370 1292 tao
1371
1372
        //create new documentImpl object
1373
        DocumentImpl documentImplObject =
1374 1217 tao
                                    new DocumentImpl(docidPlusVersion);
1375 1292 tao
       //add them to vector
1376
        documentImplList.add(documentImplObject);
1377
      }//try
1378
      catch (Exception e)
1379
      {
1380
        MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1381
                            +e.getMessage(), 30);
1382
        // continue the for loop
1383
        continue;
1384
      }
1385 940 tao
    }//for
1386
    return documentImplList;
1387
  }
1388
1389
  /**
1390 1292 tao
   * Transfer a docid vetor to a documentImpl vector. If a DocumentImple object
1391
   * couldn't find for a docid, then the String of this docid was added to vetor
1392
   * rather than DocumentImple object.
1393
   * @param docIdList, a vetor hold a docid list for a data package. In docid,
1394
   *t here is version number in it.
1395 940 tao
   */
1396
  private Vector getOldVersionAllDocumentImpl( Vector docIdList)
1397
  {
1398 1217 tao
    //Connection dbConn=null;
1399 940 tao
    Vector documentImplList=new Vector();
1400
    String siteCode=null;
1401
    String uniqueId=null;
1402
    int rev=0;
1403
1404 1292 tao
    // Check the parameter
1405
    if (docIdList.isEmpty())
1406 940 tao
    {
1407 1292 tao
      return documentImplList;
1408
    }//if
1409
1410 940 tao
    //for every docid in vector
1411
    for (int i=0;i<docIdList.size();i++)
1412
    {
1413
1414 948 tao
        String docidPlusVersion=(String)(docIdList.elementAt(i));
1415 1292 tao
1416
        try
1417
        {
1418
          //create new documentImpl object
1419
          DocumentImpl documentImplObject =
1420 1217 tao
                                    new DocumentImpl(docidPlusVersion);
1421 1292 tao
          //add them to vector
1422
          documentImplList.add(documentImplObject);
1423
        }//try
1424
        catch (McdbDocNotFoundException notFoundE)
1425
        {
1426
          MetaCatUtil.debugMessage("Error in DBQuery.getOldVersionAllDocument"+
1427
                                  "Imple" + notFoundE.getMessage(), 30);
1428
          // Rather than add a DocumentImple object into vetor, a String object
1429
          // - the doicd was added to the vector
1430
          documentImplList.add(docidPlusVersion);
1431
          // Continue the for loop
1432
          continue;
1433
        }//catch
1434
        catch (Exception e)
1435
        {
1436
          MetaCatUtil.debugMessage("Error in DBQuery.getOldVersionAllDocument"+
1437
                                  "Imple" + e.getMessage(), 30);
1438
          // Continue the for loop
1439
          continue;
1440
        }//catch
1441
1442 948 tao
1443 940 tao
    }//for
1444
    return documentImplList;
1445 1292 tao
  }//getOldVersionAllDocumentImple
1446
1447 940 tao
  /**
1448
   *put a data file into a zip output stream
1449
   *@param docImpl, docmentImpl object which will be sent to zip output stream
1450
   *@param zipOut, the zip output stream which the docImpl will be put
1451
   *@param packageZipEntry, the zip entry name for whole package
1452
   */
1453
  private void addDataFileToZipOutputStream(DocumentImpl docImpl,
1454
                                ZipOutputStream zipOut, String packageZipEntry)
1455
               throws ClassNotFoundException, IOException, SQLException,
1456
                      McdbException, Exception
1457
  {
1458
    byte[] byteString = null;
1459
    ZipEntry zEntry = null;
1460
    // this is data file; add file to zip
1461
    String filePath = util.getOption("datafilepath");
1462
    if (!filePath.endsWith("/"))
1463
    {
1464
      filePath += "/";
1465
    }
1466
    String fileName = filePath + docImpl.getDocID();
1467 963 berkley
    zEntry = new ZipEntry(packageZipEntry+"/data/"+docImpl.getDocID());
1468 940 tao
    zipOut.putNextEntry(zEntry);
1469
    FileInputStream fin = null;
1470
    try
1471
    {
1472
      fin = new FileInputStream(fileName);
1473
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1474
      int b = fin.read(buf);
1475
      while (b != -1)
1476
      {
1477
        zipOut.write(buf, 0, b);
1478
        b = fin.read(buf);
1479
      }//while
1480
      zipOut.closeEntry();
1481
    }//try
1482
    catch (IOException ioe)
1483
    {
1484 1096 tao
      util.debugMessage("There is an exception: "+ioe.getMessage(), 30);
1485 940 tao
    }//catch
1486
  }//addDataFileToZipOutputStream()
1487
1488
  /**
1489
   *create a html summary for data package and put it into zip output stream
1490
   *@param docImplList, the documentImpl ojbects in data package
1491
   *@param zipOut, the zip output stream which the html should be put
1492
   *@param packageZipEntry, the zip entry name for whole package
1493
   */
1494
   private void addHtmlSummaryToZipOutputStream(Vector docImplList,
1495
                                ZipOutputStream zipOut, String packageZipEntry)
1496
                                           throws Exception
1497
  {
1498
    StringBuffer htmlDoc = new StringBuffer();
1499
    ZipEntry zEntry = null;
1500
    byte[] byteString=null;
1501
    InputStream source;
1502
    DBTransform xmlToHtml;
1503 1292 tao
1504 940 tao
    //create a DBTransform ojbect
1505 1217 tao
    xmlToHtml = new DBTransform();
1506 940 tao
    //head of html
1507
    htmlDoc.append("<html><head></head><body>");
1508
    for (int i=0; i<docImplList.size(); i++)
1509
    {
1510 1292 tao
      // If this String object, this means it is missed data file
1511
      if ((((docImplList.elementAt(i)).getClass()).toString())
1512
                                             .equals("class java.lang.String"))
1513
      {
1514
1515
        htmlDoc.append("<a href=\"");
1516
        String dataFileid =(String)docImplList.elementAt(i);
1517
        htmlDoc.append("./data/").append(dataFileid).append("\">");
1518
        htmlDoc.append("Data File: ");
1519
        htmlDoc.append(dataFileid).append("</a><br>");
1520
        htmlDoc.append("<br><hr><br>");
1521
1522
      }//if
1523
      else if ((((DocumentImpl)docImplList.elementAt(i)).getDoctype()).
1524 940 tao
                                                         compareTo("BIN")!=0)
1525
      { //this is an xml file so we can transform it.
1526
        //transform each file individually then concatenate all of the
1527
        //transformations together.
1528
1529
        //for metadata xml title
1530
        htmlDoc.append("<h2>");
1531
        htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getDocID());
1532
        //htmlDoc.append(".");
1533
        //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
1534
        htmlDoc.append("</h2>");
1535
        //do the actual transform
1536
        StringWriter docString = new StringWriter();
1537
        xmlToHtml.transformXMLDocument(
1538
                        ((DocumentImpl)docImplList.elementAt(i)).toString(),
1539
           "-//NCEAS//eml-generic//EN", "-//W3C//HTML//EN", "html", docString);
1540
        htmlDoc.append(docString.toString());
1541
        htmlDoc.append("<br><br><hr><br><br>");
1542
      }//if
1543
      else
1544
      { //this is a data file so we should link to it in the html
1545
        htmlDoc.append("<a href=\"");
1546
        String dataFileid =((DocumentImpl)docImplList.elementAt(i)).getDocID();
1547
        htmlDoc.append("./data/").append(dataFileid).append("\">");
1548
        htmlDoc.append("Data File: ");
1549
        htmlDoc.append(dataFileid).append("</a><br>");
1550
        htmlDoc.append("<br><hr><br>");
1551
      }//else
1552
    }//for
1553
    htmlDoc.append("</body></html>");
1554
    byteString = htmlDoc.toString().getBytes();
1555
    zEntry = new ZipEntry(packageZipEntry+"/metadata.html");
1556
    zEntry.setSize(byteString.length);
1557
    zipOut.putNextEntry(zEntry);
1558
    zipOut.write(byteString, 0, byteString.length);
1559
    zipOut.closeEntry();
1560 1217 tao
    //dbConn.close();
1561 940 tao
1562
  }//addHtmlSummaryToZipOutputStream
1563
1564 945 tao
1565
1566 940 tao
  /**
1567
   * put a data packadge into a zip output stream
1568
   * @param docId, which the user want to put into zip output stream
1569
   * @param out, a servletoutput stream which the zip output stream will be put
1570
   * @param user, the username of the user
1571
   * @param groups, the group of the user
1572
   */
1573
  public ZipOutputStream getZippedPackage(String docIdString,
1574 1292 tao
        ServletOutputStream out, String user, String[] groups, String passWord)
1575 940 tao
                    throws ClassNotFoundException, IOException, SQLException,
1576
                      McdbException, NumberFormatException, Exception
1577
  {
1578
    ZipOutputStream zOut = null;
1579
    String elementDocid=null;
1580
    DocumentImpl docImpls=null;
1581 1217 tao
    //Connection dbConn = null;
1582 940 tao
    Vector docIdList=new Vector();
1583 945 tao
    Vector documentImplList=new Vector();
1584
    Vector htmlDocumentImplList=new Vector();
1585 940 tao
    String packageId=null;
1586
    String rootName="package";//the package zip entry name
1587
1588
    String docId=null;
1589
    int version=-5;
1590 1292 tao
    // Docid without revision
1591 940 tao
    docId=MetaCatUtil.getDocIdFromString(docIdString);
1592 1292 tao
    // revision number
1593 940 tao
    version=MetaCatUtil.getVersionFromString(docIdString);
1594
1595
    //check if the reqused docId is a data package id
1596 1356 tao
    if (!isDataPackageId(docId))
1597 940 tao
    {
1598 1356 tao
1599
      /*Exception e = new Exception("The request the doc id " +docIdString+
1600 940 tao
                                    " is not a data package id");
1601 1356 tao
      throw e;*/
1602
1603
1604
      //CB 1/6/03: if the requested docid is not a datapackage, we just zip
1605
      //up the single document and return the zip file.
1606
1607
      if(!hasPermissionToExportPackage(docId, user, groups))
1608
      {
1609
1610
        Exception e = new Exception("User " + user + " does not have permission"
1611
                         +" to export the data package " + docIdString);
1612
        throw e;
1613
      }
1614
1615
      docImpls=new DocumentImpl(docId);
1616
      //checking if the user has the permission to read the documents
1617
      if (docImpls.hasReadPermission(user,groups,docImpls.getDocID()))
1618
      {
1619
        zOut = new ZipOutputStream(out);
1620
        //if the docImpls is metadata
1621
        if ((docImpls.getDoctype()).compareTo("BIN")!=0)
1622
        {
1623
          //add metadata into zip output stream
1624
          addDocToZipOutputStream(docImpls, zOut, rootName);
1625
        }//if
1626
        else
1627
        {
1628
          //it is data file
1629
          addDataFileToZipOutputStream(docImpls, zOut, rootName);
1630
          htmlDocumentImplList.add(docImpls);
1631
        }//else
1632
      }//if
1633
1634
      zOut.finish(); //terminate the zip file
1635
      return zOut;
1636 940 tao
    }
1637 1292 tao
    // Check the permission of user
1638 1217 tao
    else if(!hasPermissionToExportPackage(docId, user, groups))
1639 945 tao
    {
1640 1292 tao
1641 945 tao
      Exception e = new Exception("User " + user + " does not have permission"
1642
                       +" to export the data package " + docIdString);
1643
      throw e;
1644
    }
1645 940 tao
    else //it is a packadge id
1646
    {
1647
      //store the package id
1648
      packageId=docId;
1649 1292 tao
      //get current version in database
1650
      int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
1651
      //If it is for current version (-1 means user didn't specify revision)
1652
      if ((version ==-1)||version==currentVersion)
1653 940 tao
      {
1654
        //get current version number
1655 1292 tao
        version=currentVersion;
1656 940 tao
        //get package zip entry name
1657
        //it should be docId.revsion.package
1658
        rootName=packageId+util.getOption("accNumSeparator")+version+
1659
                                  util.getOption("accNumSeparator")+"package";
1660
        //get the whole id list for data packadge
1661
        docIdList=getCurrentDocidListForDataPackage(packageId);
1662
        //get the whole documentImple object
1663
        documentImplList=getCurrentAllDocumentImpl(docIdList);
1664
1665
      }//if
1666 1292 tao
      else if (version > currentVersion || version < -1)
1667
      {
1668
        throw new Exception ("The user specified docid: "+docId+"."+version
1669
                                              +" doesn't exist");
1670
      }//else if
1671 940 tao
      else  //for an old version
1672
      {
1673
1674
        rootName=docIdString+util.getOption("accNumSeparator")+"package";
1675
        //get the whole id list for data packadge
1676
        docIdList=getOldVersionDocidListForDataPackage(docIdString);
1677
1678
        //get the whole documentImple object
1679
        documentImplList=getOldVersionAllDocumentImpl(docIdList);
1680
      }//else
1681
1682 1292 tao
      // Make sure documentImplist is not empty
1683
      if (documentImplList.isEmpty())
1684
      {
1685
        throw new Exception ("Couldn't find component for data package: "
1686
                                              + packageId);
1687
      }//if
1688 940 tao
1689 1292 tao
1690
       zOut = new ZipOutputStream(out);
1691 940 tao
      //put every element into zip output stream
1692
      for (int i=0; i < documentImplList.size(); i++ )
1693
      {
1694 1292 tao
        // if the object in the vetor is String, this means we couldn't find
1695
        // the document locally, we need find it remote
1696
       if ((((documentImplList.elementAt(i)).getClass()).toString())
1697
                                             .equals("class java.lang.String"))
1698
        {
1699
          // Get String object from vetor
1700
          String documentId = (String) documentImplList.elementAt(i);
1701
          MetaCatUtil.debugMessage("docid: "+documentId, 30);
1702
          // Get doicd without revision
1703
          String docidWithoutRevision =
1704
                                     MetaCatUtil.getDocIdFromString(documentId);
1705
          MetaCatUtil.debugMessage("docidWithoutRevsion: "
1706
                                                     +docidWithoutRevision, 30);
1707
          // Get revision
1708
          String revision = MetaCatUtil.getRevisionStringFromString(documentId);
1709
          MetaCatUtil.debugMessage("revsion from docIdentifier: "+revision, 30);
1710
          // Zip entry string
1711
          String zipEntryPath = rootName+"/data/";
1712
          // Create a RemoteDocument object
1713
          RemoteDocument remoteDoc =
1714
                          new RemoteDocument(docidWithoutRevision,revision,user,
1715
                                                     passWord, zipEntryPath);
1716
          // Here we only read data file from remote metacat
1717
          String docType = remoteDoc.getDocType();
1718
          if (docType!=null)
1719
          {
1720
            if (docType.equals("BIN"))
1721
            {
1722
              // Put remote document to zip output
1723
              remoteDoc.readDocumentFromRemoteServerByZip(zOut);
1724
              // Add String object to htmlDocumentImplList
1725
              String elementInHtmlList = remoteDoc.getDocIdWithoutRevsion()+
1726
               MetaCatUtil.getOption("accNumSeparator")+remoteDoc.getRevision();
1727
              htmlDocumentImplList.add(elementInHtmlList);
1728
            }//if
1729
          }//if
1730
1731
        }//if
1732
        else
1733
        {
1734
          //create a docmentImpls object (represent xml doc) base on the docId
1735
          docImpls=(DocumentImpl)documentImplList.elementAt(i);
1736
          //checking if the user has the permission to read the documents
1737
          if (docImpls.hasReadPermission(user,groups,docImpls.getDocID()))
1738
          {
1739 948 tao
            //if the docImpls is metadata
1740 1292 tao
            if ((docImpls.getDoctype()).compareTo("BIN")!=0)
1741
            {
1742 948 tao
              //add metadata into zip output stream
1743
              addDocToZipOutputStream(docImpls, zOut, rootName);
1744
              //add the documentImpl into the vetor which will be used in html
1745
              htmlDocumentImplList.add(docImpls);
1746 953 tao
1747 1292 tao
            }//if
1748
            else
1749
            {
1750
              //it is data file
1751
              addDataFileToZipOutputStream(docImpls, zOut, rootName);
1752
              htmlDocumentImplList.add(docImpls);
1753
            }//else
1754 948 tao
          }//if
1755 1292 tao
        }//else
1756 940 tao
      }//for
1757
1758
      //add html summary file
1759 945 tao
      addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut, rootName);
1760 940 tao
      zOut.finish(); //terminate the zip file
1761 1217 tao
      //dbConn.close();
1762 940 tao
      return zOut;
1763
    }//else
1764
  }//getZippedPackage()
1765 1361 tao
1766
   private class ReturnFieldValue
1767
  {
1768
    private String docid          = null; //return field value for this docid
1769
    private String fieldValue     = null;
1770
    private String xmlFieldValue  = null; //return field value in xml format
1771
1772
1773
    public void setDocid(String myDocid)
1774
    {
1775
      docid = myDocid;
1776
    }
1777
1778
    public String getDocid()
1779
    {
1780
      return docid;
1781
    }
1782
1783
    public void setFieldValue(String myValue)
1784
    {
1785
      fieldValue = myValue;
1786
    }
1787
1788
    public String getFieldValue()
1789
    {
1790
      return fieldValue;
1791
    }
1792
1793
    public void setXMLFieldValue(String xml)
1794
    {
1795
      xmlFieldValue = xml;
1796
    }
1797
1798
    public String getXMLFieldValue()
1799
    {
1800
      return xmlFieldValue;
1801
    }
1802
1803 940 tao
1804 1361 tao
  }
1805
1806 155 jones
}