Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *    Release: @release@
12
 *
13
 *   '$Author: jones $'
14
 *     '$Date: 2005-11-16 17:27:26 -0800 (Wed, 16 Nov 2005) $'
15
 * '$Revision: 2752 $'
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
import org.apache.log4j.Logger;
58

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

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

    
71
    static final int ALL = 1;
72

    
73
    static final int WRITE = 2;
74

    
75
    static final int READ = 4;
76

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

    
80
    private MetaCatUtil util = new MetaCatUtil();
81

    
82
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
83

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

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

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

    
114
                // Time the request if asked for
115
                double startTime = System.currentTimeMillis();
116

    
117
                // Open a connection to the database
118
                MetaCatUtil util = new MetaCatUtil();
119
                //Connection dbconn = util.openDBConnection();
120

    
121
                double connTime = System.currentTimeMillis();
122

    
123
                // Execute the query
124
                DBQuery queryobj = new DBQuery();
125
                FileReader xml = new FileReader(new File(xmlfile));
126
                Hashtable nodelist = null;
127
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
128

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

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

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

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

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

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

    
197

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

    
216
  }
217

    
218

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

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

    
258

    
259

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

    
278
         DBTransform trans = new DBTransform();
279
         response.setContentType("text/html");
280
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
281
                                 "-//W3C//HTML//EN", qformat, out, params,
282
                                 sessionid);
283

    
284
        }
285
        catch(Exception e)
286
        {
287
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
288
                                +e.getMessage());
289
         }
290

    
291
      }//else
292

    
293
    }
294

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

    
323
        //checkout the dbconnection
324
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
325
        serialNumber = dbconn.getCheckOutSerialNumber();
326

    
327
        //print out the search result
328
        // search the doc list
329
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
330
                                      dbconn, useXMLIndex);
331

    
332
      } //try
333
      catch (IOException ioe)
334
      {
335
        logMetacat.error("IO error in DBQuery.findDocuments:");
336
        logMetacat.error(ioe.getMessage());
337

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

    
361
    return resultset;
362
  }//createResultDocuments
363

    
364

    
365

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

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

    
422
      double startTime = System.currentTimeMillis() / 1000;
423
      pstmt = dbconn.prepareStatement(query);
424

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

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

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

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

    
504
                String docid_org = xmldoc.getDocID();
505
                if (docid_org == null)
506
                {
507
                   logMetacat.info("Docid_org was null.");
508
                   //continue;
509
                }
510
                docid = docid_org.trim();
511
                docname = xmldoc.getDocname();
512
                doctype = xmldoc.getDoctype();
513
                createDate = xmldoc.getCreateDate();
514
                updateDate = xmldoc.getUpdateDate();
515
                rev = xmldoc.getRev();
516
                document = new StringBuffer();
517

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

    
543

    
544
                // Get the next package document linked to our hit
545
                hasBtRows = btrs.next();
546
              }//while
547
              npstmt.close();
548
              btrs.close();
549
        }
550
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
551
        {
552

    
553
           document = new StringBuffer();
554

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

    
579

    
580
        }//else
581
        // when doclist reached the offset number, send out doc list and empty
582
        // the hash table
583
        if (count == offset)
584
        {
585
          //reset count
586
          count = 0;
587
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
588
                              user, groups,dbconn, useXMLIndex);
589
          // reset docListResult
590
          docListResult = new Hashtable();
591

    
592
        }
593
       // Advance to the next record in the cursor
594
       tableHasRows = rs.next();
595
     }//while
596
     rs.close();
597
     pstmt.close();
598
     //if docListResult is not empty, it need to be sent.
599
     if (!docListResult.isEmpty())
600
     {
601
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
602
                              user, groups,dbconn, useXMLIndex);
603
     }
604
     double docListTime = System.currentTimeMillis() / 1000;
605
     logMetacat.warn("prepare docid list time: "
606
                    + (docListTime - queryExecuteTime));
