Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *    Release: 1.4.0
12
 *
13
 *   '$Author: sgarg $'
14
 *     '$Date: 2005-03-29 08:06:46 -0800 (Tue, 29 Mar 2005) $'
15
 * '$Revision: 2430 $'
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 ('" + returnfield_id
693
                 + "', '" + key + "', '" + element + "')";
694
             PreparedStatement pstmt = null;
695
             pstmt = dbconn.prepareStatement(query);
696
             dbconn.increaseUsageCount(1);
697
             pstmt.execute();
698
             pstmt.close();
699
         }
700

    
701
         // A string with element
702
         String xmlElement = "  <document>" + element + "</document>";
703

    
704
         //send single element to output
705
         if (out != null)
706
         {
707
             out.println(xmlElement);
708
         }
709
         resultset.append(xmlElement);
710
     }//while
711

    
712

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

    
728
     return resultset;
729
 }
730

    
731
   /**
732
    * Get the docids already in xml_queryresult table and corresponding
733
    * queryresultstring as a hashtable
734
    */
735
   private Hashtable docidsInQueryresultTable(int returnfield_id,
736
                                              Hashtable partOfDoclist,
737
                                              DBConnection dbconn){
738

    
739
         Hashtable returnValue = new Hashtable();
740
         PreparedStatement pstmt = null;
741
         ResultSet rs = null;
742

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

    
753

    
754
         if (doclist.length() > 0)
755
         {
756
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
757

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

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

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

    
797

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

    
811
       // query for finding the id from xml_returnfield
812
       String query = "select returnfield_id, usage_count from xml_returnfield "
813
           + "where returnfield_string like '" + returnfield +"'";
814
       MetaCatUtil.debugMessage("ReturnField Query:" + query, 50);
815

    
816
       try {
817
           // prepare and run the query
818
           pstmt = dbconn.prepareStatement(query);
819
           dbconn.increaseUsageCount(1);
820
           pstmt.execute();
821
           rs = pstmt.getResultSet();
822
           boolean tableHasRows = rs.next();
823

    
824
           // if record found then increase the usage count
825
           // else insert a new record and get the id of the new record
826
           if(tableHasRows){
827
               // get the id
828
               id = rs.getInt(1);
829
               count = rs.getInt(2) + 1;
830
               rs.close();
831
               pstmt.close();
832

    
833
               // increase the usage count
834
               query = "UPDATE xml_returnfield SET usage_count ='" + count
835
                   + "' WHERE returnfield_id ='"+ id +"'";
836
               MetaCatUtil.debugMessage("ReturnField Table Update:"+ query, 50);
837

    
838
               pstmt = dbconn.prepareStatement(query);
839
               dbconn.increaseUsageCount(1);
840
               pstmt.execute();
841
               pstmt.close();
842

    
843
           } else {
844
               rs.close();
845
               pstmt.close();
846

    
847
               // insert a new record
848
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
849
                   + "VALUES ('" + returnfield + "', '1')";
850
               MetaCatUtil.debugMessage("ReturnField Table Insert:"+ query, 50);
851
               pstmt = dbconn.prepareStatement(query);
852
               dbconn.increaseUsageCount(1);
853
               pstmt.execute();
854
               pstmt.close();
855

    
856
               // get the id of the new record
857
               query = "select returnfield_id from xml_returnfield "
858
                   + "where returnfield_string like '" + returnfield +"'";
859
               MetaCatUtil.debugMessage("ReturnField query after Insert:"
860
                                        + query, 50);
861
               pstmt = dbconn.prepareStatement(query);
862
               dbconn.increaseUsageCount(1);
863
               pstmt.execute();
864
               rs = pstmt.getResultSet();
865
               if(rs.next()){
866
                   id = rs.getInt(1);
867
               } else {
868
                   id = -1;
869
               }
870
               rs.close();
871
               pstmt.close();
872
           }
873

    
874
       } catch (Exception e){
875
           MetaCatUtil.debugMessage("Error getting id from xml_returnfield in "
876
                                     + "DBQuery.getXmlReturnfieldsTableId: "
877
                                     + e.getMessage(), 20);
878
           id = -1;
879
       }
880

    
881
       returnfield_id = id;
882
       return count;
883
   }
884

    
885

    
886
    /*
887
     * A method to add return field to return doclist hash table
888
     */
889
    private Hashtable addReturnfield(Hashtable docListResult,
890
                                      QuerySpecification qspec,
891
                                      String user, String[]groups,
892
                                      DBConnection dbconn, boolean useXMLIndex )
893
                                      throws Exception
894
    {
895
      PreparedStatement pstmt = null;
896
      ResultSet rs = null;
897
      String docid = null;
898
      String fieldname = null;
899
      String fielddata = null;
900
      String relation = null;
901

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

    
940
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
941
           MetaCatUtil.debugMessage( "Time for execute access extended query: "
942
                          + (extendedAccessQueryEnd - extendedQueryStart),30);
943

    
944
           String extendedQuery =
945
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
946
           MetaCatUtil.debugMessage("Extended query: " + extendedQuery, 30);
947
           pstmt = dbconn.prepareStatement(extendedQuery);
948
           //increase dbconnection usage count
949
           dbconn.increaseUsageCount(1);
950
           pstmt.execute();
951
           rs = pstmt.getResultSet();
952
           double extendedQueryEnd = System.currentTimeMillis() / 1000;
953
           MetaCatUtil.debugMessage("Time for execute extended query: "
954
                           + (extendedQueryEnd - extendedQueryStart), 30);
955
           tableHasRows = rs.next();
956
           while (tableHasRows)
957
           {
958
               ReturnFieldValue returnValue = new ReturnFieldValue();
959
               docid = rs.getString(1).trim();
960
               fieldname = rs.getString(2);
961
               fielddata = rs.getString(3);
962
               fielddata = MetaCatUtil.normalize(fielddata);
963
               String parentId = rs.getString(4);
964
               StringBuffer value = new StringBuffer();
965

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

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

    
1032
              // get attribures return
1033
              docListResult = getAttributeValueForReturn(qspec,
1034
                            docListResult, doclist.toString(), useXMLIndex);
1035
       }//if doclist lenght is great than zero
1036

    
1037
     }//if has extended query
1038

    
1039
      return docListResult;
1040
    }//addReturnfield
