Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *    Release: 1.4.0
12
 *
13
 *   '$Author: sgarg $'
14
 *     '$Date: 2005-01-06 12:47:04 -0800 (Thu, 06 Jan 2005) $'
15
 * '$Revision: 2360 $'
16
 *
17
 * This program is free software; you can redistribute it and/or modify
18
 * it under the terms of the GNU General Public License as published by
19
 * the Free Software Foundation; either version 2 of the License, or
20
 * (at your option) any later version.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
 * GNU General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU General Public License
28
 * along with this program; if not, write to the Free Software
29
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30
 */
31

    
32
package edu.ucsb.nceas.metacat;
33

    
34
import java.io.BufferedWriter;
35
import java.io.File;
36
import java.io.FileInputStream;
37
import java.io.FileReader;
38
import java.io.FileWriter;
39
import java.io.IOException;
40
import java.io.InputStream;
41
import java.io.PrintWriter;
42
import java.io.Reader;
43
import java.io.StringReader;
44
import java.io.StringWriter;
45
import java.sql.PreparedStatement;
46
import java.sql.ResultSet;
47
import java.sql.SQLException;
48
import java.util.Enumeration;
49
import java.util.Hashtable;
50
import java.util.StringTokenizer;
51
import java.util.Vector;
52
import java.util.zip.ZipEntry;
53
import java.util.zip.ZipOutputStream;
54

    
55
import javax.servlet.ServletOutputStream;
56
import javax.servlet.http.HttpServletResponse;
57

    
58

    
59
import edu.ucsb.nceas.morpho.datapackage.Triple;
60
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
61

    
62
/**
63
 * A Class that searches a relational DB for elements and attributes that have
64
 * free text matches a query string, or structured query matches to a path
65
 * specified node in the XML hierarchy. It returns a result set consisting of
66
 * the document ID for each document that satisfies the query
67
 */
68
public class DBQuery
69
{
70

    
71
    static final int ALL = 1;
72

    
73
    static final int WRITE = 2;
74

    
75
    static final int READ = 4;
76

    
77
    //private Connection conn = null;
78
    private String parserName = null;
79

    
80
    private MetaCatUtil util = new MetaCatUtil();
81

    
82
    /**
83
     * the main routine used to test the DBQuery utility.
84
     * <p>
85
     * Usage: java DBQuery <xmlfile>
86
     *
87
     * @param xmlfile the filename of the xml file containing the query
88
     */
89
    static public void main(String[] args)
90
    {
91

    
92
        if (args.length < 1) {
93
            System.err.println("Wrong number of arguments!!!");
94
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
95
            return;
96
        } else {
97
            try {
98

    
99
                int i = 0;
100
                boolean showRuntime = false;
101
                boolean useXMLIndex = false;
102
                if (args[i].equals("-t")) {
103
                    showRuntime = true;
104
                    i++;
105
                }
106
                if (args[i].equals("-index")) {
107
                    useXMLIndex = true;
108
                    i++;
109
                }
110
                String xmlfile = args[i];
111

    
112
                // Time the request if asked for
113
                double startTime = System.currentTimeMillis();
114

    
115
                // Open a connection to the database
116
                MetaCatUtil util = new MetaCatUtil();
117
                //Connection dbconn = util.openDBConnection();
118

    
119
                double connTime = System.currentTimeMillis();
120

    
121
                // Execute the query
122
                DBQuery queryobj = new DBQuery(MetaCatUtil
123
                        .getOption("saxparser"));
124
                FileReader xml = new FileReader(new File(xmlfile));
125
                Hashtable nodelist = null;
126
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
127

    
128
                // Print the reulting document listing
129
                StringBuffer result = new StringBuffer();
130
                String document = null;
131
                String docid = null;
132
                result.append("<?xml version=\"1.0\"?>\n");
133
                result.append("<resultset>\n");
134

    
135
                if (!showRuntime) {
136
                    Enumeration doclist = nodelist.keys();
137
                    while (doclist.hasMoreElements()) {
138
                        docid = (String) doclist.nextElement();
139
                        document = (String) nodelist.get(docid);
140
                        result.append("  <document>\n    " + document
141
                                + "\n  </document>\n");
142
                    }
143

    
144
                    result.append("</resultset>\n");
145
                }
146
                // Time the request if asked for
147
                double stopTime = System.currentTimeMillis();
148
                double dbOpenTime = (connTime - startTime) / 1000;
149
                double readTime = (stopTime - connTime) / 1000;
150
                double executionTime = (stopTime - startTime) / 1000;
151
                if (showRuntime) {
152
                    System.out.print("  " + executionTime);
153
                    System.out.print("  " + dbOpenTime);
154
                    System.out.print("  " + readTime);
155
                    System.out.print("  " + nodelist.size());
156
                    System.out.println();
157
                }
158
                //System.out.println(result);
159
                //write into a file "result.txt"
160
                if (!showRuntime) {
161
                    File f = new File("./result.txt");
162
                    FileWriter fw = new FileWriter(f);
163
                    BufferedWriter out = new BufferedWriter(fw);
164
                    out.write(result.toString());
165
                    out.flush();
166
                    out.close();
167
                    fw.close();
168
                }
169

    
170
            } catch (Exception e) {
171
                System.err.println("Error in DBQuery.main");
172
                System.err.println(e.getMessage());
173
                e.printStackTrace(System.err);
174
            }
175
        }
176
    }
177

    
178
    /**
179
     * construct an instance of the DBQuery class
180
     *
181
     * <p>
182
     * Generally, one would call the findDocuments() routine after creating an
183
     * instance to specify the search query
184
     * </p>
185
     *
186

    
187
     * @param parserName the fully qualified name of a Java class implementing
188
     *            the org.xml.sax.XMLReader interface
189
     */
190
    public DBQuery(String parserName)
191
    {
192
       this.parserName = parserName;
193
    }
194

    
195

    
196
  /**
197
   * Method put the search result set into out printerwriter
198
   * @param resoponse the return response
199
   * @param out the output printer
200
   * @param params the paratermer hashtable
201
   * @param user the user name (it maybe different to the one in param)
202
   * @param groups the group array
203
   * @param sessionid  the sessionid
204
   */
205
  public void findDocuments(HttpServletResponse response,
206
                                       PrintWriter out, Hashtable params,
207
                                       String user, String[] groups,
208
                                       String sessionid)
209
  {
210
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
211
               .booleanValue();
212
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
213

    
214
  }
215

    
216

    
217
    /**
218
     * Method put the search result set into out printerwriter
219
     * @param resoponse the return response
220
     * @param out the output printer
221
     * @param params the paratermer hashtable
222
     * @param user the user name (it maybe different to the one in param)
223
     * @param groups the group array
224
     * @param sessionid  the sessionid
225
     */
226
    public void findDocuments(HttpServletResponse response,
227
                                         PrintWriter out, Hashtable params,
228
                                         String user, String[] groups,
229
                                         String sessionid, boolean useXMLIndex)
230
    {
231
      // get query and qformat
232
      String xmlquery = ((String[])params.get("query"))[0];
233

    
234
      MetaCatUtil.debugMessage("xmlquery: " + xmlquery, 30);
235
      String qformat = ((String[])params.get("qformat"))[0];
236
      MetaCatUtil.debugMessage("qformat: " + qformat, 30);
237
      // Get the XML query and covert it into a SQL statment
238
      QuerySpecification qspec = null;
239
      if ( xmlquery != null)
240
      {
241
         xmlquery = transformQuery(xmlquery);
242
         try
243
         {
244
           qspec = new QuerySpecification(xmlquery,
245
                                          parserName,
246
                                          MetaCatUtil.getOption("accNumSeparator"));
247
         }
248
         catch (Exception ee)
249
         {
250
           MetaCatUtil.debugMessage("erro to generate QuerySpecification object"
251
                                    +" in DBQuery.findDocuments"
252
                                    + ee.getMessage(), 30);
253
         }
254
      }
255

    
256

    
257

    
258
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
259
      {
260
        //xml format
261
        response.setContentType("text/xml");
262
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex);
263
      }//if
264
      else
265
      {
266
        //knb format, in this case we will get whole result and sent it out
267
        response.setContentType("text/html");
268
        PrintWriter nonout = null;
269
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
270
                                                groups, useXMLIndex);
271
        //transfer the xml to html
272
        try
273
        {
274

    
275
         DBTransform trans = new DBTransform();
276
         response.setContentType("text/html");
277
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
278
                                 "-//W3C//HTML//EN", qformat, out, params,
279
                                 sessionid);
280

    
281
        }
282
        catch(Exception e)