607

    
608
     return resultsetBuffer;
609
    }//findReturnDoclist
610

    
611

    
612
    /*
613
     * Send completed search hashtable(part of reulst)to output stream
614
     * and buffer into a buffer stream
615
     */
616
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
617
                                           StringBuffer resultset,
618
                                           PrintWriter out, Hashtable partOfDoclist,
619
                                           String user, String[]groups,
620
                                       DBConnection dbconn, boolean useXMLIndex)
621
                                       throws Exception
622
   {
623

    
624
     // check if there is a record in xml_returnfield
625
     // and get the returnfield_id and usage count
626
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
627
     boolean enterRecords = false;
628

    
629
     // get value of xml_returnfield_count
630
     int count = (new Integer(MetaCatUtil
631
                            .getOption("xml_returnfield_count")))
632
                            .intValue();
633

    
634
     // set enterRecords to true if usage_count is more than the offset
635
     // specified in metacat.properties
636
     if(usage_count > count){
637
         enterRecords = true;
638
     }
639

    
640
     if(returnfield_id < 0){
641
         logMetacat.warn("Error in getting returnfield id from"
642
                                  + "xml_returnfield table");
643
	enterRecords = false;
644
     }
645

    
646
     // get the hashtable containing the docids that already in the
647
     // xml_queryresult table
648
     logMetacat.info("size of partOfDoclist before"
649
                             + " docidsInQueryresultTable(): "
650
                             + partOfDoclist.size());
651
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
652
                                                        partOfDoclist, dbconn);
653

    
654
     // remove the keys in queryresultDocList from partOfDoclist
655
     Enumeration _keys = queryresultDocList.keys();
656
     while (_keys.hasMoreElements()){
657
         partOfDoclist.remove(_keys.nextElement());
658
     }
659

    
660
     // backup the keys-elements in partOfDoclist to check later
661
     // if the doc entry is indexed yet
662
     Hashtable partOfDoclistBackup = new Hashtable();
663
     _keys = partOfDoclist.keys();
664
     while (_keys.hasMoreElements()){
665
	 Object key = _keys.nextElement();
666
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
667
     }
668

    
669
     logMetacat.info("size of partOfDoclist after"
670
                             + " docidsInQueryresultTable(): "
671
                             + partOfDoclist.size());
672

    
673
     //add return fields for the documents in partOfDoclist
674
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
675
                                        dbconn, useXMLIndex );
676
     //add relationship part part docid list for the documents in partOfDocList
677
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
678

    
679

    
680
     Enumeration keys = partOfDoclist.keys();
681
     String key = null;
682
     String element = null;
683
     String query = null;
684
     int offset = (new Integer(MetaCatUtil
685
                               .getOption("queryresult_string_length")))
686
                               .intValue();
687
     while (keys.hasMoreElements())
688
     {
689
         key = (String) keys.nextElement();
690
         element = (String)partOfDoclist.get(key);
691

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

    
701
             PreparedStatement pstmt = null;
702
             pstmt = dbconn.prepareStatement(query);
703
             pstmt.setInt(1, returnfield_id);
704
             pstmt.setString(2, key);
705
             pstmt.setString(3, element);
706

    
707
             dbconn.increaseUsageCount(1);
708
             pstmt.execute();
709
             pstmt.close();
710
         }
711

    
712
         // A string with element
713
         String xmlElement = "  <document>" + element + "</document>";
714

    
715
         //send single element to output
716
         if (out != null)
717
         {
718
             out.println(xmlElement);
719
         }
720
         resultset.append(xmlElement);
721
     }//while
722

    
723

    
724
     keys = queryresultDocList.keys();
725
     while (keys.hasMoreElements())
726
     {
727
         key = (String) keys.nextElement();
728
         element = (String)queryresultDocList.get(key);
729
         // A string with element
730
         String xmlElement = "  <document>" + element + "</document>";
731
         //send single element to output
732
         if (out != null)
733
         {
734
             out.println(xmlElement);
735
         }
736
         resultset.append(xmlElement);
737
     }//while
