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-18 12:11:01 -0800 (Tue, 18 Jan 2005) $'
15
 * '$Revision: 2376 $'
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
        if(!query.endsWith("WHERE")){
410
            query = query + accessQuery;
411
        } else {
412
            query = query + accessQuery.substring(4, accessQuery.length());
413
        }
414
        MetaCatUtil.debugMessage(" final query: " + query, 30);
415
      }
416

    
417
      double startTime = System.currentTimeMillis() / 1000;
418
      pstmt = dbconn.prepareStatement(query);
419

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

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

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

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

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

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

    
536

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

    
546
           document = new StringBuffer();
547

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

    
572

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

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

    
601
     return resultsetBuffer;
602
    }//findReturnDoclist
603

    
604

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

    
639
      return resultset;
640
   }
641

    
642

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

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

    
697
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
698
           MetaCatUtil.debugMessage( "Time for execute access extended query: "
699
                          + (extendedAccessQueryEnd - extendedQueryStart),30);
700

    
701
           String extendedQuery =
702
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
703
           MetaCatUtil.debugMessage("Extended query: " + extendedQuery, 30);
704
           pstmt = dbconn.prepareStatement(extendedQuery);
705
           //increase dbconnection usage count
706
           dbconn.increaseUsageCount(1);
707
           pstmt.execute();
708
           rs = pstmt.getResultSet();
709
           double extendedQueryEnd = System.currentTimeMillis() / 1000;
710
           MetaCatUtil.debugMessage("Time for execute extended query: "
711
                           + (extendedQueryEnd - extendedQueryStart), 30);
712
           tableHasRows = rs.next();
713
           while (tableHasRows)
714
           {
715
               ReturnFieldValue returnValue = new ReturnFieldValue();
716
               docid = rs.getString(1).trim();
717
               fieldname = rs.getString(2);
718
               fielddata = rs.getString(3);
719
               fielddata = MetaCatUtil.normalize(fielddata);
720
               String parentId = rs.getString(4);
721
               StringBuffer value = new StringBuffer();
722

    
723
	       // if xml_index is used, there would be just one record per nodeid
724
	       // as xml_index just keeps one entry for each path
725
               if (useXMLIndex || !containsKey(parentidList, parentId))
726
               {
727
                  // don't need to merger nodedata
728
                  value.append("<param name=\"");
729
                  value.append(fieldname);
730
                  value.append("\">");
731
                  value.append(fielddata);
732
                  value.append("</param>");
733
                  //set returnvalue
734
                  returnValue.setDocid(docid);
735
                  returnValue.setFieldValue(fielddata);
736
                  returnValue.setXMLFieldValue(value.toString());
737
                  // Store it in hastable
738
                  putInArray(parentidList, parentId, returnValue);
739
                }
740
                else
741
                {
742
                  // need to merge nodedata if they have same parent id and
743
                  // node type is text
744
                  fielddata = (String) ((ReturnFieldValue) getArrayValue(
745
                                    parentidList, parentId)).getFieldValue()
746
                                    + fielddata;
747
                  value.append("<param name=\"");
748
                  value.append(fieldname);
749
                  value.append("\">");
750
                  value.append(fielddata);
751
                  value.append("</param>");
752
                  returnValue.setDocid(docid);
753
                  returnValue.setFieldValue(fielddata);
754
                  returnValue.setXMLFieldValue(value.toString());
755
                  // remove the old return value from paretnidList
756
                  parentidList.remove(parentId);
757
                  // store the new return value in parentidlit
758
                  putInArray(parentidList, parentId, returnValue);
759
                }
760
              tableHasRows = rs.next();
761
            }//while
762
            rs.close();
763
            pstmt.close();
764

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

    
789
              // get attribures return
790
              docListResult = getAttributeValueForReturn(qspec,
791
                            docListResult, doclist.toString(), useXMLIndex);
792
       }//if doclist lenght is great than zero
793

    
794
     }//if has extended query
795

    
796
      return docListResult;
797
    }//addReturnfield
798

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

    
831
        document = new StringBuffer();
832
        document.append("<triple>");
833
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
834
        document.append("</subject>");
835
        if (subDT != null)
836
        {
837
          document.append("<subjectdoctype>").append(subDT);
838
          document.append("</subjectdoctype>");
839
        }
840
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
841
        document.append("</relationship>");
842
        document.append("<object>").append(MetaCatUtil.normalize(obj));
843
        document.append("</object>");