283
        {
284
         MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
285
                                +e.getMessage(), 30);
286
         }
287

    
288
      }//else
289

    
290
    }
291

    
292
  /*
293
   * Transforms a hashtable of documents to an xml or html result and sent
294
   * the content to outputstream. Keep going untill hastable is empty. stop it.
295
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
296
   * to xmlquery String
297
   */
298
  public StringBuffer createResultDocument(String xmlquery,
299
                                            QuerySpecification qspec,
300
                                            PrintWriter out,
301
                                            String user, String[] groups,
302
                                            boolean useXMLIndex)
303
  {
304
    DBConnection dbconn = null;
305
    int serialNumber = -1;
306
    StringBuffer resultset = new StringBuffer();
307
    resultset.append("<?xml version=\"1.0\"?>\n");
308
    resultset.append("<resultset>\n");
309
    resultset.append("  <query>" + xmlquery + "</query>");
310
    // sent query part out
311
    if (out != null)
312
    {
313
      out.println(resultset.toString());
314
    }
315
    if (qspec != null)
316
    {
317
      try
318
      {
319

    
320
        //checkout the dbconnection
321
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
322
        serialNumber = dbconn.getCheckOutSerialNumber();
323

    
324
        //print out the search result
325
        // search the doc list
326
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
327
                                      dbconn, useXMLIndex);
328

    
329
      } //try
330
      catch (IOException ioe)
331
      {
332
        MetaCatUtil.debugMessage("IO error in DBQuery.findDocuments:", 30);
333
        MetaCatUtil.debugMessage(ioe.getMessage(), 30);
334

    
335
      }
336
      catch (SQLException e)
337
      {
338
        MetaCatUtil.debugMessage("SQL Error in DBQuery.findDocuments: "
339
                                 + e.getMessage(), 30);
340
      }
341
      catch (Exception ee)
342
      {
343
        MetaCatUtil.debugMessage("Exception in DBQuery.findDocuments: "
344
                                 + ee.getMessage(), 30);
345
      }
346
      finally
347
      {
348
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
349
      } //finally
350
    }//if
351
    String closeRestultset = "</resultset>";
352
    resultset.append(closeRestultset);
353
    if (out != null)
354
    {
355
      out.println(closeRestultset);
356
    }
357

    
358
    return resultset;
359
  }//createResultDocuments
360

    
361

    
362

    
363
    /*
364
     * Find the doc list which match the query
365
     */
366
    private StringBuffer findResultDoclist(QuerySpecification qspec,
367
                                      StringBuffer resultsetBuffer,
368
                                      PrintWriter out,
369
                                      String user, String[]groups,
370
                                      DBConnection dbconn, boolean useXMLIndex )
371
                                      throws Exception
372
    {
373
      int offset = 1;
374
      // this is a hack for offset
375
      if (out == null)
376
      {
377
        // for html page, we put everything into one page
378
        offset = 500000;
379
      }
380
      else
381
      {
382
          offset =
383
              (new Integer(MetaCatUtil.getOption("resultsetsize"))).intValue();
384
      }
385
      int count = 0;
386
      int index = 0;
387
      Hashtable docListResult = new Hashtable();
388
      PreparedStatement pstmt = null;
389
      String docid = null;
390
      String docname = null;
391
      String doctype = null;
392
      String createDate = null;
393
      String updateDate = null;
394
      StringBuffer document = null;
395
      int rev = 0;
396
      String query = qspec.printSQL(useXMLIndex);
397
      String ownerQuery = getOwnerQuery(user);
398
      MetaCatUtil.debugMessage("query: " + query, 30);
399
      //MetaCatUtil.debugMessage("query: "+ownerQuery, 30);
400
      // if query is not the owner query, we need to check the permission
401
      // otherwise we don't need (owner has all permission by default)
402
      if (!query.equals(ownerQuery))
403
      {
404
        // set user name and group
405
        qspec.setUserName(user);
406
        qspec.setGroup(groups);
407
        // Get access query
408
        String accessQuery = qspec.getAccessQuery();
409
        query = query + accessQuery;
410
        MetaCatUtil.debugMessage(" final query: " + query, 30);
411
      }
412

    
413
      double startTime = System.currentTimeMillis() / 1000;
414
      pstmt = dbconn.prepareStatement(query);
415

    
416
      // Execute the SQL query using the JDBC connection
417
      pstmt.execute();
418
      ResultSet rs = pstmt.getResultSet();
419
      double queryExecuteTime = System.currentTimeMillis() / 1000;
420
      MetaCatUtil.debugMessage("Time for execute query: "
421
                    + (queryExecuteTime - startTime), 30);
422
      boolean tableHasRows = rs.next();
423
      while (tableHasRows)
424
      {
425
        docid = rs.getString(1).trim();
426
        docname = rs.getString(2);
427
        doctype = rs.getString(3);
428
        createDate = rs.getString(4);
429
        updateDate = rs.getString(5);
430
        rev = rs.getInt(6);
431

    
432
        // if there are returndocs to match, backtracking can be performed
433
        // otherwise, just return the document that was hit
434
        Vector returndocVec = qspec.getReturnDocList();
435
         if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
436
                        && !qspec.isPercentageSearch())
437
        {
438
           MetaCatUtil.debugMessage("Back tracing now...", 20);
439
           String sep = MetaCatUtil.getOption("accNumSeparator");
440
           StringBuffer btBuf = new StringBuffer();
441
           btBuf.append("select docid from xml_relation where ");
442

    
443
           //build the doctype list for the backtracking sql statement
444
           btBuf.append("packagetype in (");
445
           for (int i = 0; i < returndocVec.size(); i++)
446
           {
447
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
448
             if (i != (returndocVec.size() - 1))
449
             {
450
                btBuf.append(", ");
451
              }
452
            }
453
            btBuf.append(") ");
454
            btBuf.append("and (subject like '");
455
            btBuf.append(docid).append("'");
456
            btBuf.append("or object like '");
457
            btBuf.append(docid).append("')");
458

    
459
            PreparedStatement npstmt = dbconn.prepareStatement(btBuf.toString());
460
            //should incease usage count
461
            dbconn.increaseUsageCount(1);
462
            npstmt.execute();
463
            ResultSet btrs = npstmt.getResultSet();
464
            boolean hasBtRows = btrs.next();
465
            while (hasBtRows)
466
            {
467
               //there was a backtrackable document found
468
               DocumentImpl xmldoc = null;
469
               String packageDocid = btrs.getString(1);
470
               MetaCatUtil.debugMessage("Getting document for docid: "
471
                                         + packageDocid, 40);
472
                try
473
                {
474
                    //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not
475
                    // needed here
476
                    // xmldoc = new DocumentImpl(dbconn, packageDocid);
477
                    //  thus use the following to get the doc info only
478
                    //  xmldoc = new DocumentImpl(dbconn);
479
                    xmldoc = new DocumentImpl(packageDocid, false);
480
                    if (xmldoc == null)
481
                    {
482
                       MetaCatUtil.debugMessage("Document was null for: "
483
                                                + packageDocid, 50);
484
                    }
485
                }
486
                catch (Exception e)
487
                {
488
                    System.out.println("Error getting document in "
489
                                       + "DBQuery.findDocuments: "
490
                                       + e.getMessage());
491
                }
492

    
493
                String docid_org = xmldoc.getDocID();
494
                if (docid_org == null)
495
                {
496
                   MetaCatUtil.debugMessage("Docid_org was null.", 40);
497
                   //continue;
498
                }
499
                docid = docid_org.trim();
500
                docname = xmldoc.getDocname();
501
                doctype = xmldoc.getDoctype();
502
                createDate = xmldoc.getCreateDate();
503
                updateDate = xmldoc.getUpdateDate();
504
                rev = xmldoc.getRev();
505
                document = new StringBuffer();
506

    
507
                String completeDocid = docid
508
                                + MetaCatUtil.getOption("accNumSeparator");
509
                completeDocid += rev;
510
                document.append("<docid>").append(completeDocid);
511
                document.append("</docid>");
512
                if (docname != null)
513
                {
514
                  document.append("<docname>" + docname + "</docname>");
515
                }
516
                if (doctype != null)
517
                {
518
                  document.append("<doctype>" + doctype + "</doctype>");
519
                }
520
                if (createDate != null)
521
                {
522
                 document.append("<createdate>" + createDate + "</createdate>");
523
                }
524
                if (updateDate != null)
525
                {
526
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
527
                }
528
                // Store the document id and the root node id
529
                docListResult.put(docid, (String) document.toString());
530
                count++;
531

    
532

    
533
                // Get the next package document linked to our hit
534
                hasBtRows = btrs.next();
535
              }//while
536
              npstmt.close();
537
              btrs.close();
538
        }
539
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
540
        {
541

    
542
           document = new StringBuffer();
543

    
544
           String completeDocid = docid
545
                            + MetaCatUtil.getOption("accNumSeparator");
546
           completeDocid += rev;
547
           document.append("<docid>").append(completeDocid).append("</docid>");
548
           if (docname != null)
549
           {
550
               document.append("<docname>" + docname + "</docname>");
551
            }
552
            if (doctype != null)
553
            {
554
               document.append("<doctype>" + doctype + "</doctype>");
555
            }
556
            if (createDate != null)
557
            {
558
                document.append("<createdate>" + createDate + "</createdate>");
559
             }
560
             if (updateDate != null)
561
             {
562
               document.append("<updatedate>" + updateDate + "</updatedate>");
563
             }
564
              // Store the document id and the root node id
565
              docListResult.put(docid, (String) document.toString());
566
              count++;
567

    
568

    
569
        }//else
570
        // when doclist reached the offset number, send out doc list and empty
571
        // the hash table
572
        if (count == offset)
573
        {
574
          //reset count
575
          count = 0;
576
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
577
                              user, groups,dbconn, useXMLIndex);
578
          // reset docListResult
579
          docListResult = new Hashtable();
580

    
581
        }