738

    
739
     return resultset;
740
 }
741

    
742
   /**
743
    * Get the docids already in xml_queryresult table and corresponding
744
    * queryresultstring as a hashtable
745
    */
746
   private Hashtable docidsInQueryresultTable(int returnfield_id,
747
                                              Hashtable partOfDoclist,
748
                                              DBConnection dbconn){
749

    
750
         Hashtable returnValue = new Hashtable();
751
         PreparedStatement pstmt = null;
752
         ResultSet rs = null;
753

    
754
         // get partOfDoclist as string for the query
755
         Enumeration keylist = partOfDoclist.keys();
756
         StringBuffer doclist = new StringBuffer();
757
         while (keylist.hasMoreElements())
758
         {
759
             doclist.append("'");
760
             doclist.append((String) keylist.nextElement());
761
             doclist.append("',");
762
         }//while
763

    
764

    
765
         if (doclist.length() > 0)
766
         {
767
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
768

    
769
             // the query to find out docids from xml_queryresult
770
             String query = "select docid, queryresult_string from "
771
                          + "xml_queryresult where returnfield_id = " +
772
                          returnfield_id +" and docid in ("+ doclist + ")";
773
             logMetacat.info("Query to get docids from xml_queryresult:"
774
                                      + query);
775

    
776
             try {
777
                 // prepare and execute the query
778
                 pstmt = dbconn.prepareStatement(query);
779
                 dbconn.increaseUsageCount(1);
780
                 pstmt.execute();
781
                 rs = pstmt.getResultSet();
782
                 boolean tableHasRows = rs.next();
783
                 while (tableHasRows) {
784
                     // store the returned results in the returnValue hashtable
785
                     String key = rs.getString(1);
786
                     String element = rs.getString(2);
787

    
788
                     if(element != null){
789
                         returnValue.put(key, element);
790
                     } else {
791
                         logMetacat.info("Null elment found ("
792
                         + "DBQuery.docidsInQueryresultTable)");
793
                     }
794
                     tableHasRows = rs.next();
795
                 }
796
                 rs.close();
797
                 pstmt.close();
798
             } catch (Exception e){
799
                 logMetacat.error("Error getting docids from "
800
                                          + "queryresult in "
801
                                          + "DBQuery.docidsInQueryresultTable: "
802
                                          + e.getMessage());
803
              }
804
         }
805
         return returnValue;
806
     }
807

    
808

    
809
   /**
810
    * Method to get id from xml_returnfield table
811
    * for a given query specification
812
    */
813
   private int returnfield_id;
