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-18 11:19:52 -0800 (Fri, 18 Mar 2005) $'
15
 * '$Revision: 2425 $'
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
     if(usage_count > count){
628
         enterRecords = true;
629
     }
630

    
631
     if(returnfield_id < 0){
632
         MetaCatUtil.debugMessage("Error in getting returnfield id from"
633
                                  + "xml_returnfield table", 20);
634
     }
635

    
636

    
637

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

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

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

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

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

    
671

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

    
684
	 // check if the enterRecords is true, elements is not null, element's 
685
         // length is less than the limit of table column and if the document 
686
         // has been indexed already
687
         if(enterRecords && element != null 
688
		&& element.length() < offset
689
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
690
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
691
                 + "queryresult_string) VALUES ('" + returnfield_id
692
                 + "', '" + key + "', '" + element + "')";
693
             PreparedStatement pstmt = null;
694
             pstmt = dbconn.prepareStatement(query);
695
             dbconn.increaseUsageCount(1);
696
             pstmt.execute();
697
             pstmt.close();
698
         }
699

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

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

    
711

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

    
727
     return resultset;
728
 }
729

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

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

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

    
752

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

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

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

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

    
796

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

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

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

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

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

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

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

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

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

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

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

    
884

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

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

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

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

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

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

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

    
1036
     }//if has extended query
1037

    
1038
      return docListResult;
1039
    }//addReturnfield
1040

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

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

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

    
1104
    return docListResult;
1105
  }//addRelation
1106

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

    
1127

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

    
1134
        Vector tempVector = null;
1135

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

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

    
1150
        Vector tempVector = null;
1151

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

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

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

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

    
1175
        Vector tempVector = null;
1176

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

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

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

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

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

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

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

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

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

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

    
1278
    }
1279

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

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

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

    
1326

    
1327

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1502
        return (xmlquery.toString());
1503
    }
1504

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1652
        // return result
1653
        return docIdList;
1654
    }//getDocidListForPackageInXMLRevisions()
1655

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

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

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

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

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

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

    
1805
    }//addDocToZipOutputStream()
1806

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

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

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

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

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

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

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

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

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

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

    
1885
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1886

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

    
1913
        }//for
1914
        return documentImplList;
1915
    }//getOldVersionAllDocumentImple
1916

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

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

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

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

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

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

    
2030
    }//addHtmlSummaryToZipOutputStream
2031

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2230
    private class ReturnFieldValue
2231
    {
2232

    
2233
        private String docid = null; //return field value for this docid
2234

    
2235
        private String fieldValue = null;
2236

    
2237
        private String xmlFieldValue = null; //return field value in xml
2238
                                             // format
2239

    
2240
        public void setDocid(String myDocid)
2241
        {
2242
            docid = myDocid;
2243
        }
2244

    
2245
        public String getDocid()
2246
        {
2247
            return docid;
2248
        }
2249

    
2250
        public void setFieldValue(String myValue)
2251
        {
2252
            fieldValue = myValue;
2253
        }
2254

    
2255
        public String getFieldValue()
2256
        {
2257
            return fieldValue;
2258
        }
2259

    
2260
        public void setXMLFieldValue(String xml)
2261
        {
2262
            xmlFieldValue = xml;
2263
        }
2264

    
2265
        public String getXMLFieldValue()
2266
        {
2267
            return xmlFieldValue;
2268
        }
2269

    
2270
    }
2271
}
(22-22/63)