582
       // Advance to the next record in the cursor
583
       tableHasRows = rs.next();
584
     }//while
585
     rs.close();
586
     pstmt.close();
587
     //if docListResult is not empty, it need to be sent.
588
     if (!docListResult.isEmpty())
589
     {
590
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
591
                              user, groups,dbconn, useXMLIndex);
592
     }
593
     double docListTime = System.currentTimeMillis() / 1000;
594
     MetaCatUtil.debugMessage("prepare docid list time: "
595
                    + (docListTime - queryExecuteTime), 30);
596

    
597
     return resultsetBuffer;
598
    }//findReturnDoclist
599

    
600

    
601
    /*
602
     * Send completed search hashtable(part of reulst)to output stream
603
     * and buffer into a buffer stream
604
     */
605
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
606
                                           StringBuffer resultset,
607
                                           PrintWriter out, Hashtable partOfDoclist,
608
                                           String user, String[]groups,
609
                                       DBConnection dbconn, boolean useXMLIndex)
610
                                       throws Exception
611
   {
612
     //add return field
613
     partOfDoclist = addRetrunfield(partOfDoclist, qspec, user, groups,
614
                                        dbconn, useXMLIndex );
615
     //add relationship part part docid list
616
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
617
     // send the completed search item to output and store it in a buffer
618
     String key = null;
619
     String element = null;
620
     Enumeration keys = partOfDoclist.keys();
621
     while (keys.hasMoreElements())
622
     {
623
           key = (String) keys.nextElement();
624
           element = (String)partOfDoclist.get(key);
625
           // A string with element
626
           String xmlElement = "  <document>" + element + "</document>";
627
           //send single element to output
628
           if (out != null)
629
           {
630
             out.println(xmlElement);
631
           }
632
           resultset.append(xmlElement);
633
      }//while
634

    
635
      return resultset;
636
   }
637

    
638

    
639
    /*
640
     * A method to add return field to return doclist hash table
641
     */
642
    private Hashtable addRetrunfield(Hashtable docListResult,
643
                                      QuerySpecification qspec,
644
                                      String user, String[]groups,
645
                                      DBConnection dbconn, boolean useXMLIndex )
646
                                      throws Exception
647
    {
648
      PreparedStatement pstmt = null;
649
      ResultSet rs = null;
650
      String docid = null;
651
      String fieldname = null;
652
      String fielddata = null;
653
      String relation = null;
654

    
655
      if (qspec.containsExtendedSQL())
656
      {
657
        qspec.setUserName(user);
658
        qspec.setGroup(groups);
659
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
660
        Vector results = new Vector();
661
        Enumeration keylist = docListResult.keys();
662
        StringBuffer doclist = new StringBuffer();
663
        Vector parentidList = new Vector();
664
        Hashtable returnFieldValue = new Hashtable();
665
        while (keylist.hasMoreElements())
666
        {
667
          doclist.append("'");
668
          doclist.append((String) keylist.nextElement());
669
          doclist.append("',");
670
        }
671
        if (doclist.length() > 0)
672
        {
673
          Hashtable controlPairs = new Hashtable();
674
          double extendedQueryStart = System.currentTimeMillis() / 1000;
675
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
676
          // check if user has permission to see the return field data
677
          String accessControlSQL =
678
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
679
          pstmt = dbconn.prepareStatement(accessControlSQL);
680
          //increase dbconnection usage count
681
          dbconn.increaseUsageCount(1);
682
          pstmt.execute();
683
          rs = pstmt.getResultSet();
684
          boolean tableHasRows = rs.next();
685
          while (tableHasRows)
686
          {
687
            long startNodeId = rs.getLong(1);
688
            long endNodeId = rs.getLong(2);
689
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
690
            tableHasRows = rs.next();
691
          }
692

    
693
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
694
           MetaCatUtil.debugMessage( "Time for execute access extended query: "
695
                          + (extendedAccessQueryEnd - extendedQueryStart),30);
696

    
697
           String extendedQuery =
698
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
699
           MetaCatUtil.debugMessage("Extended query: " + extendedQuery, 30);
700
           pstmt = dbconn.prepareStatement(extendedQuery);
701
           //increase dbconnection usage count
702
           dbconn.increaseUsageCount(1);
703
           pstmt.execute();
704
           rs = pstmt.getResultSet();
705
           double extendedQueryEnd = System.currentTimeMillis() / 1000;
706
           MetaCatUtil.debugMessage("Time for execute extended query: "
707
                           + (extendedQueryEnd - extendedQueryStart), 30);
708
           tableHasRows = rs.next();
709
           while (tableHasRows)
710
           {
711
               ReturnFieldValue returnValue = new ReturnFieldValue();
712
               docid = rs.getString(1).trim();
713
               fieldname = rs.getString(2);
714
               fielddata = rs.getString(3);
715
               fielddata = MetaCatUtil.normalize(fielddata);
716
               String parentId = rs.getString(4);
717
               StringBuffer value = new StringBuffer();
718
               if (!containsKey(parentidList, parentId))
719
               {
720
                  // don't need to merger nodedata
721
                  value.append("<param name=\"");
722
                  value.append(fieldname);
723
                  value.append("\">");
724
                  value.append(fielddata);
725
                  value.append("</param>");
726
                  //set returnvalue
727
                  returnValue.setDocid(docid);
728
                  returnValue.setFieldValue(fielddata);
729
                  returnValue.setXMLFieldValue(value.toString());
730
                  // Store it in hastable
731
                  putInArray(parentidList, parentId, returnValue);
732
                }
733
                else
734
                {
735
                  // need to merge nodedata if they have same parent id and
736
                  // node type is text
737
                  fielddata = (String) ((ReturnFieldValue) getArrayValue(
738
                                    parentidList, parentId)).getFieldValue()
739
                                    + fielddata;
740
                  value.append("<param name=\"");
741
                  value.append(fieldname);
742
                  value.append("\">");
743
                  value.append(fielddata);
744
                  value.append("</param>");
745
                  returnValue.setDocid(docid);
746
                  returnValue.setFieldValue(fielddata);
747
                  returnValue.setXMLFieldValue(value.toString());
748
                  // remove the old return value from paretnidList
749
                  parentidList.remove(parentId);
750
                  // store the new return value in parentidlit
751
                  putInArray(parentidList, parentId, returnValue);
752
                }
753
              tableHasRows = rs.next();
754
            }//while
755
            rs.close();
756
            pstmt.close();
757

    
758
            // put the merger node data info into doclistReult
759
            Enumeration xmlFieldValue = (getElements(parentidList)).elements();
760
            while (xmlFieldValue.hasMoreElements())
761
            {
762
              ReturnFieldValue object =
763
                  (ReturnFieldValue) xmlFieldValue.nextElement();
764
              docid = object.getDocid();
765
              if (docListResult.containsKey(docid))
766
              {
767
                 String removedelement = (String) docListResult.remove(docid);
768
                 docListResult.
769
                         put(docid, removedelement+ object.getXMLFieldValue());
770
              }
771
              else
772
              {
773
                docListResult.put(docid, object.getXMLFieldValue());
774
               }
775
             }//while
776
             double docListResultEnd = System.currentTimeMillis() / 1000;
777
             MetaCatUtil.debugMessage("Time for prepare doclistresult after"
778
                                       + " execute extended query: "
779
                                       + (docListResultEnd - extendedQueryEnd),
780
                                      30);
781

    
782
              // get attribures return
783
              docListResult = getAttributeValueForReturn(qspec,
784
                            docListResult, doclist.toString(), useXMLIndex);
785
       }//if doclist lenght is great than zero
786

    
787
     }//if has extended query
788

    
789
      return docListResult;
790
    }//addReturnfield