814
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
815
                                           DBConnection dbconn){
816
       int id = -1;
817
       int count = 1;
818
       PreparedStatement pstmt = null;
819
       ResultSet rs = null;
820
       String returnfield = qspec.getSortedReturnFieldString();
821

    
822
       // query for finding the id from xml_returnfield
823
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
824
            + "WHERE returnfield_string LIKE ?";
825
       logMetacat.info("ReturnField Query:" + query);
826

    
827
       try {
828
           // prepare and run the query
829
           pstmt = dbconn.prepareStatement(query);
830
           pstmt.setString(1,returnfield);
831
           dbconn.increaseUsageCount(1);
832
           pstmt.execute();
833
           rs = pstmt.getResultSet();
834
           boolean tableHasRows = rs.next();
835

    
836
           // if record found then increase the usage count
837
           // else insert a new record and get the id of the new record
838
           if(tableHasRows){
839
               // get the id
840
               id = rs.getInt(1);
841
               count = rs.getInt(2) + 1;
842
               rs.close();
843
               pstmt.close();
844

    
845
               // increase the usage count
846
               query = "UPDATE xml_returnfield SET usage_count ='" + count
847
                   + "' WHERE returnfield_id ='"+ id +"'";
848
               logMetacat.info("ReturnField Table Update:"+ query);
849

    
850
               pstmt = dbconn.prepareStatement(query);
851
               dbconn.increaseUsageCount(1);
852
               pstmt.execute();
853
               pstmt.close();
854

    
855
           } else {
856
               rs.close();
857
               pstmt.close();
858

    
859
               // insert a new record
860
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
861
                   + "VALUES (?, '1')";
862
               logMetacat.info("ReturnField Table Insert:"+ query);
863
               pstmt = dbconn.prepareStatement(query);
864
               pstmt.setString(1, returnfield);
865
               dbconn.increaseUsageCount(1);
866
               pstmt.execute();
867
               pstmt.close();
868

    
869
               // get the id of the new record
870
               query = "SELECT returnfield_id FROM xml_returnfield "
871
                   + "WHERE returnfield_string LIKE ?";
872
               logMetacat.info("ReturnField query after Insert:" + query);
873
               pstmt = dbconn.prepareStatement(query);
874
               pstmt.setString(1, returnfield);
875

    
876
               dbconn.increaseUsageCount(1);
877
               pstmt.execute();
878
               rs = pstmt.getResultSet();
879
               if(rs.next()){
880
                   id = rs.getInt(1);
881
               } else {
882
                   id = -1;
883
               }
884
               rs.close();
885
               pstmt.close();
886
           }
887

    
888
       } catch (Exception e){
889
           logMetacat.error("Error getting id from xml_returnfield in "
890
                                     + "DBQuery.getXmlReturnfieldsTableId: "
891
                                     + e.getMessage());
892
           id = -1;
893
       }
894

    
895
       returnfield_id = id;
896
       return count;
897
   }
898

    
899

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

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

    
954
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
955
           logMetacat.info( "Time for execute access extended query: "
956
                          + (extendedAccessQueryEnd - extendedQueryStart));
957

    
958
           String extendedQuery =
959
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
960
           logMetacat.warn("Extended query: " + extendedQuery);
961

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

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

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

    
1048
           // get attribures return
1049
           docListResult = getAttributeValueForReturn(qspec,
1050
                           docListResult, doclist.toString(), useXMLIndex);
1051
       }//if doclist lenght is great than zero
1052

    
1053
     }//if has extended query
1054

    
1055
      return docListResult;
1056
    }//addReturnfield
1057

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

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

    
1110
        String removedelement = (String) docListResult.remove(docidkey);
1111
        docListResult.put(docidkey, removedelement+ document.toString());
1112
        tableHasRows = rs.next();
1113
      }//while
1114
      rs.close();
1115
      pstmt.close();
1116
    }//while
1117
    double endRelation = System.currentTimeMillis() / 1000;
1118
    logMetacat.info("Time for adding relation to docListResult: "
1119
                             + (endRelation - startRelation));
1120

    
1121
    return docListResult;
1122
  }//addRelation
1123

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

    
1144

    
1145
    /*
1146
     * A method to search if Vector contains a particular key string
1147
     */
1148
    private boolean containsKey(Vector parentidList, String parentId)
1149
    {
1150

    
1151
        Vector tempVector = null;
1152

    
1153
        for (int count = 0; count < parentidList.size(); count++) {
1154
            tempVector = (Vector) parentidList.get(count);
1155
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1156
        }
1157
        return false;
1158
    }
1159

    
1160
    /*
1161
     * A method to put key and value in Vector
1162
     */
1163
    private void putInArray(Vector parentidList, String key,
1164
            ReturnFieldValue value)
1165
    {
1166

    
1167
        Vector tempVector = null;
1168

    
1169
        for (int count = 0; count < parentidList.size(); count++) {
1170
            tempVector = (Vector) parentidList.get(count);
1171

    
1172
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1173
                tempVector.remove(1);
1174
                tempVector.add(1, value);
1175
                return;
1176
            }
1177
        }
1178

    
1179
        tempVector = new Vector();
