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: cjones $'
14
 *     '$Date: 2005-04-07 16:08:54 -0700 (Thu, 07 Apr 2005) $'
15
 * '$Revision: 2473 $'
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
           pstmt = dbconn.prepareStatement(extendedQuery);
955
           //increase dbconnection usage count
956
           dbconn.increaseUsageCount(1);
957
           pstmt.execute();
958
           rs = pstmt.getResultSet();
959
           double extendedQueryEnd = System.currentTimeMillis() / 1000;
960
           MetaCatUtil.debugMessage("Time for execute extended query: "
961
                           + (extendedQueryEnd - extendedQueryStart), 30);
962
           tableHasRows = rs.next();
963
           while (tableHasRows)
964
           {
965
               ReturnFieldValue returnValue = new ReturnFieldValue();
966
               docid = rs.getString(1).trim();
967
               fieldname = rs.getString(2);
968
               fielddata = rs.getString(3);
969
               fielddata = MetaCatUtil.normalize(fielddata);
970
               String parentId = rs.getString(4);
971
               StringBuffer value = new StringBuffer();
972

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

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

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

    
1044
     }//if has extended query
1045

    
1046
      return docListResult;
1047
    }//addReturnfield
1048

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

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

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

    
1112
    return docListResult;
1113
  }//addRelation
1114

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

    
1135

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

    
1142
        Vector tempVector = null;
1143

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

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

    
1158
        Vector tempVector = null;
1159

    
1160
        for (int count = 0; count < parentidList.size(); count++) {
1161
            tempVector = (Vector) parentidList.get(count);
1162

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

    
1170
        tempVector = new Vector();
1171
        tempVector.add(0, key);
1172
        tempVector.add(1, value);
1173
        parentidList.add(tempVector);
1174
        return;
1175
    }
1176

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

    
1183
        Vector tempVector = null;
1184

    
1185
        for (int count = 0; count < parentidList.size(); count++) {
1186
            tempVector = (Vector) parentidList.get(count);
1187

    
1188
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1189
                    .get(1); }
1190
        }
1191
        return null;
1192
    }
1193

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

    
1202
        for (int count = 0; count < parentidList.size(); count++) {
1203
            tempVector = (Vector) parentidList.get(count);
1204

    
1205
            enumVector.add(tempVector.get(1));
1206
        }
1207
        return enumVector;
1208
    }
1209

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

    
1225
        //check the parameter
1226
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1227

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

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

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

    
1287
    }
1288

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

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

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

    
1335

    
1336

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

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

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

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

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

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

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

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

    
1396
        if (params.containsKey("casesensitive")) {
1397
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1398
        } else {
1399
            casesensitive = "false";
1400
        }
1401

    
1402
        if (params.containsKey("searchmode")) {
1403
            searchmode = ((String[]) params.get("searchmode"))[0];
1404
        } else {
1405
            searchmode = "contains";
1406
        }
1407

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

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

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

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

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

    
1493
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1494
            xmlquery.append("<returndoctype>");
1495
            xmlquery.append(doctype).append("</returndoctype>");
1496
        }
1497

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

    
1511
        return (xmlquery.toString());
1512
    }
1513

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

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

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

    
1554
        // Check the parameter
1555
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1556

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

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

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

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

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

    
1623
        Vector docIdList = new Vector();//return value
1624
        Vector tripleList = null;
1625
        String xml = null;
1626

    
1627
        // Check the parameter
1628
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1629

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

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

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

    
1661
        // return result
1662
        return docIdList;
1663
    }//getDocidListForPackageInXMLRevisions()
1664

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

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

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

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

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

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

    
1814
    }//addDocToZipOutputStream()
1815

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

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

    
1833
        // Check the parameter
1834
        if (docIdList.isEmpty()) { return documentImplList; }//if
1835

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

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

    
1853
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1854
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1855

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

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

    
1888
        // Check the parameter
1889
        if (docIdList.isEmpty()) { return documentImplList; }//if
1890

    
1891
        //for every docid in vector
1892
        for (int i = 0; i < docIdList.size(); i++) {
1893

    
1894
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1895

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

    
1922
        }//for
1923
        return documentImplList;
1924
    }//getOldVersionAllDocumentImple
1925

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

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

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

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

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

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

    
2039
    }//addHtmlSummaryToZipOutputStream
2040

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

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

    
2072
        //check if the reqused docId is a data package id
2073
        if (!isDataPackageId(docId)) {
2074

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

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

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

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

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

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

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

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

    
2152
                //get the whole documentImple object
2153
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2154
            }//else
2155

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

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

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

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

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

    
2239
    private class ReturnFieldValue
2240
    {
2241

    
2242
        private String docid = null; //return field value for this docid
2243

    
2244
        private String fieldValue = null;
2245

    
2246
        private String xmlFieldValue = null; //return field value in xml
2247
                                             // format
2248

    
2249
        public void setDocid(String myDocid)
2250
        {
2251
            docid = myDocid;
2252
        }
2253

    
2254
        public String getDocid()
2255
        {
2256
            return docid;
2257
        }
2258

    
2259
        public void setFieldValue(String myValue)
2260
        {
2261
            fieldValue = myValue;
2262
        }
2263

    
2264
        public String getFieldValue()
2265
        {
2266
            return fieldValue;
2267
        }
2268

    
2269
        public void setXMLFieldValue(String xml)
2270
        {
2271
            xmlFieldValue = xml;
2272
        }
2273

    
2274
        public String getXMLFieldValue()
2275
        {
2276
            return xmlFieldValue;
2277
        }
2278

    
2279
    }
2280
}
(22-22/63)