844
        if (objDT != null)
845
        {
846
          document.append("<objectdoctype>").append(objDT);
847
          document.append("</objectdoctype>");
848
        }
849
        document.append("</triple>");
850

    
851
        String removedelement = (String) docListResult.remove(docidkey);
852
        docListResult.put(docidkey, removedelement+ document.toString());
853
        tableHasRows = rs.next();
854
      }//while
855
      rs.close();
856
      pstmt.close();
857
    }//while
858
    double endRelation = System.currentTimeMillis() / 1000;
859
    MetaCatUtil.debugMessage("Time for adding relation to docListResult: "
860
                             + (endRelation - startRelation), 30);
861

    
862
    return docListResult;
863
  }//addRelation
864

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

    
885

    
886
    /*
887
     * A method to search if Vector contains a particular key string
888
     */
889
    private boolean containsKey(Vector parentidList, String parentId)
890
    {
891

    
892
        Vector tempVector = null;
893

    
894
        for (int count = 0; count < parentidList.size(); count++) {
895
            tempVector = (Vector) parentidList.get(count);
896
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
897
        }
898
        return false;
899
    }
900

    
901
    /*
902
     * A method to put key and value in Vector
903
     */
904
    private void putInArray(Vector parentidList, String key,
905
            ReturnFieldValue value)
906
    {
907

    
908
        Vector tempVector = null;
909

    
910
        for (int count = 0; count < parentidList.size(); count++) {
911
            tempVector = (Vector) parentidList.get(count);
912

    
913
            if (key.compareTo((String) tempVector.get(0)) == 0) {
914
                tempVector.remove(1);
915
                tempVector.add(1, value);
916
                return;
917
            }
918
        }
919

    
920
        tempVector = new Vector();
921
        tempVector.add(0, key);
922
        tempVector.add(1, value);
923
        parentidList.add(tempVector);
924
        return;
925
    }
926

    
927
    /*
928
     * A method to get value in Vector given a key
929
     */
930
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
931
    {
932

    
933
        Vector tempVector = null;
934

    
935
        for (int count = 0; count < parentidList.size(); count++) {
936
            tempVector = (Vector) parentidList.get(count);
937

    
938
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
939
                    .get(1); }
940
        }
941
        return null;
942
    }
943

    
944
    /*
945
     * A method to get enumeration of all values in Vector
946
     */
947
    private Vector getElements(Vector parentidList)
948
    {
949
        Vector enum = new Vector();
950
        Vector tempVector = null;
951

    
952
        for (int count = 0; count < parentidList.size(); count++) {
953
            tempVector = (Vector) parentidList.get(count);
954

    
955
            enum.add(tempVector.get(1));
956
        }
957
        return enum;
958
    }
959

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

    
975
        //check the parameter
976
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
977

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

    
996
                    XML.append("<param name=\"");
997
                    XML.append(fieldname);
998
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
999
                    XML.append(attirbuteName);
1000
                    XML.append("\">");
1001
                    XML.append(fielddata);
1002
                    XML.append("</param>");
1003
                    tableHasRows = rs.next();
1004

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

    
1036
    }
1037

    
1038
    /*
1039
     * A method to create a query to get owner's docid list
1040
     */
1041
    private String getOwnerQuery(String owner)
1042
    {
1043
        if (owner != null) {
1044
            owner = owner.toLowerCase();
1045
        }
1046
        StringBuffer self = new StringBuffer();
1047

    
1048
        self.append("SELECT docid,docname,doctype,");
1049
        self.append("date_created, date_updated, rev ");
1050
        self.append("FROM xml_documents WHERE docid IN (");
1051
        self.append("(");
1052
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1053
        self.append("nodedata LIKE '%%%' ");
1054
        self.append(") \n");
1055
        self.append(") ");
1056
        self.append(" AND (");
1057
        self.append(" lower(user_owner) = '" + owner + "'");
1058
        self.append(") ");
1059
        return self.toString();
1060
    }
1061

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

    
1084

    
1085

    
1086
        if (params.containsKey("meta_file_id")) {
1087
            query.append("<meta_file_id>");
1088
            query.append(((String[]) params.get("meta_file_id"))[0]);
1089
            query.append("</meta_file_id>");
1090
        }