791

    
792
    /*
793
    * A method to add relationship to return doclist hash table
794
    */
795
   private Hashtable addRelationship(Hashtable docListResult,
796
                                     QuerySpecification qspec,
797
                                     DBConnection dbconn, boolean useXMLIndex )
798
                                     throws Exception
799
  {
800
    PreparedStatement pstmt = null;
801
    ResultSet rs = null;
802
    StringBuffer document = null;
803
    double startRelation = System.currentTimeMillis() / 1000;
804
    Enumeration docidkeys = docListResult.keys();
805
    while (docidkeys.hasMoreElements())
806
    {
807
      //String connstring =
808
      // "metacat://"+util.getOption("server")+"?docid=";
809
      String connstring = "%docid=";
810
      String docidkey = (String) docidkeys.nextElement();
811
      pstmt = dbconn.prepareStatement(QuerySpecification
812
                      .printRelationSQL(docidkey));
813
      pstmt.execute();
814
      rs = pstmt.getResultSet();
815
      boolean tableHasRows = rs.next();
816
      while (tableHasRows)
817
      {
818
        String sub = rs.getString(1);
819
        String rel = rs.getString(2);
820
        String obj = rs.getString(3);
821
        String subDT = rs.getString(4);
822
        String objDT = rs.getString(5);
823

    
824
        document = new StringBuffer();
825
        document.append("<triple>");
826
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
827
        document.append("</subject>");
828
        if (subDT != null)
829
        {
830
          document.append("<subjectdoctype>").append(subDT);
831
          document.append("</subjectdoctype>");
832
        }
833
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
834
        document.append("</relationship>");
835
        document.append("<object>").append(MetaCatUtil.normalize(obj));
836
        document.append("</object>");
837
        if (objDT != null)
838
        {
839
          document.append("<objectdoctype>").append(objDT);
840
          document.append("</objectdoctype>");
841
        }
842
        document.append("</triple>");
843

    
844
        String removedelement = (String) docListResult.remove(docidkey);
845
        docListResult.put(docidkey, removedelement+ document.toString());
846
        tableHasRows = rs.next();
847
      }//while
848
      rs.close();
849
      pstmt.close();
850
    }//while
851
    double endRelation = System.currentTimeMillis() / 1000;
852
    MetaCatUtil.debugMessage("Time for adding relation to docListResult: "
853
                             + (endRelation - startRelation), 30);
854

    
855
    return docListResult;
856
  }//addRelation
857

    
858
  /**
859
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
860
   * string as a param instead of a hashtable.
861
   *
862
   * @param xmlquery a string representing a query.
863
   */
864
   private  String transformQuery(String xmlquery)
865
   {
866
     xmlquery = xmlquery.trim();
867
     int index = xmlquery.indexOf("?>");
868
     if (index != -1)
869
     {
870
       return xmlquery.substring(index + 2, xmlquery.length());
871
     }
872
     else
873
     {
874
       return xmlquery;
875
     }
876
   }
877

    
878

    
879
    /*
880
     * A method to search if Vector contains a particular key string
881
     */
882
    private boolean containsKey(Vector parentidList, String parentId)
883
    {
884

    
885
        Vector tempVector = null;
886

    
887
        for (int count = 0; count < parentidList.size(); count++) {
888
            tempVector = (Vector) parentidList.get(count);
889
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
890
        }
891
        return false;
892
    }
893

    
894
    /*
895
     * A method to put key and value in Vector
896
     */
897
    private void putInArray(Vector parentidList, String key,
898
            ReturnFieldValue value)
899
    {
900

    
901
        Vector tempVector = null;
902

    
903
        for (int count = 0; count < parentidList.size(); count++) {
904
            tempVector = (Vector) parentidList.get(count);
905

    
906
            if (key.compareTo((String) tempVector.get(0)) == 0) {
907
                tempVector.remove(1);
908
                tempVector.add(1, value);
909
                return;
910
            }
911
        }
912

    
913
        tempVector = new Vector();
914
        tempVector.add(0, key);
915
        tempVector.add(1, value);
916
        parentidList.add(tempVector);
917
        return;
918
    }
919

    
920
    /*
921
     * A method to get value in Vector given a key
922
     */
923
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
924
    {
925

    
926
        Vector tempVector = null;
927

    
928
        for (int count = 0; count < parentidList.size(); count++) {
929
            tempVector = (Vector) parentidList.get(count);
930

    
931
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
932
                    .get(1); }
933
        }
934
        return null;
935
    }
936

    
937
    /*
938
     * A method to get enumeration of all values in Vector
939
     */
940
    private Vector getElements(Vector parentidList)
941
    {
942
        Vector enum = new Vector();
943
        Vector tempVector = null;
944

    
945
        for (int count = 0; count < parentidList.size(); count++) {
946
            tempVector = (Vector) parentidList.get(count);
947

    
948
            enum.add(tempVector.get(1));
949
        }
950
        return enum;
951
    }
952

    
953
    /*
954
     * A method to return search result after running a query which return
955
     * field have attribue
956
     */
957
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
958
            Hashtable docInformationList, String docList, boolean useXMLIndex)
959
    {
960
        StringBuffer XML = null;
961
        String sql = null;
962
        DBConnection dbconn = null;
963
        PreparedStatement pstmt = null;
964
        ResultSet rs = null;
965
        int serialNumber = -1;
966
        boolean tableHasRows = false;
967

    
968
        //check the parameter
969
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
970

    
971
        // if has attribute as return field
972
        if (squery.containAttributeReturnField()) {
973
            sql = squery.printAttributeQuery(docList, useXMLIndex);
974
            try {
975
                dbconn = DBConnectionPool
976
                        .getDBConnection("DBQuery.getAttributeValue");
977
                serialNumber = dbconn.getCheckOutSerialNumber();
978
                pstmt = dbconn.prepareStatement(sql);
979
                pstmt.execute();
980
                rs = pstmt.getResultSet();
981
                tableHasRows = rs.next();
982
                while (tableHasRows) {
983
                    String docid = rs.getString(1).trim();
984
                    String fieldname = rs.getString(2);
985
                    String fielddata = rs.getString(3);
986
                    String attirbuteName = rs.getString(4);
987
                    XML = new StringBuffer();
988

    
989
                    XML.append("<param name=\"");
990
                    XML.append(fieldname);
991
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
992
                    XML.append(attirbuteName);
993
                    XML.append("\">");
994
                    XML.append(fielddata);
995
                    XML.append("</param>");
996
                    tableHasRows = rs.next();
997

    
998
                    if (docInformationList.containsKey(docid)) {
999
                        String removedelement = (String) docInformationList
1000
                                .remove(docid);
1001
                        docInformationList.put(docid, removedelement
1002
                                + XML.toString());
1003
                    } else {
1004
                        docInformationList.put(docid, XML.toString());
1005
                    }
1006
                }//while
1007
                rs.close();
1008
                pstmt.close();
1009
            } catch (Exception se) {
1010
                MetaCatUtil.debugMessage(
1011
                        "Error in DBQuery.getAttributeValue1: "
1012
                                + se.getMessage(), 30);
1013
            } finally {
1014
                try {
1015
                    pstmt.close();
1016
                }//try
1017
                catch (SQLException sqlE) {
1018
                    MetaCatUtil.debugMessage(
1019
                            "Error in DBQuery.getAttributeValue2: "
1020
                                    + sqlE.getMessage(), 30);
1021
                }//catch
1022
                finally {
1023
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
1024
                }//finally
1025
            }//finally
1026
        }//if
1027
        return docInformationList;
1028

    
1029
    }
1030

    
1031
    /*
1032
     * A method to create a query to get owner's docid list
1033
     */
1034
    private String getOwnerQuery(String owner)
1035
    {
1036
        if (owner != null) {
1037
            owner = owner.toLowerCase();
1038
        }
1039
        StringBuffer self = new StringBuffer();
1040

    
1041
        self.append("SELECT docid,docname,doctype,");
1042
        self.append("date_created, date_updated, rev ");
1043
        self.append("FROM xml_documents WHERE docid IN (");
1044
        self.append("(");
1045
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1046
        self.append("nodedata LIKE '%%%' ");
1047
        self.append(") \n");
1048
        self.append(") ");
1049
        self.append(" AND (");
1050
        self.append(" lower(user_owner) = '" + owner + "'");
1051
        self.append(") ");
1052
        return self.toString();
1053
    }
