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-07 17:04:18 -0700 (Thu, 07 Apr 2005) $'
15
 * '$Revision: 2474 $'
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
     }
638

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

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

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

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

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

    
672

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

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

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

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

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

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

    
716

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

    
732
     return resultset;
733
 }
734

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

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

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

    
757

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

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

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

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

    
801

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

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

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

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

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

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

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

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

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

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

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

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

    
892

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

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

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

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

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

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

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

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

    
1047
     }//if has extended query
1048

    
1049
      return docListResult;
1050
    }//addReturnfield
1051

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

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

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

    
1115
    return docListResult;
1116
  }//addRelation
1117

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

    
1138

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

    
1145
        Vector tempVector = null;
1146

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

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

    
1161
        Vector tempVector = null;
1162

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

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

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

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

    
1186
        Vector tempVector = null;
1187

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

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

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

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

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

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

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

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

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

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

    
1290
    }
1291

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

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

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

    
1338

    
1339

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1817
    }//addDocToZipOutputStream()
1818

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2042
    }//addHtmlSummaryToZipOutputStream
2043

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2242
    private class ReturnFieldValue
2243
    {
2244

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

    
2247
        private String fieldValue = null;
2248

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

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

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

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

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

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

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

    
2282
    }
2283
}
(22-22/63)