1091

    
1092
        if (params.containsKey("returndoctype")) {
1093
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1094
            for (int i = 0; i < returnDoctypes.length; i++) {
1095
                String doctype = (String) returnDoctypes[i];
1096

    
1097
                if (!doctype.equals("any") && !doctype.equals("ANY")
1098
                        && !doctype.equals("")) {
1099
                    query.append("<returndoctype>").append(doctype);
1100
                    query.append("</returndoctype>");
1101
                }
1102
            }
1103
        }
1104

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

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

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

    
1129
        if (params.containsKey("site")) {
1130
            String[] site = ((String[]) params.get("site"));
1131
            for (int i = 0; i < site.length; i++) {
1132
                query.append("<site>").append(site[i]);
1133
                query.append("</site>");
1134
            }
1135
        }
1136

    
1137
        //allows the dynamic switching of boolean operators
1138
        if (params.containsKey("operator")) {
1139
            query.append("<querygroup operator=\""
1140
                    + ((String[]) params.get("operator"))[0] + "\">");
1141
        } else { //the default operator is UNION
1142
            query.append("<querygroup operator=\"UNION\">");
1143
        }
1144

    
1145
        if (params.containsKey("casesensitive")) {
1146
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1147
        } else {
1148
            casesensitive = "false";
1149
        }
1150

    
1151
        if (params.containsKey("searchmode")) {
1152
            searchmode = ((String[]) params.get("searchmode"))[0];
1153
        } else {
1154
            searchmode = "contains";
1155
        }
1156

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

    
1174
        //this while loop finds the rest of the parameters
1175
        //and attempts to query for the field specified
1176
        //by the parameter.
1177
        elements = params.elements();
1178
        keys = params.keys();
1179
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1180
            nextkey = keys.nextElement();
1181
            nextelement = elements.nextElement();
1182

    
1183
            //make sure we aren't querying for any of these
1184
            //parameters since the are already in the query
1185
            //in one form or another.
1186
            Vector ignoredParams = new Vector();
1187
            ignoredParams.add("returndoctype");
1188
            ignoredParams.add("filterdoctype");
1189
            ignoredParams.add("action");
1190
            ignoredParams.add("qformat");
1191
            ignoredParams.add("anyfield");
1192
            ignoredParams.add("returnfield");
1193
            ignoredParams.add("owner");
1194
            ignoredParams.add("site");
1195
            ignoredParams.add("operator");
1196
            ignoredParams.add("sessionid");
1197

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

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

    
1242
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1243
            xmlquery.append("<returndoctype>");
1244
            xmlquery.append(doctype).append("</returndoctype>");
1245
        }
1246

    
1247
        xmlquery.append("<querygroup operator=\"UNION\">");
1248
        //chad added - 8/14
1249
        //the if statement allows a query to gracefully handle a null
1250
        //query. Without this if a nullpointerException is thrown.
1251
        if (!value.equals("")) {
1252
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1253
            xmlquery.append("searchmode=\"contains\">");
1254
            xmlquery.append("<value>").append(value).append("</value>");
1255
            xmlquery.append("</queryterm>");
1256
        }
1257
        xmlquery.append("</querygroup>");
1258
        xmlquery.append("</pathquery>");
1259

    
1260
        return (xmlquery.toString());
1261
    }
1262

    
1263
    /**
1264
     * format a simple free-text value query as an XML document that conforms
1265
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1266
     * structured query engine
1267
     *
1268
     * @param value the text string to search for in the xml catalog
1269
     */
1270
    public static String createQuery(String value)
1271
    {
1272
        return createQuery(value, "any");
1273
    }
1274

    
1275
    /**
1276
     * Check for "READ" permission on @docid for @user and/or @group from DB
1277
     * connection
1278
     */
1279
    private boolean hasPermission(String user, String[] groups, String docid)
1280
            throws SQLException, Exception
1281
    {
1282
        // Check for READ permission on @docid for @user and/or @groups
1283
        PermissionController controller = new PermissionController(docid);
1284
        return controller.hasPermission(user, groups,
1285
                AccessControlInterface.READSTRING);
1286
    }
1287

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

    
1303
        // Check the parameter
1304
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1305

    
1306
        //the query stirng
1307
        String query = "SELECT subject, object from xml_relation where docId = ?";
