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: @release@
12
 *
13
 *   '$Author: sgarg $'
14
 *     '$Date: 2005-04-13 11:38:16 -0700 (Wed, 13 Apr 2005) $'
15
 * '$Revision: 2486 $'
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.StringReader;
43
import java.io.StringWriter;
44
import java.sql.PreparedStatement;
45
import java.sql.ResultSet;
46
import java.sql.SQLException;
47
import java.util.Enumeration;
48
import java.util.Hashtable;
49
import java.util.StringTokenizer;
50
import java.util.Vector;
51
import java.util.zip.ZipEntry;
52
import java.util.zip.ZipOutputStream;
53

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

    
57

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

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

    
70
    static final int ALL = 1;
71

    
72
    static final int WRITE = 2;
73

    
74
    static final int READ = 4;
75

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

    
79
    private MetaCatUtil util = new MetaCatUtil();
80

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

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

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

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

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

    
118
                double connTime = System.currentTimeMillis();
119

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

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

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

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

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

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

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

    
194

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

    
213
  }
214

    
215

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

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

    
255

    
256

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

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

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

    
287
      }//else
288

    
289
    }
290

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

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

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

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

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

    
357
    return resultset;
358
  }//createResultDocuments
359

    
360

    
361

    
362
    /*
363
     * Find the doc list which match the query
364
     */
365
    private StringBuffer findResultDoclist(QuerySpecification qspec,
366
                                      StringBuffer resultsetBuffer,
367
                                      PrintWriter out,
368
                                      String user, String[]groups,
369
                                      DBConnection dbconn, boolean useXMLIndex )
370
                                      throws Exception
371
    {
372
      int offset = 1;
373
      // this is a hack for offset
374
      if (out == null)
375
      {
376
        // for html page, we put everything into one page
377
        offset =
378
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
379
      }
380
      else
381
      {
382
          offset =
383
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
384
      }
385

    
386
      int count = 0;
387
      int index = 0;
388
      Hashtable docListResult = new Hashtable();
389
      PreparedStatement pstmt = null;
390
      String docid = null;
391
      String docname = null;
392
      String doctype = null;
393
      String createDate = null;
394
      String updateDate = null;
395
      StringBuffer document = null;
396
      int rev = 0;
397
      String query = qspec.printSQL(useXMLIndex);
398
      String ownerQuery = getOwnerQuery(user);
399
      MetaCatUtil.debugMessage("query: " + query, 30);
400
      //MetaCatUtil.debugMessage("query: "+ownerQuery, 30);
401
      // if query is not the owner query, we need to check the permission
402
      // otherwise we don't need (owner has all permission by default)
403
      if (!query.equals(ownerQuery))
404
      {
405
        // set user name and group
406
        qspec.setUserName(user);
407
        qspec.setGroup(groups);
408
        // Get access query
409
        String accessQuery = qspec.getAccessQuery();
410
        if(!query.endsWith("WHERE")){
411
            query = query + accessQuery;
412
        } else {
413
            query = query + accessQuery.substring(4, accessQuery.length());
414
        }
415
        MetaCatUtil.debugMessage(" final query: " + query, 30);
416
      }
417

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

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

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

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

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

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

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

    
537

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

    
547
           document = new StringBuffer();
548

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

    
573

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

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

    
602
     return resultsetBuffer;
603
    }//findReturnDoclist
604

    
605

    
606
    /*
607
     * Send completed search hashtable(part of reulst)to output stream
608
     * and buffer into a buffer stream
609
     */
610
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
611
                                           StringBuffer resultset,
612
                                           PrintWriter out, Hashtable partOfDoclist,
613
                                           String user, String[]groups,
614
                                       DBConnection dbconn, boolean useXMLIndex)
615
                                       throws Exception
616
   {
617

    
618
     // check if there is a record in xml_returnfield
619
     // and get the returnfield_id and usage count
620
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
621
     boolean enterRecords = false;
622

    
623
     // get value of xml_returnfield_count
624
     int count = (new Integer(MetaCatUtil
625
                            .getOption("xml_returnfield_count")))
626
                            .intValue();
627

    
628
     // set enterRecords to true if usage_count is more than the offset
629
     // specified in metacat.properties
630
     if(usage_count > count){
631
         enterRecords = true;
632
     }
633

    
634
     if(returnfield_id < 0){
635
         MetaCatUtil.debugMessage("Error in getting returnfield id from"
636
                                  + "xml_returnfield table", 20);
637
	enterRecords = false;
638
     }
639

    
640
     // get the hashtable containing the docids that already in the
641
     // xml_queryresult table
642
     MetaCatUtil.debugMessage("size of partOfDoclist before"
643
                             + " docidsInQueryresultTable(): "
644
                             + partOfDoclist.size() , 50);
645
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
646
                                                        partOfDoclist, dbconn);
647

    
648
     // remove the keys in queryresultDocList from partOfDoclist
649
     Enumeration _keys = queryresultDocList.keys();
650
     while (_keys.hasMoreElements()){
651
         partOfDoclist.remove(_keys.nextElement());
652
     }
653

    
654
     // backup the keys-elements in partOfDoclist to check later
655
     // if the doc entry is indexed yet
656
     Hashtable partOfDoclistBackup = new Hashtable();
657
     _keys = partOfDoclist.keys();
658
     while (_keys.hasMoreElements()){
659
	 Object key = _keys.nextElement();
660
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
661
     }
662

    
663
     MetaCatUtil.debugMessage("size of partOfDoclist after"
664
                             + " docidsInQueryresultTable(): "
665
                             + partOfDoclist.size() , 50);
666

    
667
     //add return fields for the documents in partOfDoclist
668
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
669
                                        dbconn, useXMLIndex );
670
     //add relationship part part docid list for the documents in partOfDocList
671
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
672

    
673

    
674
     Enumeration keys = partOfDoclist.keys();
675
     String key = null;
676
     String element = null;
677
     String query = null;
678
     int offset = (new Integer(MetaCatUtil
679
                               .getOption("queryresult_string_length")))
680
                               .intValue();
681
     while (keys.hasMoreElements())
682
     {
683
         key = (String) keys.nextElement();
684
         element = (String)partOfDoclist.get(key);
685

    
686
	 // check if the enterRecords is true, elements is not null, element's
687
         // length is less than the limit of table column and if the document
688
         // has been indexed already
689
         if(enterRecords && element != null
690
		&& element.length() < offset
691
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
692
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
693
                 + "queryresult_string) VALUES (?, ?, ?)";
694

    
695
             PreparedStatement pstmt = null;
696
             pstmt = dbconn.prepareStatement(query);
697
             pstmt.setInt(1, returnfield_id);
698
             pstmt.setString(2, key);
699
             pstmt.setString(3, element);
700

    
701
             dbconn.increaseUsageCount(1);
702
             pstmt.execute();
703
             pstmt.close();
704
         }
705

    
706
         // A string with element
707
         String xmlElement = "  <document>" + element + "</document>";
708

    
709
         //send single element to output
710
         if (out != null)
711
         {
712
             out.println(xmlElement);
713
         }
714
         resultset.append(xmlElement);
715
     }//while
716

    
717

    
718
     keys = queryresultDocList.keys();
719
     while (keys.hasMoreElements())
720
     {
721
         key = (String) keys.nextElement();
722
         element = (String)queryresultDocList.get(key);
723
         // A string with element
724
         String xmlElement = "  <document>" + element + "</document>";
725
         //send single element to output
726
         if (out != null)
727
         {
728
             out.println(xmlElement);
729
         }
730
         resultset.append(xmlElement);
731
     }//while
732

    
733
     return resultset;
734
 }
735

    
736
   /**
737
    * Get the docids already in xml_queryresult table and corresponding
738
    * queryresultstring as a hashtable
739
    */