1180
        tempVector.add(0, key);
1181
        tempVector.add(1, value);
1182
        parentidList.add(tempVector);
1183
        return;
1184
    }
1185

    
1186
    /*
1187
     * A method to get value in Vector given a key
1188
     */
1189
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1190
    {
1191

    
1192
        Vector tempVector = null;
1193

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

    
1197
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1198
                    .get(1); }
1199
        }
1200
        return null;
1201
    }
1202

    
1203
    /*
1204
     * A method to get enumeration of all values in Vector
1205
     */
1206
    private Vector getElements(Vector parentidList)
1207
    {
1208
        Vector enumVector = new Vector();
1209
        Vector tempVector = null;
1210

    
1211
        for (int count = 0; count < parentidList.size(); count++) {
1212
            tempVector = (Vector) parentidList.get(count);
1213

    
1214
            enumVector.add(tempVector.get(1));
1215
        }
1216
        return enumVector;
1217
    }
1218

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

    
1234
        //check the parameter
1235
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1236

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

    
1255
                    XML.append("<param name=\"");
1256
                    XML.append(fieldname);
1257
                    XML.append("/");
1258
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1259
                    XML.append(attirbuteName);
1260
                    XML.append("\">");
1261
                    XML.append(fielddata);
1262
                    XML.append("</param>");
1263
                    tableHasRows = rs.next();
1264

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

    
1296
    }
1297

    
1298
    /*
1299
     * A method to create a query to get owner's docid list
1300
     */
1301
    private String getOwnerQuery(String owner)
1302
    {
1303
        if (owner != null) {
1304
            owner = owner.toLowerCase();
1305
        }
1306
        StringBuffer self = new StringBuffer();
1307

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

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

    
1344

    
1345

    
1346
        if (params.containsKey("meta_file_id")) {
1347
            query.append("<meta_file_id>");
1348
            query.append(((String[]) params.get("meta_file_id"))[0]);
1349
            query.append("</meta_file_id>");
1350
        }
1351

    
1352
        if (params.containsKey("returndoctype")) {
1353
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1354
            for (int i = 0; i < returnDoctypes.length; i++) {
1355
                String doctype = (String) returnDoctypes[i];
1356

    
1357
                if (!doctype.equals("any") && !doctype.equals("ANY")
1358
                        && !doctype.equals("")) {
1359
                    query.append("<returndoctype>").append(doctype);
1360
                    query.append("</returndoctype>");
1361
                }
1362
            }
1363
        }
1364

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

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

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

    
1389
        if (params.containsKey("site")) {
1390
            String[] site = ((String[]) params.get("site"));
1391
            for (int i = 0; i < site.length; i++) {
1392
                query.append("<site>").append(site[i]);
1393
                query.append("</site>");
1394
            }
1395
        }
1396

    
1397
        //allows the dynamic switching of boolean operators
1398
        if (params.containsKey("operator")) {
1399
            query.append("<querygroup operator=\""
1400
                    + ((String[]) params.get("operator"))[0] + "\">");
1401
        } else { //the default operator is UNION
1402
            query.append("<querygroup operator=\"UNION\">");
1403
        }
1404

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

    
1411
        if (params.containsKey("searchmode")) {
1412
            searchmode = ((String[]) params.get("searchmode"))[0];
1413
        } else {
1414
            searchmode = "contains";
1415
        }
1416

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

    
1434
        //this while loop finds the rest of the parameters
1435
        //and attempts to query for the field specified
1436
        //by the parameter.
1437
        elements = params.elements();
1438
        keys = params.keys();
1439
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1440
            nextkey = keys.nextElement();
1441
            nextelement = elements.nextElement();
1442

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

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

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

    
1502
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1503
            xmlquery.append("<returndoctype>");
1504
            xmlquery.append(doctype).append("</returndoctype>");
1505
        }
1506

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

    
1520
        return (xmlquery.toString());
1521
    }