1308
        try {
1309
            dbConn = DBConnectionPool
1310
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1311
            serialNumber = dbConn.getCheckOutSerialNumber();
1312
            pStmt = dbConn.prepareStatement(query);
1313
            //bind the value to query
1314
            pStmt.setString(1, dataPackageDocid);
1315

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

    
1331
                //don't put the duplicate docId into the vector
1332
                if (!docIdList.contains(docIdInSubjectField)) {
1333
                    docIdList.add(docIdInSubjectField);
1334
                }
1335

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

    
1364
    /**
1365
     * Get all docIds list for a data packadge
1366
     *
1367
     * @param dataPackageDocid, the string in docId field of xml_relation table
1368
     */
1369
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1370
    {
1371

    
1372
        Vector docIdList = new Vector();//return value
1373
        Vector tripleList = null;
1374
        String xml = null;
1375

    
1376
        // Check the parameter
1377
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1378

    
1379
        try {
1380
            //initial a documentImpl object
1381
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocid);
1382
            //transfer to documentImpl object to string
1383
            xml = packageDocument.toString();
1384

    
1385
            //create a tripcollection object
1386
            TripleCollection tripleForPackage = new TripleCollection(
1387
                    new StringReader(xml));
1388
            //get the vetor of triples
1389
            tripleList = tripleForPackage.getCollection();
1390

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

    
1410
        // return result
1411
        return docIdList;
1412
    }//getDocidListForPackageInXMLRevisions()
1413

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

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

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

    
1515
        }//try
1516
        catch (SQLException e) {
1517
            MetaCatUtil.debugMessage(
1518
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1519
                            + e.getMessage(), 30);
1520
            throw e;
1521
        }//catch
1522
        finally {
1523
            try {
1524
                pStmt.close();
1525
            }//try
1526
            catch (SQLException ee) {
1527
                MetaCatUtil.debugMessage(
1528
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1529
                                + ee.getMessage(), 30);
1530
            }//catch
1531
            finally {
1532
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1533
            }//finally
1534
        }//finally
1535
        return rev;
1536
    }//getCurrentRevFromXMLDoumentsTable
1537

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

    
1554
        byteString = docImpl.toString().getBytes();
1555
        //use docId as the zip entry's name
1556
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1557
                + docImpl.getDocID());
1558
        zEntry.setSize(byteString.length);
1559
        zipOut.putNextEntry(zEntry);
1560
        zipOut.write(byteString, 0, byteString.length);
1561
        zipOut.closeEntry();
1562

    
1563
    }//addDocToZipOutputStream()
1564

    
1565
    /**
1566
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1567
     * only inlcudes current version. If a DocumentImple object couldn't find
1568
     * for a docid, then the String of this docid was added to vetor rather
1569
     * than DocumentImple object.
1570
     *
1571
     * @param docIdList, a vetor hold a docid list for a data package. In
1572
     *            docid, there is not version number in it.
1573
     */
1574

    
1575
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1576
            throws McdbException, Exception
1577
    {
1578
        //Connection dbConn=null;
1579
        Vector documentImplList = new Vector();
1580
        int rev = 0;
1581

    
1582
        // Check the parameter
1583
        if (docIdList.isEmpty()) { return documentImplList; }//if
1584

    
1585
        //for every docid in vector
1586
        for (int i = 0; i < docIdList.size(); i++) {
1587
            try {
1588
                //get newest version for this docId
1589
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1590
                        .elementAt(i));
1591

    
1592
                // There is no record for this docId in xml_documents table
1593
                if (rev == -5) {
1594
                    // Rather than put DocumentImple object, put a String
1595
                    // Object(docid)
1596
                    // into the documentImplList
1597
                    documentImplList.add((String) docIdList.elementAt(i));
1598
                    // Skip other code
1599
                    continue;
1600
                }
1601

    
1602
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1603
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1604

    
1605
                //create new documentImpl object
1606
                DocumentImpl documentImplObject = new DocumentImpl(
1607
                        docidPlusVersion);
1608
                //add them to vector
1609
                documentImplList.add(documentImplObject);
1610
            }//try
1611
            catch (Exception e) {
1612
                MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1613
                        + e.getMessage(), 30);
1614
                // continue the for loop
1615
                continue;
1616
            }
1617
        }//for
1618
        return documentImplList;
1619
    }
1620

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

    
1637
        // Check the parameter
1638
        if (docIdList.isEmpty()) { return documentImplList; }//if
1639

    
1640
        //for every docid in vector
1641
        for (int i = 0; i < docIdList.size(); i++) {
1642

    
1643
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1644

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

    
1671
        }//for
1672
        return documentImplList;
1673
    }//getOldVersionAllDocumentImple
1674

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

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

    
1731
        //create a DBTransform ojbect