740
   private Hashtable docidsInQueryresultTable(int returnfield_id,
741
                                              Hashtable partOfDoclist,
742
                                              DBConnection dbconn){
743

    
744
         Hashtable returnValue = new Hashtable();
745
         PreparedStatement pstmt = null;
746
         ResultSet rs = null;
747

    
748
         // get partOfDoclist as string for the query
749
         Enumeration keylist = partOfDoclist.keys();
750
         StringBuffer doclist = new StringBuffer();
751
         while (keylist.hasMoreElements())
752
         {
753
             doclist.append("'");
754
             doclist.append((String) keylist.nextElement());
755
             doclist.append("',");
756
         }//while
757

    
758

    
759
         if (doclist.length() > 0)
760
         {
761
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
762

    
763
             // the query to find out docids from xml_queryresult
764
             String query = "select docid, queryresult_string from "
765
                          + "xml_queryresult where returnfield_id = " +
766
                          returnfield_id +" and docid in ("+ doclist + ")";
767
             MetaCatUtil.debugMessage("Query to get docids from xml_queryresult:"
768
                                      + query, 50);
769

    
770
             try {
771
                 // prepare and execute the query
772
                 pstmt = dbconn.prepareStatement(query);
773
                 dbconn.increaseUsageCount(1);
774
                 pstmt.execute();
775
                 rs = pstmt.getResultSet();
776
                 boolean tableHasRows = rs.next();
777
                 while (tableHasRows) {
778
                     // store the returned results in the returnValue hashtable
779
                     String key = rs.getString(1);
780
                     String element = rs.getString(2);
781

    
782
                     if(element != null){
783
                         returnValue.put(key, element);
784
                     } else {
785
                         MetaCatUtil.debugMessage("Null elment found ("
786
                         + "DBQuery.docidsInQueryresultTable)", 50);
787
                     }
788
                     tableHasRows = rs.next();
789
                 }
790
                 rs.close();
791
                 pstmt.close();
792
             } catch (Exception e){
793
                 MetaCatUtil.debugMessage("Error getting docids from "
794
                                          + "queryresult in "
795
                                          + "DBQuery.docidsInQueryresultTable: "
796
                                          + e.getMessage(), 20);
797
              }
798
         }
799
         return returnValue;
800
     }
801

    
802

    
803
   /**
804
    * Method to get id from xml_returnfield table
805
    * for a given query specification
806
    */
807
   private int returnfield_id;
808
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
809
                                           DBConnection dbconn){
810
       int id = -1;
811
       int count = 1;
812
       PreparedStatement pstmt = null;
813
       ResultSet rs = null;
814
       String returnfield = qspec.getSortedReturnFieldString();
815

    
816
       // query for finding the id from xml_returnfield
817
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
818
            + "WHERE returnfield_string LIKE ?";
819
       MetaCatUtil.debugMessage("ReturnField Query:" + query, 50);
820

    
821
       try {
822
           // prepare and run the query
823
           pstmt = dbconn.prepareStatement(query);
824
           pstmt.setString(1,returnfield);
825
           dbconn.increaseUsageCount(1);
826
           pstmt.execute();
827
           rs = pstmt.getResultSet();
828
           boolean tableHasRows = rs.next();
829

    
830
           // if record found then increase the usage count
831
           // else insert a new record and get the id of the new record
832
           if(tableHasRows){
833
               // get the id
834
               id = rs.getInt(1);
835
               count = rs.getInt(2) + 1;
836
               rs.close();
837
               pstmt.close();
838

    
839
               // increase the usage count
840
               query = "UPDATE xml_returnfield SET usage_count ='" + count
841
                   + "' WHERE returnfield_id ='"+ id +"'";
842
               MetaCatUtil.debugMessage("ReturnField Table Update:"+ query, 50);
843

    
844
               pstmt = dbconn.prepareStatement(query);
845
               dbconn.increaseUsageCount(1);
846
               pstmt.execute();
847
               pstmt.close();
848

    
849
           } else {
850
               rs.close();
851
               pstmt.close();
852

    
853
               // insert a new record
854
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
855
                   + "VALUES (?, '1')";
856
               MetaCatUtil.debugMessage("ReturnField Table Insert:"+ query, 50);
857
               pstmt = dbconn.prepareStatement(query);
858
               pstmt.setString(1, returnfield);
859
               dbconn.increaseUsageCount(1);
860
               pstmt.execute();
861
               pstmt.close();
862

    
863
               // get the id of the new record
864
               query = "SELECT returnfield_id FROM xml_returnfield "
865
                   + "WHERE returnfield_string LIKE ?";
866
               MetaCatUtil.debugMessage("ReturnField query after Insert:" + query, 50);
867
               pstmt = dbconn.prepareStatement(query);
868
               pstmt.setString(1, returnfield);
869

    
870
               dbconn.increaseUsageCount(1);
871
               pstmt.execute();
872
               rs = pstmt.getResultSet();
873
               if(rs.next()){
874
                   id = rs.getInt(1);
875
               } else {
876
                   id = -1;
877
               }
878
               rs.close();
879
               pstmt.close();
880
           }
881

    
882
       } catch (Exception e){
883
           MetaCatUtil.debugMessage("Error getting id from xml_returnfield in "
884
                                     + "DBQuery.getXmlReturnfieldsTableId: "
885
                                     + e.getMessage(), 20);
886
           id = -1;
887
       }
888

    
889
       returnfield_id = id;
890
       return count;
891
   }
892

    
893

    
894
    /*
895
     * A method to add return field to return doclist hash table
896
     */
897
    private Hashtable addReturnfield(Hashtable docListResult,
898
                                      QuerySpecification qspec,
899
                                      String user, String[]groups,
900
                                      DBConnection dbconn, boolean useXMLIndex )
901
                                      throws Exception