1041

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

    
1074
        document = new StringBuffer();
1075
        document.append("<triple>");
1076
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1077
        document.append("</subject>");
1078
        if (subDT != null)
1079
        {
1080
          document.append("<subjectdoctype>").append(subDT);
1081
          document.append("</subjectdoctype>");
1082
        }
1083
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1084
        document.append("</relationship>");
1085
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1086
        document.append("</object>");
1087
        if (objDT != null)
1088
        {
1089
          document.append("<objectdoctype>").append(objDT);
1090
          document.append("</objectdoctype>");
1091
        }
1092
        document.append("</triple>");
1093

    
1094
        String removedelement = (String) docListResult.remove(docidkey);
1095
        docListResult.put(docidkey, removedelement+ document.toString());
1096
        tableHasRows = rs.next();
1097
      }//while
1098
      rs.close();
1099
      pstmt.close();
1100
    }//while
1101
    double endRelation = System.currentTimeMillis() / 1000;
1102
    MetaCatUtil.debugMessage("Time for adding relation to docListResult: "
1103
                             + (endRelation - startRelation), 30);
1104

    
1105
    return docListResult;
1106
  }//addRelation
1107

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

    
1128

    
1129
    /*
1130
     * A method to search if Vector contains a particular key string
1131
     */
1132
    private boolean containsKey(Vector parentidList, String parentId)
1133
    {
1134

    
1135
        Vector tempVector = null;
1136

    
1137
        for (int count = 0; count < parentidList.size(); count++) {
1138
            tempVector = (Vector) parentidList.get(count);
1139
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1140
        }
1141
        return false;
1142
    }
1143

    
1144
    /*
1145
     * A method to put key and value in Vector
1146
     */
1147
    private void putInArray(Vector parentidList, String key,
1148
            ReturnFieldValue value)
1149
    {
1150

    
1151
        Vector tempVector = null;
1152

    
1153
        for (int count = 0; count < parentidList.size(); count++) {
1154
            tempVector = (Vector) parentidList.get(count);
1155

    
1156
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1157
                tempVector.remove(1);
1158
                tempVector.add(1, value);
1159
                return;
1160
            }
1161
        }