1732
        xmlToHtml = new DBTransform();
1733
        //head of html
1734
        htmlDoc.append("<html><head></head><body>");
1735
        for (int i = 0; i < docImplList.size(); i++) {
1736
            // If this String object, this means it is missed data file
1737
            if ((((docImplList.elementAt(i)).getClass()).toString())
1738
                    .equals("class java.lang.String")) {
1739

    
1740
                htmlDoc.append("<a href=\"");
1741
                String dataFileid = (String) docImplList.elementAt(i);
1742
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1743
                htmlDoc.append("Data File: ");
1744
                htmlDoc.append(dataFileid).append("</a><br>");
1745
                htmlDoc.append("<br><hr><br>");
1746

    
1747
            }//if
1748
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
1749
                    .compareTo("BIN") != 0) { //this is an xml file so we can
1750
                                              // transform it.
1751
                //transform each file individually then concatenate all of the
1752
                //transformations together.
1753

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

    
1788
    }//addHtmlSummaryToZipOutputStream
1789

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

    
1814
        String docId = null;
1815
        int version = -5;
1816
        // Docid without revision
1817
        docId = MetaCatUtil.getDocIdFromString(docIdString);
1818
        // revision number
1819
        version = MetaCatUtil.getVersionFromString(docIdString);
1820

    
1821
        //check if the reqused docId is a data package id
1822
        if (!isDataPackageId(docId)) {
1823

    
1824
            /*
1825
             * Exception e = new Exception("The request the doc id "
1826
             * +docIdString+ " is not a data package id");
1827
             */
1828

    
1829
            //CB 1/6/03: if the requested docid is not a datapackage, we just
1830
            // zip
1831
            //up the single document and return the zip file.
1832
            if (!hasPermissionToExportPackage(docId, user, groups)) {
1833

    
1834
                Exception e = new Exception("User " + user
1835
                        + " does not have permission"
1836
                        + " to export the data package " + docIdString);
1837
                throw e;
1838
            }
1839

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

    
1857
            zOut.finish(); //terminate the zip file
1858
            return zOut;
1859
        }
1860
        // Check the permission of user
1861
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
1862

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

    
1888
            }//if
1889
            else if (version > currentVersion || version < -1) {
1890
                throw new Exception("The user specified docid: " + docId + "."
1891
                        + version + " doesn't exist");
1892
            }//else if
1893
            else //for an old version
1894
            {
1895

    
1896
                rootName = docIdString
1897
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
1898
                //get the whole id list for data packadge
1899
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
1900

    
1901
                //get the whole documentImple object
1902
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
1903
            }//else
1904

    
1905
            // Make sure documentImplist is not empty
1906
            if (documentImplList.isEmpty()) { throw new Exception(
1907
                    "Couldn't find component for data package: " + packageId); }//if
1908

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

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

    
1968
                        }//if
1969
                        else {
1970
                            //it is data file
1971
                            addDataFileToZipOutputStream(docImpls, zOut,
1972
                                    rootName);
1973
                            htmlDocumentImplList.add(docImpls);
1974
                        }//else
1975
                    }//if
1976
                }//else
1977
            }//for
1978

    
1979
            //add html summary file
1980
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
1981
                    rootName);
1982
            zOut.finish(); //terminate the zip file
1983
            //dbConn.close();
1984
            return zOut;
1985
        }//else
1986
    }//getZippedPackage()
1987

    
1988
    private class ReturnFieldValue
1989
    {
1990

    
1991
        private String docid = null; //return field value for this docid
1992

    
1993
        private String fieldValue = null;
1994

    
1995
        private String xmlFieldValue = null; //return field value in xml
1996
                                             // format
1997

    
1998
        public void setDocid(String myDocid)
1999
        {
2000
            docid = myDocid;
2001
        }
2002

    
2003
        public String getDocid()
2004
        {
2005
            return docid;
2006
        }
2007

    
2008
        public void setFieldValue(String myValue)
2009
        {
2010
            fieldValue = myValue;
2011
        }
2012

    
2013
        public String getFieldValue()
2014
        {
2015
            return fieldValue;
2016
        }
2017

    
2018
        public void setXMLFieldValue(String xml)
2019
        {
2020
            xmlFieldValue = xml;
2021
        }
2022

    
2023
        public String getXMLFieldValue()
2024
        {
2025
            return xmlFieldValue;
2026
        }
2027

    
2028
    }
2029
}
(22-22/63)