902
    {
903
      PreparedStatement pstmt = null;
904
      ResultSet rs = null;
905
      String docid = null;
906
      String fieldname = null;
907
      String fielddata = null;
908
      String relation = null;
909

    
910
      if (qspec.containsExtendedSQL())
911
      {
912
        qspec.setUserName(user);
913
        qspec.setGroup(groups);
914
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
915
        Vector results = new Vector();
916
        Enumeration keylist = docListResult.keys();
917
        StringBuffer doclist = new StringBuffer();
918
        Vector parentidList = new Vector();
919
        Hashtable returnFieldValue = new Hashtable();
920
        while (keylist.hasMoreElements())
921
        {
922
          doclist.append("'");
923
          doclist.append((String) keylist.nextElement());
924
          doclist.append("',");
925
        }
926
        if (doclist.length() > 0)
927
        {
928
          Hashtable controlPairs = new Hashtable();
929
          double extendedQueryStart = System.currentTimeMillis() / 1000;
930
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
931
          // check if user has permission to see the return field data
932
          String accessControlSQL =
933
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
934
          pstmt = dbconn.prepareStatement(accessControlSQL);
935
          //increase dbconnection usage count
936
          dbconn.increaseUsageCount(1);
937
          pstmt.execute();
938
          rs = pstmt.getResultSet();
939
          boolean tableHasRows = rs.next();
940
          while (tableHasRows)
941
          {
942
            long startNodeId = rs.getLong(1);
943
            long endNodeId = rs.getLong(2);
944
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
945
            tableHasRows = rs.next();
946
          }
947

    
948
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
949
           MetaCatUtil.debugMessage( "Time for execute access extended query: "
950
                          + (extendedAccessQueryEnd - extendedQueryStart),30);
951

    
952
           String extendedQuery =
953
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
954
           MetaCatUtil.debugMessage("Extended query: " + extendedQuery, 30);
955

    
956
           if(extendedQuery != null){
957
               pstmt = dbconn.prepareStatement(extendedQuery);
958
               //increase dbconnection usage count
959
               dbconn.increaseUsageCount(1);
960
               pstmt.execute();
961
               rs = pstmt.getResultSet();
962
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
963
               MetaCatUtil.debugMessage(
964
                   "Time for execute extended query: "
965
                   + (extendedQueryEnd - extendedQueryStart), 30);
966
               tableHasRows = rs.next();
967
               while (tableHasRows) {
968
                   ReturnFieldValue returnValue = new ReturnFieldValue();
969
                   docid = rs.getString(1).trim();
970
                   fieldname = rs.getString(2);
971
                   fielddata = rs.getString(3);
972
                   fielddata = MetaCatUtil.normalize(fielddata);
973
                   String parentId = rs.getString(4);
974
                   StringBuffer value = new StringBuffer();
975

    
976
                   // if xml_index is used, there would be just one record per nodeid
977
                   // as xml_index just keeps one entry for each path
978
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
979
                       // don't need to merger nodedata
980
                       value.append("<param name=\"");
981
                       value.append(fieldname);
982
                       value.append("\">");
983
                       value.append(fielddata);
984
                       value.append("</param>");
985
                       //set returnvalue
986
                       returnValue.setDocid(docid);
987
                       returnValue.setFieldValue(fielddata);
988
                       returnValue.setXMLFieldValue(value.toString());
989
                       // Store it in hastable
990
                       putInArray(parentidList, parentId, returnValue);
991
                   }
992
                   else {
993
                       // need to merge nodedata if they have same parent id and
994
                       // node type is text
995
                       fielddata = (String) ( (ReturnFieldValue)
996
                                             getArrayValue(
997
                           parentidList, parentId)).getFieldValue()
998
                           + fielddata;
999
                       value.append("<param name=\"");
1000
                       value.append(fieldname);
1001
                       value.append("\">");
1002
                       value.append(fielddata);
1003
                       value.append("</param>");
1004
                       returnValue.setDocid(docid);
1005
                       returnValue.setFieldValue(fielddata);
1006
                       returnValue.setXMLFieldValue(value.toString());
1007
                       // remove the old return value from paretnidList
1008
                       parentidList.remove(parentId);
1009
                       // store the new return value in parentidlit
1010
                       putInArray(parentidList, parentId, returnValue);
1011
                   }
1012
                   tableHasRows = rs.next();
1013
               } //while
1014
               rs.close();
1015
               pstmt.close();
1016

    
1017
               // put the merger node data info into doclistReult
1018
               Enumeration xmlFieldValue = (getElements(parentidList)).
1019
                   elements();
1020
               while (xmlFieldValue.hasMoreElements()) {
1021
                   ReturnFieldValue object =
1022
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1023
                   docid = object.getDocid();
1024
                   if (docListResult.containsKey(docid)) {
1025
                       String removedelement = (String) docListResult.
1026
                           remove(docid);
1027
                       docListResult.
1028
                           put(docid,
1029
                               removedelement + object.getXMLFieldValue());
1030
                   }
1031
                   else {
1032
                       docListResult.put(docid, object.getXMLFieldValue());
1033
                   }
1034
               } //while
1035
               double docListResultEnd = System.currentTimeMillis() / 1000;
1036
               MetaCatUtil.debugMessage(
1037
                   "Time for prepare doclistresult after"
1038
                   + " execute extended query: "
1039
                   + (docListResultEnd - extendedQueryEnd),
1040
                   30);
1041
           }
1042

    
1043
           // get attribures return
1044
           docListResult = getAttributeValueForReturn(qspec,
1045
                           docListResult, doclist.toString(), useXMLIndex);
1046
       }//if doclist lenght is great than zero
1047

    
1048
     }//if has extended query
1049

    
1050
      return docListResult;
1051
    }//addReturnfield
1052

    
1053
    /*
1054
    * A method to add relationship to return doclist hash table
1055
    */
1056
   private Hashtable addRelationship(Hashtable docListResult,
1057
                                     QuerySpecification qspec,
1058
                                     DBConnection dbconn, boolean useXMLIndex )
1059
                                     throws Exception
1060
  {
1061
    PreparedStatement pstmt = null;
1062
    ResultSet rs = null;
1063
    StringBuffer document = null;
1064
    double startRelation = System.currentTimeMillis() / 1000;
1065
    Enumeration docidkeys = docListResult.keys();
1066
    while (docidkeys.hasMoreElements())
1067
    {
1068
      //String connstring =
1069
      // "metacat://"+util.getOption("server")+"?docid=";
1070
      String connstring = "%docid=";
1071
      String docidkey = (String) docidkeys.nextElement();
1072
      pstmt = dbconn.prepareStatement(QuerySpecification
1073
                      .printRelationSQL(docidkey));
1074
      pstmt.execute();
1075
      rs = pstmt.getResultSet();
1076
      boolean tableHasRows = rs.next();
1077
      while (tableHasRows)
1078
      {
1079
        String sub = rs.getString(1);
1080
        String rel = rs.getString(2);
1081
        String obj = rs.getString(3);
1082
        String subDT = rs.getString(4);
1083
        String objDT = rs.getString(5);
1084

    
1085
        document = new StringBuffer();
1086
        document.append("<triple>");
1087
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1088
        document.append("</subject>");
1089
        if (subDT != null)
1090
        {
1091
          document.append("<subjectdoctype>").append(subDT);
1092
          document.append("</subjectdoctype>");
1093
        }
1094
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1095
        document.append("</relationship>");
1096
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1097
        document.append("</object>");
1098
        if (objDT != null)
1099
        {
1100
          document.append("<objectdoctype>").append(objDT);
1101
          document.append("</objectdoctype>");
1102
        }
1103
        document.append("</triple>");
1104

    
1105
        String removedelement = (String) docListResult.remove(docidkey);
1106
        docListResult.put(docidkey, removedelement+ document.toString());
1107
        tableHasRows = rs.next();
1108
      }//while
1109
      rs.close();
1110
      pstmt.close();
1111
    }//while
1112
    double endRelation = System.currentTimeMillis() / 1000;
1113
    MetaCatUtil.debugMessage("Time for adding relation to docListResult: "
1114
                             + (endRelation - startRelation), 30);
1115

    
1116
    return docListResult;
1117
  }//addRelation
1118

    
1119
  /**
1120
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1121
   * string as a param instead of a hashtable.
1122
   *
1123
   * @param xmlquery a string representing a query.
1124
   */
1125
   private  String transformQuery(String xmlquery)
1126
   {
1127
     xmlquery = xmlquery.trim();
1128
     int index = xmlquery.indexOf("?>");
1129
     if (index != -1)
1130
     {
1131
       return xmlquery.substring(index + 2, xmlquery.length());
1132
     }
1133
     else
1134
     {
1135
       return xmlquery;
1136
     }
1137
   }
1138

    
1139

    
1140
    /*
1141
     * A method to search if Vector contains a particular key string
1142
     */
1143
    private boolean containsKey(Vector parentidList, String parentId)
1144
    {
1145

    
1146
        Vector tempVector = null;
1147

    
1148
        for (int count = 0; count < parentidList.size(); count++) {
1149
            tempVector = (Vector) parentidList.get(count);
1150
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1151
        }
1152
        return false;
1153
    }
1154

    
1155
    /*
1156
     * A method to put key and value in Vector
1157
     */
1158
    private void putInArray(Vector parentidList, String key,
1159
            ReturnFieldValue value)
1160
    {
1161

    
1162
        Vector tempVector = null;
1163

    
1164
        for (int count = 0; count < parentidList.size(); count++) {
1165
            tempVector = (Vector) parentidList.get(count);
1166

    
1167
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1168
                tempVector.remove(1);
1169
                tempVector.add(1, value);
1170
                return;
1171
            }
1172
        }