1162

    
1163
        tempVector = new Vector();
1164
        tempVector.add(0, key);
1165
        tempVector.add(1, value);
1166
        parentidList.add(tempVector);
1167
        return;
1168
    }
1169

    
1170
    /*
1171
     * A method to get value in Vector given a key
1172
     */
1173
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1174
    {
1175

    
1176
        Vector tempVector = null;
1177

    
1178
        for (int count = 0; count < parentidList.size(); count++) {
1179
            tempVector = (Vector) parentidList.get(count);
1180

    
1181
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1182
                    .get(1); }
1183
        }
1184
        return null;
1185
    }
1186

    
1187
    /*
1188
     * A method to get enumeration of all values in Vector
1189
     */
1190
    private Vector getElements(Vector parentidList)
1191
    {
1192
        Vector enum = new Vector();
1193
        Vector tempVector = null;
1194

    
1195
        for (int count = 0; count < parentidList.size(); count++) {
1196
            tempVector = (Vector) parentidList.get(count);
1197

    
1198
            enum.add(tempVector.get(1));
1199
        }
1200
        return enum;
1201
    }
1202

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

    
1218
        //check the parameter
1219
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1220

    
1221
        // if has attribute as return field
1222
        if (squery.containAttributeReturnField()) {
1223
            sql = squery.printAttributeQuery(docList, useXMLIndex);
1224
            try {
1225
                dbconn = DBConnectionPool
1226
                        .getDBConnection("DBQuery.getAttributeValue");
1227
                serialNumber = dbconn.getCheckOutSerialNumber();
1228
                pstmt = dbconn.prepareStatement(sql);
1229
                pstmt.execute();
1230
                rs = pstmt.getResultSet();
1231
                tableHasRows = rs.next();
1232
                while (tableHasRows) {
1233
                    String docid = rs.getString(1).trim();
1234
                    String fieldname = rs.getString(2);
1235
                    String fielddata = rs.getString(3);
1236
                    String attirbuteName = rs.getString(4);
1237
                    XML = new StringBuffer();
1238

    
1239
                    XML.append("<param name=\"");
1240
                    XML.append(fieldname);
1241
                    XML.append("/");
1242
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1243
                    XML.append(attirbuteName);
1244
                    XML.append("\">");
1245
                    XML.append(fielddata);
1246
                    XML.append("</param>");
1247
                    tableHasRows = rs.next();
1248

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

    
1280
    }
1281

    
1282
    /*
1283
     * A method to create a query to get owner's docid list
1284
     */
1285
    private String getOwnerQuery(String owner)
1286
    {
1287
        if (owner != null) {
1288
            owner = owner.toLowerCase();
1289
        }
1290
        StringBuffer self = new StringBuffer();
1291

    
1292
        self.append("SELECT docid,docname,doctype,");
1293
        self.append("date_created, date_updated, rev ");
1294
        self.append("FROM xml_documents WHERE docid IN (");
1295
        self.append("(");
1296
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1297
        self.append("nodedata LIKE '%%%' ");
1298
        self.append(") \n");
1299
        self.append(") ");
1300
        self.append(" AND (");
1301
        self.append(" lower(user_owner) = '" + owner + "'");
1302
        self.append(") ");
1303
        return self.toString();
1304
    }
1305

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

    
1328

    
1329

    
1330
        if (params.containsKey("meta_file_id")) {
1331
            query.append("<meta_file_id>");
1332
            query.append(((String[]) params.get("meta_file_id"))[0]);
1333
            query.append("</meta_file_id>");
1334
        }
1335

    
1336
        if (params.containsKey("returndoctype")) {
1337
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1338
            for (int i = 0; i < returnDoctypes.length; i++) {
1339
                String doctype = (String) returnDoctypes[i];
1340

    
1341
                if (!doctype.equals("any") && !doctype.equals("ANY")
1342
                        && !doctype.equals("")) {
1343
                    query.append("<returndoctype>").append(doctype);
1344
                    query.append("</returndoctype>");
1345
                }
1346
            }
1347
        }
1348

    
1349
        if (params.containsKey("filterdoctype")) {
1350
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1351
            for (int i = 0; i < filterDoctypes.length; i++) {
1352
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1353
                query.append("</filterdoctype>");
1354
            }
1355
        }
1356

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

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

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

    
1381
        //allows the dynamic switching of boolean operators
1382
        if (params.containsKey("operator")) {
1383
            query.append("<querygroup operator=\""
1384
                    + ((String[]) params.get("operator"))[0] + "\">");
1385
        } else { //the default operator is UNION
1386
            query.append("<querygroup operator=\"UNION\">");
1387
        }
1388

    
1389
        if (params.containsKey("casesensitive")) {
1390
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1391
        } else {
1392
            casesensitive = "false";
1393
        }
1394

    
1395
        if (params.containsKey("searchmode")) {
1396
            searchmode = ((String[]) params.get("searchmode"))[0];
1397
        } else {
1398
            searchmode = "contains";
1399
        }
1400

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

    
1418
        //this while loop finds the rest of the parameters
1419
        //and attempts to query for the field specified
1420
        //by the parameter.
1421
        elements = params.elements();
1422
        keys = params.keys();
1423
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1424
            nextkey = keys.nextElement();
1425
            nextelement = elements.nextElement();
1426

    
1427
            //make sure we aren't querying for any of these
1428
            //parameters since the are already in the query
1429
            //in one form or another.
1430
            Vector ignoredParams = new Vector();
1431
            ignoredParams.add("returndoctype");
1432
            ignoredParams.add("filterdoctype");
1433
            ignoredParams.add("action");
1434
            ignoredParams.add("qformat");
1435
            ignoredParams.add("anyfield");
1436
            ignoredParams.add("returnfield");
1437
            ignoredParams.add("owner");
1438
            ignoredParams.add("site");
1439
            ignoredParams.add("operator");
1440
            ignoredParams.add("sessionid");
1441

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

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

    
1486
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1487
            xmlquery.append("<returndoctype>");
1488
            xmlquery.append(doctype).append("</returndoctype>");
1489
        }
1490

    
1491
        xmlquery.append("<querygroup operator=\"UNION\">");
1492
        //chad added - 8/14
1493
        //the if statement allows a query to gracefully handle a null
1494
        //query. Without this if a nullpointerException is thrown.
1495
        if (!value.equals("")) {
1496
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1497
            xmlquery.append("searchmode=\"contains\">");
1498
            xmlquery.append("<value>").append(value).append("</value>");
1499
            xmlquery.append("</queryterm>");
1500
        }
1501
        xmlquery.append("</querygroup>");
1502
        xmlquery.append("</pathquery>");
1503

    
1504
        return (xmlquery.toString());
1505
    }