1522

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

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

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

    
1563
        // Check the parameter
1564
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1565

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

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

    
1591
                //don't put the duplicate docId into the vector
1592
                if (!docIdList.contains(docIdInSubjectField)) {
1593
                    docIdList.add(docIdInSubjectField);
1594
                }
1595

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

    
1624
    /**
1625
     * Get all docIds list for a data packadge
1626
     *
1627
     * @param dataPackageDocid, the string in docId field of xml_relation table
1628
     */
1629
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1630
    {
1631

    
1632
        Vector docIdList = new Vector();//return value
1633
        Vector tripleList = null;
1634
        String xml = null;
1635

    
1636
        // Check the parameter
1637
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1638

    
1639
        try {
1640
            //initial a documentImpl object
1641
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1642
            //transfer to documentImpl object to string
1643
            xml = packageDocument.toString();
1644

    
1645
            //create a tripcollection object
1646
            TripleCollection tripleForPackage = new TripleCollection(
1647
                    new StringReader(xml));
1648
            //get the vetor of triples
1649
            tripleList = tripleForPackage.getCollection();
1650

    
1651
            for (int i = 0; i < tripleList.size(); i++) {
1652
                //put subject docid into docIdlist without duplicate
1653
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1654
                        .getSubject())) {
1655
                    //put subject docid into docIdlist
1656
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1657
                }
1658
                //put object docid into docIdlist without duplicate
1659
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1660
                        .getObject())) {
1661
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1662
                }
1663
            }//for
1664
        }//try
1665
        catch (Exception e) {
1666
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1667
                    + e.getMessage());
1668
        }//catch
1669

    
1670
        // return result
1671
        return docIdList;
1672
    }//getDocidListForPackageInXMLRevisions()
1673

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

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

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

    
1775
        }//try
1776
        catch (SQLException e) {
1777
            logMetacat.error(
1778
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1779
                            + e.getMessage());
1780
            throw e;
1781
        }//catch
1782
        finally {
1783
            try {
1784
                pStmt.close();
1785
            }//try
1786
            catch (SQLException ee) {
1787
                logMetacat.error(
1788
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1789
                                + ee.getMessage());
1790
            }//catch
1791
            finally {
1792
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1793
            }//finally
1794
        }//finally
1795
        return rev;
1796
    }//getCurrentRevFromXMLDoumentsTable
1797

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

    
1814
        byteString = docImpl.toString().getBytes();
1815
        //use docId as the zip entry's name
1816
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1817
                + docImpl.getDocID());
1818
        zEntry.setSize(byteString.length);
1819
        zipOut.putNextEntry(zEntry);
1820
        zipOut.write(byteString, 0, byteString.length);
1821
        zipOut.closeEntry();
1822

    
1823
    }//addDocToZipOutputStream()
1824

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

    
1835
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1836
            throws McdbException, Exception
1837
    {
1838
        //Connection dbConn=null;
1839
        Vector documentImplList = new Vector();
1840
        int rev = 0;
1841

    
1842
        // Check the parameter
1843
        if (docIdList.isEmpty()) { return documentImplList; }//if
1844

    
1845
        //for every docid in vector
1846
        for (int i = 0; i < docIdList.size(); i++) {
1847
            try {
1848
                //get newest version for this docId
1849
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1850
                        .elementAt(i));
1851

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

    
1862
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1863
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1864

    
1865
                //create new documentImpl object
1866
                DocumentImpl documentImplObject = new DocumentImpl(
1867
                        docidPlusVersion);
1868
                //add them to vector
1869
                documentImplList.add(documentImplObject);
1870
            }//try
1871
            catch (Exception e) {
1872
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
1873
                        + e.getMessage());
1874
                // continue the for loop
1875
                continue;
1876
            }
1877
        }//for
1878
        return documentImplList;
1879
    }
1880

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

    
1897
        // Check the parameter
1898
        if (docIdList.isEmpty()) { return documentImplList; }//if