1173

    
1174
        tempVector = new Vector();
1175
        tempVector.add(0, key);
1176
        tempVector.add(1, value);
1177
        parentidList.add(tempVector);
1178
        return;
1179
    }
1180

    
1181
    /*
1182
     * A method to get value in Vector given a key
1183
     */
1184
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1185
    {
1186

    
1187
        Vector tempVector = null;
1188

    
1189
        for (int count = 0; count < parentidList.size(); count++) {
1190
            tempVector = (Vector) parentidList.get(count);
1191

    
1192
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1193
                    .get(1); }
1194
        }
1195
        return null;
1196
    }
1197

    
1198
    /*
1199
     * A method to get enumeration of all values in Vector
1200
     */
1201
    private Vector getElements(Vector parentidList)
1202
    {
1203
        Vector enumVector = new Vector();
1204
        Vector tempVector = null;
1205

    
1206
        for (int count = 0; count < parentidList.size(); count++) {
1207
            tempVector = (Vector) parentidList.get(count);
1208

    
1209
            enumVector.add(tempVector.get(1));
1210
        }
1211
        return enumVector;
1212
    }
1213

    
1214
    /*
1215
     * A method to return search result after running a query which return
1216
     * field have attribue
1217
     */
1218
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
1219
            Hashtable docInformationList, String docList, boolean useXMLIndex)
1220
    {
1221
        StringBuffer XML = null;
1222
        String sql = null;
1223
        DBConnection dbconn = null;
1224
        PreparedStatement pstmt = null;
1225
        ResultSet rs = null;
1226
        int serialNumber = -1;
1227
        boolean tableHasRows = false;
1228

    
1229
        //check the parameter
1230
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1231

    
1232
        // if has attribute as return field
1233
        if (squery.containsAttributeReturnField()) {
1234
            sql = squery.printAttributeQuery(docList, useXMLIndex);
1235
            try {
1236
                dbconn = DBConnectionPool
1237
                        .getDBConnection("DBQuery.getAttributeValue");
1238
                serialNumber = dbconn.getCheckOutSerialNumber();
1239
                pstmt = dbconn.prepareStatement(sql);
1240
                pstmt.execute();
1241
                rs = pstmt.getResultSet();
1242
                tableHasRows = rs.next();
1243
                while (tableHasRows) {
1244
                    String docid = rs.getString(1).trim();
1245
                    String fieldname = rs.getString(2);
1246
                    String fielddata = rs.getString(3);
1247
                    String attirbuteName = rs.getString(4);
1248
                    XML = new StringBuffer();
1249

    
1250
                    XML.append("<param name=\"");
1251
                    XML.append(fieldname);
1252
                    XML.append("/");
1253
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1254
                    XML.append(attirbuteName);
1255
                    XML.append("\">");
1256
                    XML.append(fielddata);
1257
                    XML.append("</param>");
1258
                    tableHasRows = rs.next();
1259

    
1260
                    if (docInformationList.containsKey(docid)) {
1261
                        String removedelement = (String) docInformationList
1262
                                .remove(docid);
1263
                        docInformationList.put(docid, removedelement
1264
                                + XML.toString());
1265
                    } else {
1266
                        docInformationList.put(docid, XML.toString());
1267
                    }
1268
                }//while
1269
                rs.close();
1270
                pstmt.close();
1271
            } catch (Exception se) {
1272
                MetaCatUtil.debugMessage(
1273
                        "Error in DBQuery.getAttributeValue1: "
1274
                                + se.getMessage(), 30);
1275
            } finally {
1276
                try {
1277
                    pstmt.close();
1278
                }//try
1279
                catch (SQLException sqlE) {
1280
                    MetaCatUtil.debugMessage(
1281
                            "Error in DBQuery.getAttributeValue2: "
1282
                                    + sqlE.getMessage(), 30);
1283
                }//catch
1284
                finally {
1285
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
1286
                }//finally
1287
            }//finally
1288
        }//if
1289
        return docInformationList;
1290

    
1291
    }
1292

    
1293
    /*
1294
     * A method to create a query to get owner's docid list
1295
     */
1296
    private String getOwnerQuery(String owner)
1297
    {
1298
        if (owner != null) {
1299
            owner = owner.toLowerCase();
1300
        }
1301
        StringBuffer self = new StringBuffer();
1302

    
1303
        self.append("SELECT docid,docname,doctype,");
1304
        self.append("date_created, date_updated, rev ");
1305
        self.append("FROM xml_documents WHERE docid IN (");
1306
        self.append("(");
1307
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1308
        self.append("nodedata LIKE '%%%' ");
1309
        self.append(") \n");
1310
        self.append(") ");
1311
        self.append(" AND (");
1312
        self.append(" lower(user_owner) = '" + owner + "'");
1313
        self.append(") ");
1314
        return self.toString();
1315
    }
1316

    
1317
    /**
1318
     * format a structured query as an XML document that conforms to the
1319
     * pathquery.dtd and is appropriate for submission to the DBQuery
1320
     * structured query engine
1321
     *
1322
     * @param params The list of parameters that should be included in the
1323
     *            query
1324
     */
1325
    public static String createSQuery(Hashtable params)