1506

    
1507
    /**
1508
     * format a simple free-text value query as an XML document that conforms
1509
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1510
     * structured query engine
1511
     *
1512
     * @param value the text string to search for in the xml catalog
1513
     */
1514
    public static String createQuery(String value)
1515
    {
1516
        return createQuery(value, "any");
1517
    }
1518

    
1519
    /**
1520
     * Check for "READ" permission on @docid for @user and/or @group from DB
1521
     * connection
1522
     */
1523
    private boolean hasPermission(String user, String[] groups, String docid)
1524
            throws SQLException, Exception
1525
    {
1526
        // Check for READ permission on @docid for @user and/or @groups
1527
        PermissionController controller = new PermissionController(docid);
1528
        return controller.hasPermission(user, groups,
1529
                AccessControlInterface.READSTRING);
1530
    }
1531

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

    
1547
        // Check the parameter
1548
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1549

    
1550
        //the query stirng
1551
        String query = "SELECT subject, object from xml_relation where docId = ?";
1552
        try {
1553
            dbConn = DBConnectionPool
1554
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1555
            serialNumber = dbConn.getCheckOutSerialNumber();
1556
            pStmt = dbConn.prepareStatement(query);
1557
            //bind the value to query
1558
            pStmt.setString(1, dataPackageDocid);
1559

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

    
1575
                //don't put the duplicate docId into the vector
1576
                if (!docIdList.contains(docIdInSubjectField)) {
1577
                    docIdList.add(docIdInSubjectField);
1578
                }
1579

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

    
1608
    /**
1609
     * Get all docIds list for a data packadge
1610
     *
1611
     * @param dataPackageDocid, the string in docId field of xml_relation table
1612
     */
1613
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1614
    {
1615

    
1616
        Vector docIdList = new Vector();//return value
1617
        Vector tripleList = null;
1618
        String xml = null;
1619

    
1620
        // Check the parameter
1621
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1622

    
1623
        try {
1624
            //initial a documentImpl object
1625
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocid);
1626
            //transfer to documentImpl object to string
1627
            xml = packageDocument.toString();
1628

    
1629
            //create a tripcollection object
1630
            TripleCollection tripleForPackage = new TripleCollection(
1631
                    new StringReader(xml));
1632
            //get the vetor of triples
1633
            tripleList = tripleForPackage.getCollection();
1634

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

    
1654
        // return result
1655
        return docIdList;
1656
    }//getDocidListForPackageInXMLRevisions()
1657

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

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

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

    
1759
        }//try