1054

    
1055
    /**
1056
     * format a structured query as an XML document that conforms to the
1057
     * pathquery.dtd and is appropriate for submission to the DBQuery
1058
     * structured query engine
1059
     *
1060
     * @param params The list of parameters that should be included in the
1061
     *            query
1062
     */
1063
    public static String createSQuery(Hashtable params)
1064
    {
1065
        StringBuffer query = new StringBuffer();
1066
        Enumeration elements;
1067
        Enumeration keys;
1068
        String filterDoctype = null;
1069
        String casesensitive = null;
1070
        String searchmode = null;
1071
        Object nextkey;
1072
        Object nextelement;
1073
        //add the xml headers
1074
        query.append("<?xml version=\"1.0\"?>\n");
1075
        query.append("<pathquery version=\"1.2\">\n");
1076

    
1077

    
1078

    
1079
        if (params.containsKey("meta_file_id")) {
1080
            query.append("<meta_file_id>");
1081
            query.append(((String[]) params.get("meta_file_id"))[0]);
1082
            query.append("</meta_file_id>");
1083
        }
1084

    
1085
        if (params.containsKey("returndoctype")) {
1086
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1087
            for (int i = 0; i < returnDoctypes.length; i++) {
1088
                String doctype = (String) returnDoctypes[i];
1089

    
1090
                if (!doctype.equals("any") && !doctype.equals("ANY")
1091
                        && !doctype.equals("")) {
1092
                    query.append("<returndoctype>").append(doctype);
1093
                    query.append("</returndoctype>");
1094
                }
1095
            }
1096
        }
1097

    
1098
        if (params.containsKey("filterdoctype")) {
1099
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1100
            for (int i = 0; i < filterDoctypes.length; i++) {
1101
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1102
                query.append("</filterdoctype>");
1103
            }
1104
        }
1105

    
1106
        if (params.containsKey("returnfield")) {
1107
            String[] returnfield = ((String[]) params.get("returnfield"));
1108
            for (int i = 0; i < returnfield.length; i++) {
1109
                query.append("<returnfield>").append(returnfield[i]);
1110
                query.append("</returnfield>");
1111
            }
1112
        }
1113

    
1114
        if (params.containsKey("owner")) {
1115
            String[] owner = ((String[]) params.get("owner"));
1116
            for (int i = 0; i < owner.length; i++) {
1117
                query.append("<owner>").append(owner[i]);
1118
                query.append("</owner>");
1119
            }
1120
        }
1121

    
1122
        if (params.containsKey("site")) {
1123
            String[] site = ((String[]) params.get("site"));
1124
            for (int i = 0; i < site.length; i++) {
1125
                query.append("<site>").append(site[i]);
1126
                query.append("</site>");
1127
            }
1128
        }
1129

    
1130
        //allows the dynamic switching of boolean operators
1131
        if (params.containsKey("operator")) {
1132
            query.append("<querygroup operator=\""
1133
                    + ((String[]) params.get("operator"))[0] + "\">");
1134
        } else { //the default operator is UNION
1135
            query.append("<querygroup operator=\"UNION\">");
1136
        }
1137

    
1138
        if (params.containsKey("casesensitive")) {
1139
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1140
        } else {
1141
            casesensitive = "false";
1142
        }
1143

    
1144
        if (params.containsKey("searchmode")) {
1145
            searchmode = ((String[]) params.get("searchmode"))[0];
1146
        } else {
1147
            searchmode = "contains";
1148
        }
1149

    
1150
        //anyfield is a special case because it does a
1151
        //free text search. It does not have a <pathexpr>
1152
        //tag. This allows for a free text search within the structured
1153
        //query. This is useful if the INTERSECT operator is used.
1154
        if (params.containsKey("anyfield")) {
1155
            String[] anyfield = ((String[]) params.get("anyfield"));
1156
            //allow for more than one value for anyfield
1157
            for (int i = 0; i < anyfield.length; i++) {
1158
                if (!anyfield[i].equals("")) {
1159
                    query.append("<queryterm casesensitive=\"" + casesensitive
1160
                            + "\" " + "searchmode=\"" + searchmode
1161
                            + "\"><value>" + anyfield[i]
1162
                            + "</value></queryterm>");
1163
                }
1164
            }
1165
        }
1166

    
1167
        //this while loop finds the rest of the parameters
1168
        //and attempts to query for the field specified
1169
        //by the parameter.
1170
        elements = params.elements();
1171
        keys = params.keys();
1172
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1173
            nextkey = keys.nextElement();
1174
            nextelement = elements.nextElement();
1175

    
1176
            //make sure we aren't querying for any of these
1177
            //parameters since the are already in the query
1178
            //in one form or another.
1179
            Vector ignoredParams = new Vector();
1180
            ignoredParams.add("returndoctype");
1181
            ignoredParams.add("filterdoctype");
1182
            ignoredParams.add("action");
1183
            ignoredParams.add("qformat");
1184
            ignoredParams.add("anyfield");
1185
            ignoredParams.add("returnfield");
1186
            ignoredParams.add("owner");
1187
            ignoredParams.add("site");
1188
            ignoredParams.add("operator");
1189
            ignoredParams.add("sessionid");
1190

    
1191
            // Also ignore parameters listed in the properties file
1192
            // so that they can be passed through to stylesheets
1193
            String paramsToIgnore = MetaCatUtil
1194
                    .getOption("query.ignored.params");
1195
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1196
            while (st.hasMoreTokens()) {
1197
                ignoredParams.add(st.nextToken());
1198
            }
1199
            if (!ignoredParams.contains(nextkey.toString())) {
1200
                //allow for more than value per field name
1201
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1202
                    if (!((String[]) nextelement)[i].equals("")) {
1203
                        query.append("<queryterm casesensitive=\""
1204
                                + casesensitive + "\" " + "searchmode=\""
1205
                                + searchmode + "\">" + "<value>" +
1206
                                //add the query value
1207
                                ((String[]) nextelement)[i]
1208
                                + "</value><pathexpr>" +
1209
                                //add the path to query by
1210
                                nextkey.toString() + "</pathexpr></queryterm>");
1211
                    }
1212
                }
1213
            }
1214
        }
1215
        query.append("</querygroup></pathquery>");
1216
        //append on the end of the xml and return the result as a string
1217
        return query.toString();
1218
    }
1219

    
1220
    /**
1221
     * format a simple free-text value query as an XML document that conforms
1222
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1223
     * structured query engine
1224
     *
1225
     * @param value the text string to search for in the xml catalog
1226
     * @param doctype the type of documents to include in the result set -- use
1227
     *            "any" or "ANY" for unfiltered result sets
1228
     */
1229
    public static String createQuery(String value, String doctype)
1230
    {
1231
        StringBuffer xmlquery = new StringBuffer();
1232
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1233
        xmlquery.append("<pathquery version=\"1.0\">");
1234

    
1235
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1236
            xmlquery.append("<returndoctype>");
1237
            xmlquery.append(doctype).append("</returndoctype>");
1238
        }
1239

    
1240
        xmlquery.append("<querygroup operator=\"UNION\">");
1241
        //chad added - 8/14
1242
        //the if statement allows a query to gracefully handle a null
1243
        //query. Without this if a nullpointerException is thrown.
1244
        if (!value.equals("")) {
1245
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1246
            xmlquery.append("searchmode=\"contains\">");
1247
            xmlquery.append("<value>").append(value).append("</value>");
1248
            xmlquery.append("</queryterm>");
1249
        }
1250
        xmlquery.append("</querygroup>");
1251
        xmlquery.append("</pathquery>");
1252

    
1253
        return (xmlquery.toString());
1254
    }
1255

    
1256
    /**
1257
     * format a simple free-text value query as an XML document that conforms
1258
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1259
     * structured query engine
1260
     *
1261
     * @param value the text string to search for in the xml catalog
1262
     */
1263
    public static String createQuery(String value)
1264
    {
1265
        return createQuery(value, "any");
1266
    }
1267

    
1268
    /**
1269
     * Check for "READ" permission on @docid for @user and/or @group from DB
1270
     * connection
1271
     */
1272
    private boolean hasPermission(String user, String[] groups, String docid)
1273
            throws SQLException, Exception
1274
    {
1275
        // Check for READ permission on @docid for @user and/or @groups
1276
        PermissionController controller = new PermissionController(docid);
1277
        return controller.hasPermission(user, groups,
1278
                AccessControlInterface.READSTRING);
1279
    }
