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