1326
    {
1327
        StringBuffer query = new StringBuffer();
1328
        Enumeration elements;
1329
        Enumeration keys;
1330
        String filterDoctype = null;
1331
        String casesensitive = null;
1332
        String searchmode = null;
1333
        Object nextkey;
1334
        Object nextelement;
1335
        //add the xml headers
1336
        query.append("<?xml version=\"1.0\"?>\n");
1337
        query.append("<pathquery version=\"1.2\">\n");
1338

    
1339

    
1340

    
1341
        if (params.containsKey("meta_file_id")) {
1342
            query.append("<meta_file_id>");
1343
            query.append(((String[]) params.get("meta_file_id"))[0]);
1344
            query.append("</meta_file_id>");
1345
        }
1346

    
1347
        if (params.containsKey("returndoctype")) {
1348
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1349
            for (int i = 0; i < returnDoctypes.length; i++) {
1350
                String doctype = (String) returnDoctypes[i];
1351

    
1352
                if (!doctype.equals("any") && !doctype.equals("ANY")
1353
                        && !doctype.equals("")) {
1354
                    query.append("<returndoctype>").append(doctype);
1355
                    query.append("</returndoctype>");
1356
                }
1357
            }
1358
        }
1359

    
1360
        if (params.containsKey("filterdoctype")) {
1361
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1362
            for (int i = 0; i < filterDoctypes.length; i++) {
1363
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1364
                query.append("</filterdoctype>");
1365
            }
1366
        }
1367

    
1368
        if (params.containsKey("returnfield")) {
1369
            String[] returnfield = ((String[]) params.get("returnfield"));
1370
            for (int i = 0; i < returnfield.length; i++) {
1371
                query.append("<returnfield>").append(returnfield[i]);
1372
                query.append("</returnfield>");
1373
            }
1374
        }
1375

    
1376
        if (params.containsKey("owner")) {
1377
            String[] owner = ((String[]) params.get("owner"));
1378
            for (int i = 0; i < owner.length; i++) {
1379
                query.append("<owner>").append(owner[i]);
1380
                query.append("</owner>");
1381
            }
1382
        }
1383

    
1384
        if (params.containsKey("site")) {
1385
            String[] site = ((String[]) params.get("site"));
1386
            for (int i = 0; i < site.length; i++) {
1387
                query.append("<site>").append(site[i]);
1388
                query.append("</site>");
1389
            }
1390
        }
1391

    
1392
        //allows the dynamic switching of boolean operators
1393
        if (params.containsKey("operator")) {
1394
            query.append("<querygroup operator=\""
1395
                    + ((String[]) params.get("operator"))[0] + "\">");
1396
        } else { //the default operator is UNION
1397
            query.append("<querygroup operator=\"UNION\">");
1398
        }
1399

    
1400
        if (params.containsKey("casesensitive")) {
1401
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1402
        } else {
1403
            casesensitive = "false";
1404
        }
1405

    
1406
        if (params.containsKey("searchmode")) {
1407
            searchmode = ((String[]) params.get("searchmode"))[0];
1408
        } else {
1409
            searchmode = "contains";
1410
        }
1411

    
1412
        //anyfield is a special case because it does a
1413
        //free text search. It does not have a <pathexpr>
1414
        //tag. This allows for a free text search within the structured
1415
        //query. This is useful if the INTERSECT operator is used.
1416
        if (params.containsKey("anyfield")) {
1417
            String[] anyfield = ((String[]) params.get("anyfield"));
1418
            //allow for more than one value for anyfield
1419
            for (int i = 0; i < anyfield.length; i++) {
1420
                if (!anyfield[i].equals("")) {
1421
                    query.append("<queryterm casesensitive=\"" + casesensitive
1422
                            + "\" " + "searchmode=\"" + searchmode
1423
                            + "\"><value>" + anyfield[i]
1424
                            + "</value></queryterm>");
1425
                }
1426
            }
1427
        }
1428

    
1429
        //this while loop finds the rest of the parameters
1430
        //and attempts to query for the field specified
1431
        //by the parameter.
1432
        elements = params.elements();
1433
        keys = params.keys();
1434
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1435
            nextkey = keys.nextElement();
1436
            nextelement = elements.nextElement();
1437

    
1438
            //make sure we aren't querying for any of these
1439
            //parameters since the are already in the query
1440
            //in one form or another.
1441
            Vector ignoredParams = new Vector();
1442
            ignoredParams.add("returndoctype");
1443
            ignoredParams.add("filterdoctype");
1444
            ignoredParams.add("action");
1445
            ignoredParams.add("qformat");
1446
            ignoredParams.add("anyfield");
1447
            ignoredParams.add("returnfield");
1448
            ignoredParams.add("owner");
1449
            ignoredParams.add("site");
1450
            ignoredParams.add("operator");
1451
            ignoredParams.add("sessionid");
1452

    
1453
            // Also ignore parameters listed in the properties file
1454
            // so that they can be passed through to stylesheets
1455
            String paramsToIgnore = MetaCatUtil
1456
                    .getOption("query.ignored.params");
1457
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1458
            while (st.hasMoreTokens()) {
1459
                ignoredParams.add(st.nextToken());
1460
            }
1461
            if (!ignoredParams.contains(nextkey.toString())) {
1462
                //allow for more than value per field name
1463
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1464
                    if (!((String[]) nextelement)[i].equals("")) {
1465
                        query.append("<queryterm casesensitive=\""
1466
                                + casesensitive + "\" " + "searchmode=\""
1467
                                + searchmode + "\">" + "<value>" +
1468
                                //add the query value
1469
                                ((String[]) nextelement)[i]
1470
                                + "</value><pathexpr>" +
1471
                                //add the path to query by
1472
                                nextkey.toString() + "</pathexpr></queryterm>");
1473
                    }
1474
                }
1475
            }
1476
        }
1477
        query.append("</querygroup></pathquery>");
1478
        //append on the end of the xml and return the result as a string
1479
        return query.toString();
1480
    }
1481

    
1482
    /**
1483
     * format a simple free-text value query as an XML document that conforms
1484
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1485
     * structured query engine
1486
     *
1487
     * @param value the text string to search for in the xml catalog
1488
     * @param doctype the type of documents to include in the result set -- use
1489
     *            "any" or "ANY" for unfiltered result sets
1490
     */
1491
    public static String createQuery(String value, String doctype)
1492
    {
1493
        StringBuffer xmlquery = new StringBuffer();
1494
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1495
        xmlquery.append("<pathquery version=\"1.0\">");
1496

    
1497
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1498
            xmlquery.append("<returndoctype>");
1499
            xmlquery.append(doctype).append("</returndoctype>");
1500
        }
1501

    
1502
        xmlquery.append("<querygroup operator=\"UNION\">");
1503
        //chad added - 8/14
1504
        //the if statement allows a query to gracefully handle a null
1505
        //query. Without this if a nullpointerException is thrown.
1506
        if (!value.equals("")) {
1507
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1508
            xmlquery.append("searchmode=\"contains\">");
1509
            xmlquery.append("<value>").append(value).append("</value>");
1510
            xmlquery.append("</queryterm>");
1511
        }
1512
        xmlquery.append("</querygroup>");
1513
        xmlquery.append("</pathquery>");
1514

    
1515
        return (xmlquery.toString());
1516
    }
1517

    
1518
    /**
1519
     * format a simple free-text value query as an XML document that conforms
1520
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1521
     * structured query engine
1522
     *
1523
     * @param value the text string to search for in the xml catalog
1524
     */
1525
    public static String createQuery(String value)
1526
    {
1527
        return createQuery(value, "any");
1528
    }
1529

    
1530
    /**
1531
     * Check for "READ" permission on @docid for @user and/or @group from DB
1532
     * connection
1533
     */
1534
    private boolean hasPermission(String user, String[] groups, String docid)
1535
            throws SQLException, Exception
1536
    {
1537
        // Check for READ permission on @docid for @user and/or @groups
1538
        PermissionController controller = new PermissionController(docid);
1539
        return controller.hasPermission(user, groups,
1540
                AccessControlInterface.READSTRING);
1541
    }
1542

    
1543
    /**
1544
     * Get all docIds list for a data packadge
1545
     *
1546
     * @param dataPackageDocid, the string in docId field of xml_relation table
1547
     */
1548
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1549
    {
1550
        DBConnection dbConn = null;
1551
        int serialNumber = -1;
1552
        Vector docIdList = new Vector();//return value
1553
        PreparedStatement pStmt = null;
1554
        ResultSet rs = null;
1555
        String docIdInSubjectField = null;
1556
        String docIdInObjectField = null;
1557

    
1558
        // Check the parameter
1559
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1560

    
1561
        //the query stirng
1562
        String query = "SELECT subject, object from xml_relation where docId = ?";
1563
        try {
1564
            dbConn = DBConnectionPool
1565
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1566
            serialNumber = dbConn.getCheckOutSerialNumber();
1567
            pStmt = dbConn.prepareStatement(query);
1568
            //bind the value to query
1569
            pStmt.setString(1, dataPackageDocid);
1570

    
1571
            //excute the query
1572
            pStmt.execute();
1573
            //get the result set
1574
            rs = pStmt.getResultSet();
1575
            //process the result
1576
            while (rs.next()) {
1577
                //In order to get the whole docIds in a data packadge,
1578
                //we need to put the docIds of subject and object field in
1579
                // xml_relation
1580
                //into the return vector
1581
                docIdInSubjectField = rs.getString(1);//the result docId in
1582
                                                      // subject field
1583
                docIdInObjectField = rs.getString(2);//the result docId in
1584
                                                     // object field
1585

    
1586
                //don't put the duplicate docId into the vector
1587
                if (!docIdList.contains(docIdInSubjectField)) {
1588
                    docIdList.add(docIdInSubjectField);
1589
                }
1590

    
1591
                //don't put the duplicate docId into the vector
1592
                if (!docIdList.contains(docIdInObjectField)) {
1593
                    docIdList.add(docIdInObjectField);
1594
                }
1595
            }//while
1596
            //close the pStmt
1597
            pStmt.close();
1598
        }//try
1599
        catch (SQLException e) {
1600
            MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1601
                    + e.getMessage(), 30);
1602
        }//catch