1760
        catch (SQLException e) {
1761
            MetaCatUtil.debugMessage(
1762
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1763
                            + e.getMessage(), 30);
1764
            throw e;
1765
        }//catch
1766
        finally {
1767
            try {
1768
                pStmt.close();
1769
            }//try
1770
            catch (SQLException ee) {
1771
                MetaCatUtil.debugMessage(
1772
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1773
                                + ee.getMessage(), 30);
1774
            }//catch
1775
            finally {
1776
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1777
            }//finally
1778
        }//finally
1779
        return rev;
1780
    }//getCurrentRevFromXMLDoumentsTable
1781

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

    
1798
        byteString = docImpl.toString().getBytes();
1799
        //use docId as the zip entry's name
1800
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1801
                + docImpl.getDocID());
1802
        zEntry.setSize(byteString.length);
1803
        zipOut.putNextEntry(zEntry);
1804
        zipOut.write(byteString, 0, byteString.length);
1805
        zipOut.closeEntry();
1806

    
1807
    }//addDocToZipOutputStream()
1808

    
1809
    /**
1810
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1811
     * only inlcudes current version. If a DocumentImple object couldn't find
1812
     * for a docid, then the String of this docid was added to vetor rather
1813
     * than DocumentImple object.
1814
     *
1815
     * @param docIdList, a vetor hold a docid list for a data package. In
1816
     *            docid, there is not version number in it.
1817
     */
1818

    
1819
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1820
            throws McdbException, Exception
1821
    {
1822
        //Connection dbConn=null;
1823
        Vector documentImplList = new Vector();
1824
        int rev = 0;
1825

    
1826
        // Check the parameter
1827
        if (docIdList.isEmpty()) { return documentImplList; }//if
1828

    
1829
        //for every docid in vector
1830
        for (int i = 0; i < docIdList.size(); i++) {
1831
            try {
1832
                //get newest version for this docId
1833
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1834
                        .elementAt(i));
1835

    
1836
                // There is no record for this docId in xml_documents table
1837
                if (rev == -5) {
1838
                    // Rather than put DocumentImple object, put a String
1839
                    // Object(docid)
1840
                    // into the documentImplList
1841
                    documentImplList.add((String) docIdList.elementAt(i));
1842
                    // Skip other code
1843
                    continue;
1844
                }
1845

    
1846
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1847
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1848

    
1849
                //create new documentImpl object
1850
                DocumentImpl documentImplObject = new DocumentImpl(
1851
                        docidPlusVersion);
1852
                //add them to vector
1853
                documentImplList.add(documentImplObject);
1854
            }//try
1855
            catch (Exception e) {
1856
                MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1857
                        + e.getMessage(), 30);
1858
                // continue the for loop
1859
                continue;
1860
            }
1861
        }//for
1862
        return documentImplList;
1863
    }
1864

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

    
1881
        // Check the parameter
1882
        if (docIdList.isEmpty()) { return documentImplList; }//if
1883

    
1884
        //for every docid in vector
1885
        for (int i = 0; i < docIdList.size(); i++) {
1886

    
1887
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1888

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

    
1915
        }//for
1916
        return documentImplList;
1917
    }//getOldVersionAllDocumentImple
1918

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

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

    
1975
        //create a DBTransform ojbect