1280

    
1281
    /**
1282
     * Get all docIds list for a data packadge
1283
     *
1284
     * @param dataPackageDocid, the string in docId field of xml_relation table
1285
     */
1286
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1287
    {
1288
        DBConnection dbConn = null;
1289
        int serialNumber = -1;
1290
        Vector docIdList = new Vector();//return value
1291
        PreparedStatement pStmt = null;
1292
        ResultSet rs = null;
1293
        String docIdInSubjectField = null;
1294
        String docIdInObjectField = null;
1295

    
1296
        // Check the parameter
1297
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1298

    
1299
        //the query stirng
1300
        String query = "SELECT subject, object from xml_relation where docId = ?";
1301
        try {
1302
            dbConn = DBConnectionPool
1303
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1304
            serialNumber = dbConn.getCheckOutSerialNumber();
1305
            pStmt = dbConn.prepareStatement(query);
1306
            //bind the value to query
1307
            pStmt.setString(1, dataPackageDocid);
1308

    
1309
            //excute the query
1310
            pStmt.execute();
1311
            //get the result set
1312
            rs = pStmt.getResultSet();
1313
            //process the result
1314
            while (rs.next()) {
1315
                //In order to get the whole docIds in a data packadge,
1316
                //we need to put the docIds of subject and object field in
1317
                // xml_relation
1318
                //into the return vector
1319
                docIdInSubjectField = rs.getString(1);//the result docId in
1320
                                                      // subject field
1321
                docIdInObjectField = rs.getString(2);//the result docId in
1322
                                                     // object field
1323

    
1324
                //don't put the duplicate docId into the vector
1325
                if (!docIdList.contains(docIdInSubjectField)) {
1326
                    docIdList.add(docIdInSubjectField);
1327
                }
1328

    
1329
                //don't put the duplicate docId into the vector
1330
                if (!docIdList.contains(docIdInObjectField)) {
1331
                    docIdList.add(docIdInObjectField);
1332
                }
1333
            }//while
1334
            //close the pStmt
1335
            pStmt.close();
1336
        }//try
1337
        catch (SQLException e) {
1338
            MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1339
                    + e.getMessage(), 30);
1340
        }//catch
1341
        finally {
1342
            try {
1343
                pStmt.close();
1344
            }//try
1345
            catch (SQLException ee) {
1346
                MetaCatUtil.debugMessage(
1347
                        "Error in getDocidListForDataPackage: "
1348
                                + ee.getMessage(), 30);
1349
            }//catch
1350
            finally {
1351
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1352
            }//fianlly
1353
        }//finally
1354
        return docIdList;
1355
    }//getCurrentDocidListForDataPackadge()
1356

    
1357
    /**
1358
     * Get all docIds list for a data packadge
1359
     *
1360
     * @param dataPackageDocid, the string in docId field of xml_relation table
1361
     */
1362
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1363
    {
1364

    
1365
        Vector docIdList = new Vector();//return value
1366
        Vector tripleList = null;
1367
        String xml = null;
1368

    
1369
        // Check the parameter
1370
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1371

    
1372
        try {
1373
            //initial a documentImpl object
1374
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocid);
1375
            //transfer to documentImpl object to string
1376
            xml = packageDocument.toString();
1377

    
1378
            //create a tripcollection object
1379
            TripleCollection tripleForPackage = new TripleCollection(
1380
                    new StringReader(xml));
1381
            //get the vetor of triples
1382
            tripleList = tripleForPackage.getCollection();
1383

    
1384
            for (int i = 0; i < tripleList.size(); i++) {
1385
                //put subject docid into docIdlist without duplicate
1386
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1387
                        .getSubject())) {
1388
                    //put subject docid into docIdlist
1389
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1390
                }
1391
                //put object docid into docIdlist without duplicate
1392
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1393
                        .getObject())) {
1394
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1395
                }
1396
            }//for
1397
        }//try
1398
        catch (Exception e) {
1399
            MetaCatUtil.debugMessage("Error in getOldVersionAllDocumentImpl: "
1400
                    + e.getMessage(), 30);
1401
        }//catch
1402

    
1403
        // return result
1404
        return docIdList;
1405
    }//getDocidListForPackageInXMLRevisions()
1406

    
1407
    /**
1408
     * Check if the docId is a data packadge id. If the id is a data packadage
1409
     * id, it should be store in the docId fields in xml_relation table. So we
1410
     * can use a query to get the entries which the docId equals the given
1411
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1412
     * it is.
1413
     *
1414
     * @param docId, the id need to be checked
1415
     */
1416
    private boolean isDataPackageId(String docId)
1417
    {
1418
        boolean result = false;
1419
        PreparedStatement pStmt = null;
1420
        ResultSet rs = null;
1421
        String query = "SELECT docId from xml_relation where docId = ?";
1422
        DBConnection dbConn = null;
1423
        int serialNumber = -1;
1424
        try {
1425
            dbConn = DBConnectionPool
1426
                    .getDBConnection("DBQuery.isDataPackageId");
1427
            serialNumber = dbConn.getCheckOutSerialNumber();
1428
            pStmt = dbConn.prepareStatement(query);
1429
            //bind the value to query
1430
            pStmt.setString(1, docId);
1431
            //execute the query
1432
            pStmt.execute();
1433
            rs = pStmt.getResultSet();
1434
            //process the result
1435
            if (rs.next()) //There are some records for the id in docId fields
1436
            {
1437
                result = true;//It is a data packadge id
1438
            }
1439
            pStmt.close();
1440
        }//try
1441
        catch (SQLException e) {
1442
            MetaCatUtil.debugMessage("Error in isDataPackageId: "
1443
                    + e.getMessage(), 30);
1444
        } finally {
1445
            try {
1446
                pStmt.close();
1447
            }//try
1448
            catch (SQLException ee) {
1449
                MetaCatUtil.debugMessage("Error in isDataPackageId: "
1450
                        + ee.getMessage(), 30);
1451
            }//catch
1452
            finally {
1453
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1454
            }//finally
1455
        }//finally
1456
        return result;
1457
    }//isDataPackageId()
1458

    
1459
    /**
1460
     * Check if the user has the permission to export data package
1461
     *
1462
     * @param conn, the connection
1463
     * @param docId, the id need to be checked
1464
     * @param user, the name of user
1465
     * @param groups, the user's group
1466
     */
1467
    private boolean hasPermissionToExportPackage(String docId, String user,
1468
            String[] groups) throws Exception
1469
    {
1470
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1471
        return DocumentImpl.hasReadPermission(user, groups, docId);
1472
    }
1473

    
1474
    /**
1475
     * Get the current Rev for a docid in xml_documents table
1476
     *
1477
     * @param docId, the id need to get version numb If the return value is -5,
1478
     *            means no value in rev field for this docid
1479
     */
1480
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1481
            throws SQLException
1482
    {
1483
        int rev = -5;
1484
        PreparedStatement pStmt = null;
1485
        ResultSet rs = null;
1486
        String query = "SELECT rev from xml_documents where docId = ?";
1487
        DBConnection dbConn = null;
1488
        int serialNumber = -1;
1489
        try {
1490
            dbConn = DBConnectionPool
1491
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1492
            serialNumber = dbConn.getCheckOutSerialNumber();
1493
            pStmt = dbConn.prepareStatement(query);
1494
            //bind the value to query
1495
            pStmt.setString(1, docId);
1496
            //execute the query
1497
            pStmt.execute();
1498
            rs = pStmt.getResultSet();
1499
            //process the result
1500
            if (rs.next()) //There are some records for rev
1501
            {
1502
                rev = rs.getInt(1);
1503
                ;//It is the version for given docid
1504
            } else {
1505
                rev = -5;
1506
            }
1507

    
1508
        }//try
1509
        catch (SQLException e) {
1510
            MetaCatUtil.debugMessage(
1511
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1512
                            + e.getMessage(), 30);
1513
            throw e;
1514
        }//catch
1515
        finally {
1516
            try {
1517
                pStmt.close();
1518
            }//try
1519
            catch (SQLException ee) {
1520
                MetaCatUtil.debugMessage(
1521
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1522
                                + ee.getMessage(), 30);
1523
            }//catch
1524
            finally {
1525
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1526
            }//finally
1527
        }//finally
1528
        return rev;
1529
    }//getCurrentRevFromXMLDoumentsTable
1530

    
1531
    /**
1532
     * put a doc into a zip output stream
1533
     *
1534
     * @param docImpl, docmentImpl object which will be sent to zip output
1535
     *            stream
1536
     * @param zipOut, zip output stream which the docImpl will be put
1537
     * @param packageZipEntry, the zip entry name for whole package
1538
     */