1603
        finally {
1604
            try {
1605
                pStmt.close();
1606
            }//try
1607
            catch (SQLException ee) {
1608
                MetaCatUtil.debugMessage(
1609
                        "Error in getDocidListForDataPackage: "
1610
                                + ee.getMessage(), 30);
1611
            }//catch
1612
            finally {
1613
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1614
            }//fianlly
1615
        }//finally
1616
        return docIdList;
1617
    }//getCurrentDocidListForDataPackadge()
1618

    
1619
    /**
1620
     * Get all docIds list for a data packadge
1621
     *
1622
     * @param dataPackageDocid, the string in docId field of xml_relation table
1623
     */
1624
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1625
    {
1626

    
1627
        Vector docIdList = new Vector();//return value
1628
        Vector tripleList = null;
1629
        String xml = null;
1630

    
1631
        // Check the parameter
1632
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1633

    
1634
        try {
1635
            //initial a documentImpl object
1636
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocid);
1637
            //transfer to documentImpl object to string
1638
            xml = packageDocument.toString();
1639

    
1640
            //create a tripcollection object
1641
            TripleCollection tripleForPackage = new TripleCollection(
1642
                    new StringReader(xml));
1643
            //get the vetor of triples
1644
            tripleList = tripleForPackage.getCollection();
1645

    
1646
            for (int i = 0; i < tripleList.size(); i++) {
1647
                //put subject docid into docIdlist without duplicate
1648
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1649
                        .getSubject())) {
1650
                    //put subject docid into docIdlist
1651
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1652
                }
1653
                //put object docid into docIdlist without duplicate
1654
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1655
                        .getObject())) {
1656
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1657
                }
1658
            }//for
1659
        }//try
1660
        catch (Exception e) {
1661
            MetaCatUtil.debugMessage("Error in getOldVersionAllDocumentImpl: "
1662
                    + e.getMessage(), 30);
1663
        }//catch
1664

    
1665
        // return result
1666
        return docIdList;
1667
    }//getDocidListForPackageInXMLRevisions()
1668

    
1669
    /**
1670
     * Check if the docId is a data packadge id. If the id is a data packadage
1671
     * id, it should be store in the docId fields in xml_relation table. So we
1672
     * can use a query to get the entries which the docId equals the given
1673
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1674
     * it is.
1675
     *
1676
     * @param docId, the id need to be checked
1677
     */
1678
    private boolean isDataPackageId(String docId)
1679
    {
1680
        boolean result = false;
1681
        PreparedStatement pStmt = null;
1682
        ResultSet rs = null;
1683
        String query = "SELECT docId from xml_relation where docId = ?";
1684
        DBConnection dbConn = null;
1685
        int serialNumber = -1;
1686
        try {
1687
            dbConn = DBConnectionPool
1688
                    .getDBConnection("DBQuery.isDataPackageId");
1689
            serialNumber = dbConn.getCheckOutSerialNumber();
1690
            pStmt = dbConn.prepareStatement(query);
1691
            //bind the value to query
1692
            pStmt.setString(1, docId);
1693
            //execute the query
1694
            pStmt.execute();
1695
            rs = pStmt.getResultSet();
1696
            //process the result
1697
            if (rs.next()) //There are some records for the id in docId fields
1698
            {
1699
                result = true;//It is a data packadge id
1700
            }
1701
            pStmt.close();
1702
        }//try
1703
        catch (SQLException e) {
1704
            MetaCatUtil.debugMessage("Error in isDataPackageId: "
1705
                    + e.getMessage(), 30);
1706
        } finally {
1707
            try {
1708
                pStmt.close();
1709
            }//try
1710
            catch (SQLException ee) {
1711
                MetaCatUtil.debugMessage("Error in isDataPackageId: "
1712
                        + ee.getMessage(), 30);
1713
            }//catch
1714
            finally {
1715
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1716
            }//finally
1717
        }//finally
1718
        return result;
1719
    }//isDataPackageId()
1720

    
1721
    /**
1722
     * Check if the user has the permission to export data package
1723
     *
1724
     * @param conn, the connection
1725
     * @param docId, the id need to be checked
1726
     * @param user, the name of user
1727
     * @param groups, the user's group
1728
     */
1729
    private boolean hasPermissionToExportPackage(String docId, String user,
1730
            String[] groups) throws Exception
1731
    {
1732
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1733
        return DocumentImpl.hasReadPermission(user, groups, docId);
1734
    }
1735

    
1736
    /**
1737
     * Get the current Rev for a docid in xml_documents table
1738
     *
1739
     * @param docId, the id need to get version numb If the return value is -5,
1740
     *            means no value in rev field for this docid
1741
     */
1742
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1743
            throws SQLException
1744
    {
1745
        int rev = -5;
1746
        PreparedStatement pStmt = null;
1747
        ResultSet rs = null;
1748
        String query = "SELECT rev from xml_documents where docId = ?";
1749
        DBConnection dbConn = null;
1750
        int serialNumber = -1;
1751
        try {
1752
            dbConn = DBConnectionPool
1753
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1754
            serialNumber = dbConn.getCheckOutSerialNumber();
1755
            pStmt = dbConn.prepareStatement(query);
1756
            //bind the value to query
1757
            pStmt.setString(1, docId);
1758
            //execute the query
1759
            pStmt.execute();
1760
            rs = pStmt.getResultSet();
1761
            //process the result
1762
            if (rs.next()) //There are some records for rev
1763
            {
1764
                rev = rs.getInt(1);
1765
                ;//It is the version for given docid
1766
            } else {
1767
                rev = -5;
1768
            }
1769

    
1770
        }//try
1771
        catch (SQLException e) {
1772
            MetaCatUtil.debugMessage(
1773
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1774
                            + e.getMessage(), 30);
1775
            throw e;
1776
        }//catch
1777
        finally {
1778
            try {
1779
                pStmt.close();
1780
            }//try
1781
            catch (SQLException ee) {
1782
                MetaCatUtil.debugMessage(
1783
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1784
                                + ee.getMessage(), 30);
1785
            }//catch
1786
            finally {
1787
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1788
            }//finally
1789
        }//finally
1790
        return rev;
1791
    }//getCurrentRevFromXMLDoumentsTable
1792

    
1793
    /**
1794
     * put a doc into a zip output stream
1795
     *
1796
     * @param docImpl, docmentImpl object which will be sent to zip output
1797
     *            stream
1798
     * @param zipOut, zip output stream which the docImpl will be put
1799
     * @param packageZipEntry, the zip entry name for whole package
1800
     */
1801
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1802
            ZipOutputStream zipOut, String packageZipEntry)
1803
            throws ClassNotFoundException, IOException, SQLException,
1804
            McdbException, Exception
1805
    {
1806
        byte[] byteString = null;
1807
        ZipEntry zEntry = null;
1808

    
1809
        byteString = docImpl.toString().getBytes();
1810
        //use docId as the zip entry's name
1811
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1812
                + docImpl.getDocID());
1813
        zEntry.setSize(byteString.length);
1814
        zipOut.putNextEntry(zEntry);
1815
        zipOut.write(byteString, 0, byteString.length);
1816
        zipOut.closeEntry();
1817

    
1818
    }//addDocToZipOutputStream()
1819

    
1820
    /**
1821
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1822
     * only inlcudes current version. If a DocumentImple object couldn't find
1823
     * for a docid, then the String of this docid was added to vetor rather
1824
     * than DocumentImple object.
1825
     *
1826
     * @param docIdList, a vetor hold a docid list for a data package. In
1827
     *            docid, there is not version number in it.
1828
     */
1829

    
1830
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1831
            throws McdbException, Exception