1899

    
1900
        //for every docid in vector
1901
        for (int i = 0; i < docIdList.size(); i++) {
1902

    
1903
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1904

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

    
1931
        }//for
1932
        return documentImplList;
1933
    }//getOldVersionAllDocumentImple
1934

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

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

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

    
2000
                htmlDoc.append("<a href=\"");
2001
                String dataFileid = (String) docImplList.elementAt(i);
2002
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2003
                htmlDoc.append("Data File: ");
2004
                htmlDoc.append(dataFileid).append("</a><br>");
2005
                htmlDoc.append("<br><hr><br>");
2006

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

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

    
2048
    }//addHtmlSummaryToZipOutputStream
2049

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

    
2074
        String docId = null;
2075
        int version = -5;
2076
        // Docid without revision
2077
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2078
        // revision number
2079
        version = MetaCatUtil.getVersionFromString(docIdString);
2080

    
2081
        //check if the reqused docId is a data package id
2082
        if (!isDataPackageId(docId)) {
2083

    
2084
            /*
2085
             * Exception e = new Exception("The request the doc id "
2086
             * +docIdString+ " is not a data package id");
2087
             */
2088

    
2089
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2090
            // zip
2091
            //up the single document and return the zip file.
2092
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2093

    
2094
                Exception e = new Exception("User " + user
2095
                        + " does not have permission"
2096
                        + " to export the data package " + docIdString);
2097
                throw e;
2098
            }
2099

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

    
2117
            zOut.finish(); //terminate the zip file
2118
            return zOut;
2119
        }
2120
        // Check the permission of user
2121
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2122

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

    
2148
            }//if
2149
            else if (version > currentVersion || version < -1) {
2150
                throw new Exception("The user specified docid: " + docId + "."
2151
                        + version + " doesn't exist");
2152
            }//else if
2153
            else //for an old version
2154
            {
2155

    
2156
                rootName = docIdString
2157
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2158
                //get the whole id list for data packadge
2159
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2160

    
2161
                //get the whole documentImple object
2162
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2163
            }//else
2164

    
2165
            // Make sure documentImplist is not empty
2166
            if (documentImplList.isEmpty()) { throw new Exception(
2167
                    "Couldn't find component for data package: " + packageId); }//if
2168

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

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

    
2228
                        }//if
2229
                        else {
2230
                            //it is data file
2231
                            addDataFileToZipOutputStream(docImpls, zOut,
2232
                                    rootName);
2233
                            htmlDocumentImplList.add(docImpls);
2234
                        }//else
2235
                    }//if
2236
                }//else
2237
            }//for
2238

    
2239
            //add html summary file
2240
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2241
                    rootName);
2242
            zOut.finish(); //terminate the zip file
2243
            //dbConn.close();
2244
            return zOut;
2245
        }//else
2246
    }//getZippedPackage()
2247

    
2248
    private class ReturnFieldValue
2249
    {
2250

    
2251
        private String docid = null; //return field value for this docid
2252

    
2253
        private String fieldValue = null;
2254

    
2255
        private String xmlFieldValue = null; //return field value in xml
2256
                                             // format
2257

    
2258
        public void setDocid(String myDocid)
2259
        {
2260
            docid = myDocid;
2261
        }
2262

    
2263
        public String getDocid()
2264
        {
2265
            return docid;
2266
        }
2267

    
2268
        public void setFieldValue(String myValue)
2269
        {
2270
            fieldValue = myValue;
2271
        }
2272

    
2273
        public String getFieldValue()
2274
        {
2275
            return fieldValue;
2276
        }
2277

    
2278
        public void setXMLFieldValue(String xml)
2279
        {
2280
            xmlFieldValue = xml;
2281
        }
2282

    
2283
        public String getXMLFieldValue()
2284
        {
2285
            return xmlFieldValue;
2286
        }
2287

    
2288
    }
2289
}
(22-22/65)