1539
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1540
            ZipOutputStream zipOut, String packageZipEntry)
1541
            throws ClassNotFoundException, IOException, SQLException,
1542
            McdbException, Exception
1543
    {
1544
        byte[] byteString = null;
1545
        ZipEntry zEntry = null;
1546

    
1547
        byteString = docImpl.toString().getBytes();
1548
        //use docId as the zip entry's name
1549
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1550
                + docImpl.getDocID());
1551
        zEntry.setSize(byteString.length);
1552
        zipOut.putNextEntry(zEntry);
1553
        zipOut.write(byteString, 0, byteString.length);
1554
        zipOut.closeEntry();
1555

    
1556
    }//addDocToZipOutputStream()
1557

    
1558
    /**
1559
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1560
     * only inlcudes current version. If a DocumentImple object couldn't find
1561
     * for a docid, then the String of this docid was added to vetor rather
1562
     * than DocumentImple object.
1563
     *
1564
     * @param docIdList, a vetor hold a docid list for a data package. In
1565
     *            docid, there is not version number in it.
1566
     */
1567

    
1568
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1569
            throws McdbException, Exception
1570
    {
1571
        //Connection dbConn=null;
1572
        Vector documentImplList = new Vector();
1573
        int rev = 0;
1574

    
1575
        // Check the parameter
1576
        if (docIdList.isEmpty()) { return documentImplList; }//if
1577

    
1578
        //for every docid in vector
1579
        for (int i = 0; i < docIdList.size(); i++) {
1580
            try {
1581
                //get newest version for this docId
1582
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1583
                        .elementAt(i));
1584

    
1585
                // There is no record for this docId in xml_documents table
1586
                if (rev == -5) {
1587
                    // Rather than put DocumentImple object, put a String
1588
                    // Object(docid)
1589
                    // into the documentImplList
1590
                    documentImplList.add((String) docIdList.elementAt(i));
1591
                    // Skip other code
1592
                    continue;
1593
                }
1594

    
1595
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1596
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1597

    
1598
                //create new documentImpl object
1599
                DocumentImpl documentImplObject = new DocumentImpl(
1600
                        docidPlusVersion);
1601
                //add them to vector
1602
                documentImplList.add(documentImplObject);
1603
            }//try
1604
            catch (Exception e) {
1605
                MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1606
                        + e.getMessage(), 30);
1607
                // continue the for loop
1608
                continue;
1609
            }
1610
        }//for
1611
        return documentImplList;
1612
    }
1613

    
1614
    /**
1615
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
1616
     * object couldn't find for a docid, then the String of this docid was
1617
     * added to vetor rather than DocumentImple object.
1618
     *
1619
     * @param docIdList, a vetor hold a docid list for a data package. In
1620
     *            docid, t here is version number in it.
1621
     */
1622
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
1623
    {
1624
        //Connection dbConn=null;
1625
        Vector documentImplList = new Vector();
1626
        String siteCode = null;
1627
        String uniqueId = null;
1628
        int rev = 0;
1629

    
1630
        // Check the parameter
1631
        if (docIdList.isEmpty()) { return documentImplList; }//if
1632

    
1633
        //for every docid in vector
1634
        for (int i = 0; i < docIdList.size(); i++) {
1635

    
1636
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1637

    
1638
            try {
1639
                //create new documentImpl object
1640
                DocumentImpl documentImplObject = new DocumentImpl(
1641
                        docidPlusVersion);
1642
                //add them to vector
1643
                documentImplList.add(documentImplObject);
1644
            }//try
1645
            catch (McdbDocNotFoundException notFoundE) {
1646
                MetaCatUtil.debugMessage(
1647
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1648
                                + notFoundE.getMessage(), 30);
1649
                // Rather than add a DocumentImple object into vetor, a String
1650
                // object
1651
                // - the doicd was added to the vector
1652
                documentImplList.add(docidPlusVersion);
1653
                // Continue the for loop
1654
                continue;
1655
            }//catch
1656
            catch (Exception e) {
1657
                MetaCatUtil.debugMessage(
1658
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1659
                                + e.getMessage(), 30);
1660
                // Continue the for loop
1661
                continue;
1662
            }//catch
1663

    
1664
        }//for
1665
        return documentImplList;
1666
    }//getOldVersionAllDocumentImple
1667

    
1668
    /**
1669
     * put a data file into a zip output stream
1670
     *
1671
     * @param docImpl, docmentImpl object which will be sent to zip output
1672
     *            stream
1673
     * @param zipOut, the zip output stream which the docImpl will be put
1674
     * @param packageZipEntry, the zip entry name for whole package
1675
     */
1676
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
1677
            ZipOutputStream zipOut, String packageZipEntry)
1678
            throws ClassNotFoundException, IOException, SQLException,
1679
            McdbException, Exception
1680
    {
1681
        byte[] byteString = null;
1682
        ZipEntry zEntry = null;
1683
        // this is data file; add file to zip
1684
        String filePath = MetaCatUtil.getOption("datafilepath");
1685
        if (!filePath.endsWith("/")) {
1686
            filePath += "/";
1687
        }
1688
        String fileName = filePath + docImpl.getDocID();
1689
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
1690
        zipOut.putNextEntry(zEntry);
1691
        FileInputStream fin = null;
1692
        try {
1693
            fin = new FileInputStream(fileName);
1694
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1695
            int b = fin.read(buf);
1696
            while (b != -1) {
1697
                zipOut.write(buf, 0, b);
1698
                b = fin.read(buf);
1699
            }//while
1700
            zipOut.closeEntry();
1701
        }//try
1702
        catch (IOException ioe) {
1703
            MetaCatUtil.debugMessage("There is an exception: "
1704
                    + ioe.getMessage(), 30);
1705
        }//catch
1706
    }//addDataFileToZipOutputStream()
1707

    
1708
    /**
1709
     * create a html summary for data package and put it into zip output stream
1710
     *
1711
     * @param docImplList, the documentImpl ojbects in data package
1712
     * @param zipOut, the zip output stream which the html should be put
1713
     * @param packageZipEntry, the zip entry name for whole package
1714
     */
1715
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
1716
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
1717
    {
1718
        StringBuffer htmlDoc = new StringBuffer();
1719
        ZipEntry zEntry = null;
1720
        byte[] byteString = null;
1721
        InputStream source;
1722
        DBTransform xmlToHtml;
1723

    
1724
        //create a DBTransform ojbect
1725
        xmlToHtml = new DBTransform();
1726
        //head of html
1727
        htmlDoc.append("<html><head></head><body>");
1728
        for (int i = 0; i < docImplList.size(); i++) {
1729
            // If this String object, this means it is missed data file
1730
            if ((((docImplList.elementAt(i)).getClass()).toString())
1731
                    .equals("class java.lang.String")) {
1732

    
1733
                htmlDoc.append("<a href=\"");
1734
                String dataFileid = (String) docImplList.elementAt(i);
1735
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1736
                htmlDoc.append("Data File: ");
1737
                htmlDoc.append(dataFileid).append("</a><br>");
1738
                htmlDoc.append("<br><hr><br>");
1739

    
1740
            }//if
1741
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
1742
                    .compareTo("BIN") != 0) { //this is an xml file so we can
1743
                                              // transform it.
1744
                //transform each file individually then concatenate all of the
1745
                //transformations together.
1746

    
1747
                //for metadata xml title
1748
                htmlDoc.append("<h2>");
1749
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
1750
                        .getDocID());
1751
                //htmlDoc.append(".");
1752
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
1753
                htmlDoc.append("</h2>");
1754
                //do the actual transform
1755
                StringWriter docString = new StringWriter();
1756
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
1757
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
1758
                        "-//W3C//HTML//EN", "html", docString);
1759
                htmlDoc.append(docString.toString());
1760
                htmlDoc.append("<br><br><hr><br><br>");
1761
            }//if
1762
            else { //this is a data file so we should link to it in the html
1763
                htmlDoc.append("<a href=\"");
1764
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
1765
                        .getDocID();
1766
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1767
                htmlDoc.append("Data File: ");
1768
                htmlDoc.append(dataFileid).append("</a><br>");
1769
                htmlDoc.append("<br><hr><br>");
1770
            }//else
1771
        }//for
1772
        htmlDoc.append("</body></html>");
1773
        byteString = htmlDoc.toString().getBytes();
1774
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
1775
        zEntry.setSize(byteString.length);
1776
        zipOut.putNextEntry(zEntry);
1777
        zipOut.write(byteString, 0, byteString.length);
1778
        zipOut.closeEntry();