1832
    {
1833
        //Connection dbConn=null;
1834
        Vector documentImplList = new Vector();
1835
        int rev = 0;
1836

    
1837
        // Check the parameter
1838
        if (docIdList.isEmpty()) { return documentImplList; }//if
1839

    
1840
        //for every docid in vector
1841
        for (int i = 0; i < docIdList.size(); i++) {
1842
            try {
1843
                //get newest version for this docId
1844
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1845
                        .elementAt(i));
1846

    
1847
                // There is no record for this docId in xml_documents table
1848
                if (rev == -5) {
1849
                    // Rather than put DocumentImple object, put a String
1850
                    // Object(docid)
1851
                    // into the documentImplList
1852
                    documentImplList.add((String) docIdList.elementAt(i));
1853
                    // Skip other code
1854
                    continue;
1855
                }
1856

    
1857
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1858
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1859

    
1860
                //create new documentImpl object
1861
                DocumentImpl documentImplObject = new DocumentImpl(
1862
                        docidPlusVersion);
1863
                //add them to vector
1864
                documentImplList.add(documentImplObject);
1865
            }//try
1866
            catch (Exception e) {
1867
                MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1868
                        + e.getMessage(), 30);
1869
                // continue the for loop
1870
                continue;
1871
            }
1872
        }//for
1873
        return documentImplList;
1874
    }
1875

    
1876
    /**
1877
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
1878
     * object couldn't find for a docid, then the String of this docid was
1879
     * added to vetor rather than DocumentImple object.
1880
     *
1881
     * @param docIdList, a vetor hold a docid list for a data package. In
1882
     *            docid, t here is version number in it.
1883
     */
1884
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
1885
    {
1886
        //Connection dbConn=null;
1887
        Vector documentImplList = new Vector();
1888
        String siteCode = null;
1889
        String uniqueId = null;
1890
        int rev = 0;
1891

    
1892
        // Check the parameter
1893
        if (docIdList.isEmpty()) { return documentImplList; }//if
1894

    
1895
        //for every docid in vector
1896
        for (int i = 0; i < docIdList.size(); i++) {
1897

    
1898
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1899

    
1900
            try {
1901
                //create new documentImpl object
1902
                DocumentImpl documentImplObject = new DocumentImpl(
1903
                        docidPlusVersion);
1904
                //add them to vector
1905
                documentImplList.add(documentImplObject);
1906
            }//try
1907
            catch (McdbDocNotFoundException notFoundE) {
1908
                MetaCatUtil.debugMessage(
1909
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1910
                                + notFoundE.getMessage(), 30);
1911
                // Rather than add a DocumentImple object into vetor, a String
1912
                // object
1913
                // - the doicd was added to the vector
1914
                documentImplList.add(docidPlusVersion);
1915
                // Continue the for loop
1916
                continue;
1917
            }//catch
1918
            catch (Exception e) {
1919
                MetaCatUtil.debugMessage(
1920
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1921
                                + e.getMessage(), 30);
1922
                // Continue the for loop
1923
                continue;
1924
            }//catch
1925

    
1926
        }//for
1927
        return documentImplList;
1928
    }//getOldVersionAllDocumentImple
1929

    
1930
    /**
1931
     * put a data file into a zip output stream
1932
     *
1933
     * @param docImpl, docmentImpl object which will be sent to zip output
1934
     *            stream
1935
     * @param zipOut, the zip output stream which the docImpl will be put
1936
     * @param packageZipEntry, the zip entry name for whole package
1937
     */
1938
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
1939
            ZipOutputStream zipOut, String packageZipEntry)
1940
            throws ClassNotFoundException, IOException, SQLException,
1941
            McdbException, Exception
1942
    {
1943
        byte[] byteString = null;
1944
        ZipEntry zEntry = null;
1945
        // this is data file; add file to zip
1946
        String filePath = MetaCatUtil.getOption("datafilepath");
1947
        if (!filePath.endsWith("/")) {
1948
            filePath += "/";
1949
        }
1950
        String fileName = filePath + docImpl.getDocID();
1951
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
1952
        zipOut.putNextEntry(zEntry);
1953
        FileInputStream fin = null;
1954
        try {
1955
            fin = new FileInputStream(fileName);
1956
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1957
            int b = fin.read(buf);
1958
            while (b != -1) {
1959
                zipOut.write(buf, 0, b);
1960
                b = fin.read(buf);
1961
            }//while
1962
            zipOut.closeEntry();
1963
        }//try
1964
        catch (IOException ioe) {
1965
            MetaCatUtil.debugMessage("There is an exception: "
1966
                    + ioe.getMessage(), 30);
1967
        }//catch
1968
    }//addDataFileToZipOutputStream()
1969

    
1970
    /**
1971
     * create a html summary for data package and put it into zip output stream
1972
     *
1973
     * @param docImplList, the documentImpl ojbects in data package
1974
     * @param zipOut, the zip output stream which the html should be put
1975
     * @param packageZipEntry, the zip entry name for whole package
1976
     */
1977
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
1978
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
1979
    {
1980
        StringBuffer htmlDoc = new StringBuffer();
1981
        ZipEntry zEntry = null;
1982
        byte[] byteString = null;
1983
        InputStream source;
1984
        DBTransform xmlToHtml;
1985

    
1986
        //create a DBTransform ojbect
1987
        xmlToHtml = new DBTransform();
1988
        //head of html
1989
        htmlDoc.append("<html><head></head><body>");
1990
        for (int i = 0; i < docImplList.size(); i++) {
1991
            // If this String object, this means it is missed data file
1992
            if ((((docImplList.elementAt(i)).getClass()).toString())
1993
                    .equals("class java.lang.String")) {
1994

    
1995
                htmlDoc.append("<a href=\"");
1996
                String dataFileid = (String) docImplList.elementAt(i);
1997
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1998
                htmlDoc.append("Data File: ");
1999
                htmlDoc.append(dataFileid).append("</a><br>");
2000
                htmlDoc.append("<br><hr><br>");
2001

    
2002
            }//if
2003
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2004
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2005
                                              // transform it.
2006
                //transform each file individually then concatenate all of the
2007
                //transformations together.
2008

    
2009
                //for metadata xml title
2010
                htmlDoc.append("<h2>");
2011
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2012
                        .getDocID());
2013
                //htmlDoc.append(".");
2014
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2015
                htmlDoc.append("</h2>");
2016
                //do the actual transform
2017
                StringWriter docString = new StringWriter();
2018
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2019
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2020
                        "-//W3C//HTML//EN", "html", docString);
2021
                htmlDoc.append(docString.toString());
2022
                htmlDoc.append("<br><br><hr><br><br>");
2023
            }//if
2024
            else { //this is a data file so we should link to it in the html
2025
                htmlDoc.append("<a href=\"");
2026
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2027
                        .getDocID();
2028
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2029
                htmlDoc.append("Data File: ");
2030
                htmlDoc.append(dataFileid).append("</a><br>");
2031
                htmlDoc.append("<br><hr><br>");
2032
            }//else
2033
        }//for
2034
        htmlDoc.append("</body></html>");
2035
        byteString = htmlDoc.toString().getBytes();
2036
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2037
        zEntry.setSize(byteString.length);
2038
        zipOut.putNextEntry(zEntry);
2039
        zipOut.write(byteString, 0, byteString.length);
2040
        zipOut.closeEntry();
2041
        //dbConn.close();
2042

    
2043
    }//addHtmlSummaryToZipOutputStream
2044

    
2045
    /**
2046
     * put a data packadge into a zip output stream
2047
     *
2048
     * @param docId, which the user want to put into zip output stream
2049
     * @param out, a servletoutput stream which the zip output stream will be
2050
     *            put
2051
     * @param user, the username of the user
2052
     * @param groups, the group of the user
2053
     */