1976
        xmlToHtml = new DBTransform();
1977
        //head of html
1978
        htmlDoc.append("<html><head></head><body>");
1979
        for (int i = 0; i < docImplList.size(); i++) {
1980
            // If this String object, this means it is missed data file
1981
            if ((((docImplList.elementAt(i)).getClass()).toString())
1982
                    .equals("class java.lang.String")) {
1983

    
1984
                htmlDoc.append("<a href=\"");
1985
                String dataFileid = (String) docImplList.elementAt(i);
1986
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1987
                htmlDoc.append("Data File: ");
1988
                htmlDoc.append(dataFileid).append("</a><br>");
1989
                htmlDoc.append("<br><hr><br>");
1990

    
1991
            }//if
1992
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
1993
                    .compareTo("BIN") != 0) { //this is an xml file so we can
1994
                                              // transform it.
1995
                //transform each file individually then concatenate all of the
1996
                //transformations together.
1997

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

    
2032
    }//addHtmlSummaryToZipOutputStream
2033

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

    
2058
        String docId = null;
2059
        int version = -5;
2060
        // Docid without revision
2061
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2062
        // revision number
2063
        version = MetaCatUtil.getVersionFromString(docIdString);
2064

    
2065
        //check if the reqused docId is a data package id
2066
        if (!isDataPackageId(docId)) {
2067

    
2068
            /*
2069
             * Exception e = new Exception("The request the doc id "
2070
             * +docIdString+ " is not a data package id");
2071
             */
2072

    
2073
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2074
            // zip
2075
            //up the single document and return the zip file.
2076
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2077

    
2078
                Exception e = new Exception("User " + user
2079
                        + " does not have permission"
2080
                        + " to export the data package " + docIdString);
2081
                throw e;
2082
            }
2083

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

    
2101
            zOut.finish(); //terminate the zip file
2102
            return zOut;
2103
        }
2104
        // Check the permission of user
2105
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2106

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

    
2132
            }//if
2133
            else if (version > currentVersion || version < -1) {
2134
                throw new Exception("The user specified docid: " + docId + "."
2135
                        + version + " doesn't exist");
2136
            }//else if
2137
            else //for an old version
2138
            {
2139

    
2140
                rootName = docIdString
2141
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2142
                //get the whole id list for data packadge
2143
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2144

    
2145
                //get the whole documentImple object
2146
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2147
            }//else
2148

    
2149
            // Make sure documentImplist is not empty
2150
            if (documentImplList.isEmpty()) { throw new Exception(
2151
                    "Couldn't find component for data package: " + packageId); }//if
2152

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

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

    
2212
                        }//if
2213
                        else {
2214
                            //it is data file
2215
                            addDataFileToZipOutputStream(docImpls, zOut,
2216
                                    rootName);
2217
                            htmlDocumentImplList.add(docImpls);
2218
                        }//else
2219
                    }//if
2220
                }//else
2221
            }//for
2222

    
2223
            //add html summary file
2224
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2225
                    rootName);
2226
            zOut.finish(); //terminate the zip file
2227
            //dbConn.close();
2228
            return zOut;
2229
        }//else
2230
    }//getZippedPackage()
2231

    
2232
    private class ReturnFieldValue
2233
    {
2234

    
2235
        private String docid = null; //return field value for this docid
2236

    
2237
        private String fieldValue = null;
2238

    
2239
        private String xmlFieldValue = null; //return field value in xml
2240
                                             // format
2241

    
2242
        public void setDocid(String myDocid)
2243
        {
2244
            docid = myDocid;
2245
        }
2246

    
2247
        public String getDocid()
2248
        {
2249
            return docid;
2250
        }
2251

    
2252
        public void setFieldValue(String myValue)
2253
        {
2254
            fieldValue = myValue;
2255
        }
2256

    
2257
        public String getFieldValue()
2258
        {
2259
            return fieldValue;
2260
        }
2261

    
2262
        public void setXMLFieldValue(String xml)
2263
        {
2264
            xmlFieldValue = xml;
2265
        }
2266

    
2267
        public String getXMLFieldValue()
2268
        {
2269
            return xmlFieldValue;
2270
        }
2271

    
2272
    }
2273
}
(22-22/63)