1779
        //dbConn.close();
1780

    
1781
    }//addHtmlSummaryToZipOutputStream
1782

    
1783
    /**
1784
     * put a data packadge into a zip output stream
1785
     *
1786
     * @param docId, which the user want to put into zip output stream
1787
     * @param out, a servletoutput stream which the zip output stream will be
1788
     *            put
1789
     * @param user, the username of the user
1790
     * @param groups, the group of the user
1791
     */
1792
    public ZipOutputStream getZippedPackage(String docIdString,
1793
            ServletOutputStream out, String user, String[] groups,
1794
            String passWord) throws ClassNotFoundException, IOException,
1795
            SQLException, McdbException, NumberFormatException, Exception
1796
    {
1797
        ZipOutputStream zOut = null;
1798
        String elementDocid = null;
1799
        DocumentImpl docImpls = null;
1800
        //Connection dbConn = null;
1801
        Vector docIdList = new Vector();
1802
        Vector documentImplList = new Vector();
1803
        Vector htmlDocumentImplList = new Vector();
1804
        String packageId = null;
1805
        String rootName = "package";//the package zip entry name
1806

    
1807
        String docId = null;
1808
        int version = -5;
1809
        // Docid without revision
1810
        docId = MetaCatUtil.getDocIdFromString(docIdString);
1811
        // revision number
1812
        version = MetaCatUtil.getVersionFromString(docIdString);
1813

    
1814
        //check if the reqused docId is a data package id
1815
        if (!isDataPackageId(docId)) {
1816

    
1817
            /*
1818
             * Exception e = new Exception("The request the doc id "
1819
             * +docIdString+ " is not a data package id");
1820
             */
1821

    
1822
            //CB 1/6/03: if the requested docid is not a datapackage, we just
1823
            // zip
1824
            //up the single document and return the zip file.
1825
            if (!hasPermissionToExportPackage(docId, user, groups)) {
1826

    
1827
                Exception e = new Exception("User " + user
1828
                        + " does not have permission"
1829
                        + " to export the data package " + docIdString);
1830
                throw e;
1831
            }
1832

    
1833
            docImpls = new DocumentImpl(docId);
1834
            //checking if the user has the permission to read the documents
1835
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
1836
                    .getDocID())) {
1837
                zOut = new ZipOutputStream(out);
1838
                //if the docImpls is metadata
1839
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
1840
                    //add metadata into zip output stream
1841
                    addDocToZipOutputStream(docImpls, zOut, rootName);
1842
                }//if
1843
                else {
1844
                    //it is data file
1845
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
1846
                    htmlDocumentImplList.add(docImpls);
1847
                }//else
1848
            }//if
1849

    
1850
            zOut.finish(); //terminate the zip file
1851
            return zOut;
1852
        }
1853
        // Check the permission of user
1854
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
1855

    
1856
            Exception e = new Exception("User " + user
1857
                    + " does not have permission"
1858
                    + " to export the data package " + docIdString);
1859
            throw e;
1860
        } else //it is a packadge id
1861
        {
1862
            //store the package id
1863
            packageId = docId;
1864
            //get current version in database
1865
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
1866
            //If it is for current version (-1 means user didn't specify
1867
            // revision)
1868
            if ((version == -1) || version == currentVersion) {
1869
                //get current version number
1870
                version = currentVersion;
1871
                //get package zip entry name
1872
                //it should be docId.revsion.package
1873
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
1874
                        + version + MetaCatUtil.getOption("accNumSeparator")
1875
                        + "package";
1876
                //get the whole id list for data packadge
1877
                docIdList = getCurrentDocidListForDataPackage(packageId);
1878
                //get the whole documentImple object
1879
                documentImplList = getCurrentAllDocumentImpl(docIdList);
1880

    
1881
            }//if
1882
            else if (version > currentVersion || version < -1) {
1883
                throw new Exception("The user specified docid: " + docId + "."
1884
                        + version + " doesn't exist");
1885
            }//else if
1886
            else //for an old version
1887
            {
1888

    
1889
                rootName = docIdString
1890
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
1891
                //get the whole id list for data packadge
1892
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
1893

    
1894
                //get the whole documentImple object
1895
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
1896
            }//else
1897

    
1898
            // Make sure documentImplist is not empty
1899
            if (documentImplList.isEmpty()) { throw new Exception(
1900
                    "Couldn't find component for data package: " + packageId); }//if
1901

    
1902
            zOut = new ZipOutputStream(out);
1903
            //put every element into zip output stream
1904
            for (int i = 0; i < documentImplList.size(); i++) {
1905
                // if the object in the vetor is String, this means we couldn't
1906
                // find
1907
                // the document locally, we need find it remote
1908
                if ((((documentImplList.elementAt(i)).getClass()).toString())
1909
                        .equals("class java.lang.String")) {
1910
                    // Get String object from vetor
1911
                    String documentId = (String) documentImplList.elementAt(i);
1912
                    MetaCatUtil.debugMessage("docid: " + documentId, 30);
1913
                    // Get doicd without revision
1914
                    String docidWithoutRevision = MetaCatUtil
1915
                            .getDocIdFromString(documentId);
1916
                    MetaCatUtil.debugMessage("docidWithoutRevsion: "
1917
                            + docidWithoutRevision, 30);
1918
                    // Get revision
1919
                    String revision = MetaCatUtil
1920
                            .getRevisionStringFromString(documentId);
1921
                    MetaCatUtil.debugMessage("revsion from docIdentifier: "
1922
                            + revision, 30);
1923
                    // Zip entry string
1924
                    String zipEntryPath = rootName + "/data/";
1925
                    // Create a RemoteDocument object
1926
                    RemoteDocument remoteDoc = new RemoteDocument(
1927
                            docidWithoutRevision, revision, user, passWord,
1928
                            zipEntryPath);
1929
                    // Here we only read data file from remote metacat
1930
                    String docType = remoteDoc.getDocType();
1931
                    if (docType != null) {
1932
                        if (docType.equals("BIN")) {
1933
                            // Put remote document to zip output
1934
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
1935
                            // Add String object to htmlDocumentImplList
1936
                            String elementInHtmlList = remoteDoc
1937
                                    .getDocIdWithoutRevsion()
1938
                                    + MetaCatUtil.getOption("accNumSeparator")
1939
                                    + remoteDoc.getRevision();
1940
                            htmlDocumentImplList.add(elementInHtmlList);
1941
                        }//if
1942
                    }//if
1943

    
1944
                }//if
1945
                else {
1946
                    //create a docmentImpls object (represent xml doc) base on
1947
                    // the docId
1948
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
1949
                    //checking if the user has the permission to read the
1950
                    // documents
1951
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
1952
                            .getDocID())) {
1953
                        //if the docImpls is metadata
1954
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
1955
                            //add metadata into zip output stream
1956
                            addDocToZipOutputStream(docImpls, zOut, rootName);
1957
                            //add the documentImpl into the vetor which will
1958
                            // be used in html
1959
                            htmlDocumentImplList.add(docImpls);
1960

    
1961
                        }//if
1962
                        else {
1963
                            //it is data file
1964
                            addDataFileToZipOutputStream(docImpls, zOut,
1965
                                    rootName);
1966
                            htmlDocumentImplList.add(docImpls);
1967
                        }//else
1968
                    }//if
1969
                }//else
1970
            }//for
1971

    
1972
            //add html summary file
1973
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
1974
                    rootName);
1975
            zOut.finish(); //terminate the zip file
1976
            //dbConn.close();
1977
            return zOut;
1978
        }//else
1979
    }//getZippedPackage()
1980

    
1981
    private class ReturnFieldValue
1982
    {
1983

    
1984
        private String docid = null; //return field value for this docid
1985

    
1986
        private String fieldValue = null;
1987

    
1988
        private String xmlFieldValue = null; //return field value in xml
1989
                                             // format
1990

    
1991
        public void setDocid(String myDocid)
1992
        {
1993
            docid = myDocid;
1994
        }
1995

    
1996
        public String getDocid()
1997
        {
1998
            return docid;
1999
        }
2000

    
2001
        public void setFieldValue(String myValue)
2002
        {
2003
            fieldValue = myValue;
2004
        }
2005

    
2006
        public String getFieldValue()
2007
        {
2008
            return fieldValue;
2009
        }
2010

    
2011
        public void setXMLFieldValue(String xml)
2012
        {
2013
            xmlFieldValue = xml;
2014
        }
2015

    
2016
        public String getXMLFieldValue()
2017
        {
2018
            return xmlFieldValue;
2019
        }
2020

    
2021
    }
2022
}
(22-22/63)