2054
    public ZipOutputStream getZippedPackage(String docIdString,
2055
            ServletOutputStream out, String user, String[] groups,
2056
            String passWord) throws ClassNotFoundException, IOException,
2057
            SQLException, McdbException, NumberFormatException, Exception
2058
    {
2059
        ZipOutputStream zOut = null;
2060
        String elementDocid = null;
2061
        DocumentImpl docImpls = null;
2062
        //Connection dbConn = null;
2063
        Vector docIdList = new Vector();
2064
        Vector documentImplList = new Vector();
2065
        Vector htmlDocumentImplList = new Vector();
2066
        String packageId = null;
2067
        String rootName = "package";//the package zip entry name
2068

    
2069
        String docId = null;
2070
        int version = -5;
2071
        // Docid without revision
2072
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2073
        // revision number
2074
        version = MetaCatUtil.getVersionFromString(docIdString);
2075

    
2076
        //check if the reqused docId is a data package id
2077
        if (!isDataPackageId(docId)) {
2078

    
2079
            /*
2080
             * Exception e = new Exception("The request the doc id "
2081
             * +docIdString+ " is not a data package id");
2082
             */
2083

    
2084
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2085
            // zip
2086
            //up the single document and return the zip file.
2087
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2088

    
2089
                Exception e = new Exception("User " + user
2090
                        + " does not have permission"
2091
                        + " to export the data package " + docIdString);
2092
                throw e;
2093
            }
2094

    
2095
            docImpls = new DocumentImpl(docId);
2096
            //checking if the user has the permission to read the documents
2097
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2098
                    .getDocID())) {
2099
                zOut = new ZipOutputStream(out);
2100
                //if the docImpls is metadata
2101
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2102
                    //add metadata into zip output stream
2103
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2104
                }//if
2105
                else {
2106
                    //it is data file
2107
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2108
                    htmlDocumentImplList.add(docImpls);
2109
                }//else
2110
            }//if
2111

    
2112
            zOut.finish(); //terminate the zip file
2113
            return zOut;
2114
        }
2115
        // Check the permission of user
2116
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2117

    
2118
            Exception e = new Exception("User " + user
2119
                    + " does not have permission"
2120
                    + " to export the data package " + docIdString);
2121
            throw e;
2122
        } else //it is a packadge id
2123
        {
2124
            //store the package id
2125
            packageId = docId;
2126
            //get current version in database
2127
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2128
            //If it is for current version (-1 means user didn't specify
2129
            // revision)
2130
            if ((version == -1) || version == currentVersion) {
2131
                //get current version number
2132
                version = currentVersion;
2133
                //get package zip entry name
2134
                //it should be docId.revsion.package
2135
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2136
                        + version + MetaCatUtil.getOption("accNumSeparator")
2137
                        + "package";
2138
                //get the whole id list for data packadge
2139
                docIdList = getCurrentDocidListForDataPackage(packageId);
2140
                //get the whole documentImple object
2141
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2142

    
2143
            }//if
2144
            else if (version > currentVersion || version < -1) {
2145
                throw new Exception("The user specified docid: " + docId + "."
2146
                        + version + " doesn't exist");
2147
            }//else if
2148
            else //for an old version
2149
            {
2150

    
2151
                rootName = docIdString
2152
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2153
                //get the whole id list for data packadge
2154
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2155

    
2156
                //get the whole documentImple object
2157
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2158
            }//else
2159

    
2160
            // Make sure documentImplist is not empty
2161
            if (documentImplList.isEmpty()) { throw new Exception(
2162
                    "Couldn't find component for data package: " + packageId); }//if
2163

    
2164
            zOut = new ZipOutputStream(out);
2165
            //put every element into zip output stream
2166
            for (int i = 0; i < documentImplList.size(); i++) {
2167
                // if the object in the vetor is String, this means we couldn't
2168
                // find
2169
                // the document locally, we need find it remote
2170
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2171
                        .equals("class java.lang.String")) {
2172
                    // Get String object from vetor
2173
                    String documentId = (String) documentImplList.elementAt(i);
2174
                    MetaCatUtil.debugMessage("docid: " + documentId, 30);
2175
                    // Get doicd without revision
2176
                    String docidWithoutRevision = MetaCatUtil
2177
                            .getDocIdFromString(documentId);
2178
                    MetaCatUtil.debugMessage("docidWithoutRevsion: "
2179
                            + docidWithoutRevision, 30);
2180
                    // Get revision
2181
                    String revision = MetaCatUtil
2182
                            .getRevisionStringFromString(documentId);
2183
                    MetaCatUtil.debugMessage("revsion from docIdentifier: "
2184
                            + revision, 30);
2185
                    // Zip entry string
2186
                    String zipEntryPath = rootName + "/data/";
2187
                    // Create a RemoteDocument object
2188
                    RemoteDocument remoteDoc = new RemoteDocument(
2189
                            docidWithoutRevision, revision, user, passWord,
2190
                            zipEntryPath);
2191
                    // Here we only read data file from remote metacat
2192
                    String docType = remoteDoc.getDocType();
2193
                    if (docType != null) {
2194
                        if (docType.equals("BIN")) {
2195
                            // Put remote document to zip output
2196
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2197
                            // Add String object to htmlDocumentImplList
2198
                            String elementInHtmlList = remoteDoc
2199
                                    .getDocIdWithoutRevsion()
2200
                                    + MetaCatUtil.getOption("accNumSeparator")
2201
                                    + remoteDoc.getRevision();
2202
                            htmlDocumentImplList.add(elementInHtmlList);
2203
                        }//if
2204
                    }//if
2205

    
2206
                }//if
2207
                else {
2208
                    //create a docmentImpls object (represent xml doc) base on
2209
                    // the docId
2210
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2211
                    //checking if the user has the permission to read the
2212
                    // documents
2213
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2214
                            .getDocID())) {
2215
                        //if the docImpls is metadata
2216
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2217
                            //add metadata into zip output stream
2218
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2219
                            //add the documentImpl into the vetor which will
2220
                            // be used in html
2221
                            htmlDocumentImplList.add(docImpls);
2222

    
2223
                        }//if
2224
                        else {
2225
                            //it is data file
2226
                            addDataFileToZipOutputStream(docImpls, zOut,
2227
                                    rootName);
2228
                            htmlDocumentImplList.add(docImpls);
2229
                        }//else
2230
                    }//if
2231
                }//else
2232
            }//for
2233

    
2234
            //add html summary file
2235
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2236
                    rootName);
2237
            zOut.finish(); //terminate the zip file
2238
            //dbConn.close();
2239
            return zOut;
2240
        }//else
2241
    }//getZippedPackage()
2242

    
2243
    private class ReturnFieldValue
2244
    {
2245

    
2246
        private String docid = null; //return field value for this docid
2247

    
2248
        private String fieldValue = null;
2249

    
2250
        private String xmlFieldValue = null; //return field value in xml
2251
                                             // format
2252

    
2253
        public void setDocid(String myDocid)
2254
        {
2255
            docid = myDocid;
2256
        }
2257

    
2258
        public String getDocid()
2259
        {
2260
            return docid;
2261
        }
2262

    
2263
        public void setFieldValue(String myValue)
2264
        {
2265
            fieldValue = myValue;
2266
        }
2267

    
2268
        public String getFieldValue()
2269
        {
2270
            return fieldValue;
2271
        }
2272

    
2273
        public void setXMLFieldValue(String xml)
2274
        {
2275
            xmlFieldValue = xml;
2276
        }
2277

    
2278
        public String getXMLFieldValue()
2279
        {
2280
            return xmlFieldValue;
2281
        }
2282

    
2283
    }
2284
}
(22-22/63)