Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *    Release: 1.4.0
12
 *
13
 *   '$Author: sgarg $'
14
 *     '$Date: 2005-03-18 08:51:37 -0800 (Fri, 18 Mar 2005) $'
15
 * '$Revision: 2424 $'
16
 *
17
 * This program is free software; you can redistribute it and/or modify
18
 * it under the terms of the GNU General Public License as published by
19
 * the Free Software Foundation; either version 2 of the License, or
20
 * (at your option) any later version.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
 * GNU General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU General Public License
28
 * along with this program; if not, write to the Free Software
29
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30
 */
31

    
32
package edu.ucsb.nceas.metacat;
33

    
34
import java.io.BufferedWriter;
35
import java.io.File;
36
import java.io.FileInputStream;
37
import java.io.FileReader;
38
import java.io.FileWriter;
39
import java.io.IOException;
40
import java.io.InputStream;
41
import java.io.PrintWriter;
42
import java.io.StringReader;
43
import java.io.StringWriter;
44
import java.sql.PreparedStatement;
45
import java.sql.ResultSet;
46
import java.sql.SQLException;
47
import java.util.Enumeration;
48
import java.util.Hashtable;
49
import java.util.StringTokenizer;
50
import java.util.Vector;
51
import java.util.zip.ZipEntry;
52
import java.util.zip.ZipOutputStream;
53

    
54
import javax.servlet.ServletOutputStream;
55
import javax.servlet.http.HttpServletResponse;
56

    
57

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

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

    
70
    static final int ALL = 1;
71

    
72
    static final int WRITE = 2;
73

    
74
    static final int READ = 4;
75

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

    
79
    private MetaCatUtil util = new MetaCatUtil();
80

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

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

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

    
111
                // Time the request if asked for
112
                double startTime = System.currentTimeMillis();
113

    
114
                // Open a connection to the database
115
                MetaCatUtil util = new MetaCatUtil();
116
                //Connection dbconn = util.openDBConnection();
117

    
118
                double connTime = System.currentTimeMillis();
119

    
120
                // Execute the query
121
                DBQuery queryobj = new DBQuery(MetaCatUtil
122
                        .getOption("saxparser"));
123
                FileReader xml = new FileReader(new File(xmlfile));
124
                Hashtable nodelist = null;
125
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
126

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

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

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

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

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

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

    
194

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

    
213
  }
214

    
215

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

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

    
255

    
256

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

    
274
         DBTransform trans = new DBTransform();
275
         response.setContentType("text/html");
276
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
277
                                 "-//W3C//HTML//EN", qformat, out, params,
278
                                 sessionid);
279

    
280
        }
281
        catch(Exception e)
282
        {
283
         MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
284
                                +e.getMessage(), 30);
285
         }
286

    
287
      }//else
288

    
289
    }
290

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

    
319
        //checkout the dbconnection
320
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
321
        serialNumber = dbconn.getCheckOutSerialNumber();
322

    
323
        //print out the search result
324
        // search the doc list
325
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
326
                                      dbconn, useXMLIndex);
327

    
328
      } //try
329
      catch (IOException ioe)
330
      {
331
        MetaCatUtil.debugMessage("IO error in DBQuery.findDocuments:", 30);
332
        MetaCatUtil.debugMessage(ioe.getMessage(), 30);
333

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

    
357
    return resultset;
358
  }//createResultDocuments
359

    
360

    
361

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

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

    
418
      double startTime = System.currentTimeMillis() / 1000;
419
      pstmt = dbconn.prepareStatement(query);
420

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

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

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

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

    
498
                String docid_org = xmldoc.getDocID();
499
                if (docid_org == null)
500
                {
501
                   MetaCatUtil.debugMessage("Docid_org was null.", 40);
502
                   //continue;
503
                }
504
                docid = docid_org.trim();
505
                docname = xmldoc.getDocname();
506
                doctype = xmldoc.getDoctype();
507
                createDate = xmldoc.getCreateDate();
508
                updateDate = xmldoc.getUpdateDate();
509
                rev = xmldoc.getRev();
510
                document = new StringBuffer();
511

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

    
537

    
538
                // Get the next package document linked to our hit
539
                hasBtRows = btrs.next();
540
              }//while
541
              npstmt.close();
542
              btrs.close();
543
        }
544
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
545
        {
546

    
547
           document = new StringBuffer();
548

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

    
573

    
574
        }//else
575
        // when doclist reached the offset number, send out doc list and empty
576
        // the hash table
577
        if (count == offset)
578
        {
579
          //reset count
580
          count = 0;
581
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
582
                              user, groups,dbconn, useXMLIndex);
583
          // reset docListResult
584
          docListResult = new Hashtable();
585

    
586
        }
587
       // Advance to the next record in the cursor
588
       tableHasRows = rs.next();
589
     }//while
590
     rs.close();
591
     pstmt.close();
592
     //if docListResult is not empty, it need to be sent.
593
     if (!docListResult.isEmpty())
594
     {
595
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
596
                              user, groups,dbconn, useXMLIndex);
597
     }
598
     double docListTime = System.currentTimeMillis() / 1000;
599
     MetaCatUtil.debugMessage("prepare docid list time: "
600
                    + (docListTime - queryExecuteTime), 30);
601

    
602
     return resultsetBuffer;
603
    }//findReturnDoclist
604

    
605

    
606
    /*
607
     * Send completed search hashtable(part of reulst)to output stream
608
     * and buffer into a buffer stream
609
     */
610
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
611
                                           StringBuffer resultset,
612
                                           PrintWriter out, Hashtable partOfDoclist,
613
                                           String user, String[]groups,
614
                                       DBConnection dbconn, boolean useXMLIndex)
615
                                       throws Exception
616
   {
617

    
618
     // check if there is a record in xml_returnfield
619
     // and get the returnfield_id and usage count
620
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
621
     boolean enterRecords = false;
622

    
623
     // get value of xml_returnfield_count
624
     int count = (new Integer(MetaCatUtil
625
                            .getOption("xml_returnfield_count")))
626
                            .intValue();
627
     if(usage_count > count){
628
         enterRecords = true;
629
     }
630

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

    
636

    
637

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

    
646
     // remove the keys in queryresultDocList from partOfDoclist
647
     Enumeration _keys = queryresultDocList.keys();
648
     while (_keys.hasMoreElements()){
649
         partOfDoclist.remove(_keys.nextElement());
650
     }
651
     MetaCatUtil.debugMessage("size of partOfDoclist after"
652
                             + " docidsInQueryresultTable(): "
653
                             + partOfDoclist.size() , 50);
654

    
655
     //add return fields for the documents in partOfDoclist
656
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
657
                                        dbconn, useXMLIndex );
658
     //add relationship part part docid list for the documents in partOfDocList
659
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
660

    
661

    
662
     Enumeration keys = partOfDoclist.keys();
663
     String key = null;
664
     String element = null;
665
     String query = null;
666
     int offset = (new Integer(MetaCatUtil
667
                               .getOption("queryresult_string_length")))
668
                               .intValue();
669
     while (keys.hasMoreElements())
670
     {
671
         key = (String) keys.nextElement();
672
         element = (String)partOfDoclist.get(key);
673

    
674
         if(enterRecords && element != null && element.length() < offset){
675
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
676
                 + "queryresult_string) VALUES ('" + returnfield_id
677
                 + "', '" + key + "', '" + element + "')";
678
             PreparedStatement pstmt = null;
679
             pstmt = dbconn.prepareStatement(query);
680
             dbconn.increaseUsageCount(1);
681
             pstmt.execute();
682
             pstmt.close();
683
         }
684

    
685
         // A string with element
686
         String xmlElement = "  <document>" + element + "</document>";
687

    
688
         //send single element to output
689
         if (out != null)
690
         {
691
             out.println(xmlElement);
692
         }
693
         resultset.append(xmlElement);
694
     }//while
695

    
696

    
697
     keys = queryresultDocList.keys();
698
     while (keys.hasMoreElements())
699
     {
700
         key = (String) keys.nextElement();
701
         element = (String)queryresultDocList.get(key);
702
         // A string with element
703
         String xmlElement = "  <document>" + element + "</document>";
704
         //send single element to output
705
         if (out != null)
706
         {
707
             out.println(xmlElement);
708
         }
709
         resultset.append(xmlElement);
710
     }//while
711

    
712
     return resultset;
713
 }
714

    
715
   /**
716
    * Get the docids already in xml_queryresult table and corresponding
717
    * queryresultstring as a hashtable
718
    */
719
   private Hashtable docidsInQueryresultTable(int returnfield_id,
720
                                              Hashtable partOfDoclist,
721
                                              DBConnection dbconn){
722

    
723
         Hashtable returnValue = new Hashtable();
724
         PreparedStatement pstmt = null;
725
         ResultSet rs = null;
726

    
727
         // get partOfDoclist as string for the query
728
         Enumeration keylist = partOfDoclist.keys();
729
         StringBuffer doclist = new StringBuffer();
730
         while (keylist.hasMoreElements())
731
         {
732
             doclist.append("'");
733
             doclist.append((String) keylist.nextElement());
734
             doclist.append("',");
735
         }//while
736

    
737

    
738
         if (doclist.length() > 0)
739
         {
740
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
741

    
742
             // the query to find out docids from xml_queryresult
743
             String query = "select docid, queryresult_string from "
744
                          + "xml_queryresult where returnfield_id = " +
745
                          returnfield_id +" and docid in ("+ doclist + ")";
746
             MetaCatUtil.debugMessage("Query to get docids from xml_queryresult:"
747
                                      + query, 50);
748

    
749
             try {
750
                 // prepare and execute the query
751
                 pstmt = dbconn.prepareStatement(query);
752
                 dbconn.increaseUsageCount(1);
753
                 pstmt.execute();
754
                 rs = pstmt.getResultSet();
755
                 boolean tableHasRows = rs.next();
756
                 while (tableHasRows) {
757
                     // store the returned results in the returnValue hashtable
758
                     String key = rs.getString(1);
759
                     String element = rs.getString(2);
760

    
761
                     if(element != null){
762
                         returnValue.put(key, element);
763
                     } else {
764
                         MetaCatUtil.debugMessage("Null elment found ("
765
                         + "DBQuery.docidsInQueryresultTable)", 50);
766
                     }
767
                     tableHasRows = rs.next();
768
                 }
769
                 rs.close();
770
                 pstmt.close();
771
             } catch (Exception e){
772
                 MetaCatUtil.debugMessage("Error getting docids from "
773
                                          + "queryresult in "
774
                                          + "DBQuery.docidsInQueryresultTable: "
775
                                          + e.getMessage(), 20);
776
              }
777
         }
778
         return returnValue;
779
     }
780

    
781

    
782
   /**
783
    * Method to get id from xml_returnfield table
784
    * for a given query specification
785
    */
786
   private int returnfield_id;
787
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
788
                                           DBConnection dbconn){
789
       int id = -1;
790
       int count = 1;
791
       PreparedStatement pstmt = null;
792
       ResultSet rs = null;
793
       String returnfield = qspec.getSortedReturnFieldString();
794

    
795
       // query for finding the id from xml_returnfield
796
       String query = "select returnfield_id, usage_count from xml_returnfield "
797
           + "where returnfield_string like '" + returnfield +"'";
798
       MetaCatUtil.debugMessage("ReturnField Query:" + query, 50);
799

    
800
       try {
801
           // prepare and run the query
802
           pstmt = dbconn.prepareStatement(query);
803
           dbconn.increaseUsageCount(1);
804
           pstmt.execute();
805
           rs = pstmt.getResultSet();
806
           boolean tableHasRows = rs.next();
807

    
808
           // if record found then increase the usage count
809
           // else insert a new record and get the id of the new record
810
           if(tableHasRows){
811
               // get the id
812
               id = rs.getInt(1);
813
               count = rs.getInt(2) + 1;
814
               rs.close();
815
               pstmt.close();
816

    
817
               // increase the usage count
818
               query = "UPDATE xml_returnfield SET usage_count ='" + count
819
                   + "' WHERE returnfield_id ='"+ id +"'";
820
               MetaCatUtil.debugMessage("ReturnField Table Update:"+ query, 50);
821

    
822
               pstmt = dbconn.prepareStatement(query);
823
               dbconn.increaseUsageCount(1);
824
               pstmt.execute();
825
               pstmt.close();
826

    
827
           } else {
828
               rs.close();
829
               pstmt.close();
830

    
831
               // insert a new record
832
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
833
                   + "VALUES ('" + returnfield + "', '1')";
834
               MetaCatUtil.debugMessage("ReturnField Table Insert:"+ query, 50);
835
               pstmt = dbconn.prepareStatement(query);
836
               dbconn.increaseUsageCount(1);
837
               pstmt.execute();
838
               pstmt.close();
839

    
840
               // get the id of the new record
841
               query = "select returnfield_id from xml_returnfield "
842
                   + "where returnfield_string like '" + returnfield +"'";
843
               MetaCatUtil.debugMessage("ReturnField query after Insert:"
844
                                        + query, 50);
845
               pstmt = dbconn.prepareStatement(query);
846
               dbconn.increaseUsageCount(1);
847
               pstmt.execute();
848
               rs = pstmt.getResultSet();
849
               if(rs.next()){
850
                   id = rs.getInt(1);
851
               } else {
852
                   id = -1;
853
               }
854
               rs.close();
855
               pstmt.close();
856
           }
857

    
858
       } catch (Exception e){
859
           MetaCatUtil.debugMessage("Error getting id from xml_returnfield in "
860
                                     + "DBQuery.getXmlReturnfieldsTableId: "
861
                                     + e.getMessage(), 20);
862
           id = -1;
863
       }
864

    
865
       returnfield_id = id;
866
       return count;
867
   }
868

    
869

    
870
    /*
871
     * A method to add return field to return doclist hash table
872
     */
873
    private Hashtable addReturnfield(Hashtable docListResult,
874
                                      QuerySpecification qspec,
875
                                      String user, String[]groups,
876
                                      DBConnection dbconn, boolean useXMLIndex )
877
                                      throws Exception
878
    {
879
      PreparedStatement pstmt = null;
880
      ResultSet rs = null;
881
      String docid = null;
882
      String fieldname = null;
883
      String fielddata = null;
884
      String relation = null;
885

    
886
      if (qspec.containsExtendedSQL())
887
      {
888
        qspec.setUserName(user);
889
        qspec.setGroup(groups);
890
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
891
        Vector results = new Vector();
892
        Enumeration keylist = docListResult.keys();
893
        StringBuffer doclist = new StringBuffer();
894
        Vector parentidList = new Vector();
895
        Hashtable returnFieldValue = new Hashtable();
896
        while (keylist.hasMoreElements())
897
        {
898
          doclist.append("'");
899
          doclist.append((String) keylist.nextElement());
900
          doclist.append("',");
901
        }
902
        if (doclist.length() > 0)
903
        {
904
          Hashtable controlPairs = new Hashtable();
905
          double extendedQueryStart = System.currentTimeMillis() / 1000;
906
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
907
          // check if user has permission to see the return field data
908
          String accessControlSQL =
909
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
910
          pstmt = dbconn.prepareStatement(accessControlSQL);
911
          //increase dbconnection usage count
912
          dbconn.increaseUsageCount(1);
913
          pstmt.execute();
914
          rs = pstmt.getResultSet();
915
          boolean tableHasRows = rs.next();
916
          while (tableHasRows)
917
          {
918
            long startNodeId = rs.getLong(1);
919
            long endNodeId = rs.getLong(2);
920
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
921
            tableHasRows = rs.next();
922
          }
923

    
924
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
925
           MetaCatUtil.debugMessage( "Time for execute access extended query: "
926
                          + (extendedAccessQueryEnd - extendedQueryStart),30);
927

    
928
           String extendedQuery =
929
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
930
           MetaCatUtil.debugMessage("Extended query: " + extendedQuery, 30);
931
           pstmt = dbconn.prepareStatement(extendedQuery);
932
           //increase dbconnection usage count
933
           dbconn.increaseUsageCount(1);
934
           pstmt.execute();
935
           rs = pstmt.getResultSet();
936
           double extendedQueryEnd = System.currentTimeMillis() / 1000;
937
           MetaCatUtil.debugMessage("Time for execute extended query: "
938
                           + (extendedQueryEnd - extendedQueryStart), 30);
939
           tableHasRows = rs.next();
940
           while (tableHasRows)
941
           {
942
               ReturnFieldValue returnValue = new ReturnFieldValue();
943
               docid = rs.getString(1).trim();
944
               fieldname = rs.getString(2);
945
               fielddata = rs.getString(3);
946
               fielddata = MetaCatUtil.normalize(fielddata);
947
               String parentId = rs.getString(4);
948
               StringBuffer value = new StringBuffer();
949

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

    
992
            // put the merger node data info into doclistReult
993
            Enumeration xmlFieldValue = (getElements(parentidList)).elements();
994
            while (xmlFieldValue.hasMoreElements())
995
            {
996
              ReturnFieldValue object =
997
                  (ReturnFieldValue) xmlFieldValue.nextElement();
998
              docid = object.getDocid();
999
              if (docListResult.containsKey(docid))
1000
              {
1001
                 String removedelement = (String) docListResult.remove(docid);
1002
                 docListResult.
1003
                         put(docid, removedelement+ object.getXMLFieldValue());
1004
              }
1005
              else
1006
              {
1007
                docListResult.put(docid, object.getXMLFieldValue());
1008
               }
1009
             }//while
1010
             double docListResultEnd = System.currentTimeMillis() / 1000;
1011
             MetaCatUtil.debugMessage("Time for prepare doclistresult after"
1012
                                       + " execute extended query: "
1013
                                       + (docListResultEnd - extendedQueryEnd),
1014
                                      30);
1015

    
1016
              // get attribures return
1017
              docListResult = getAttributeValueForReturn(qspec,
1018
                            docListResult, doclist.toString(), useXMLIndex);
1019
       }//if doclist lenght is great than zero
1020

    
1021
     }//if has extended query
1022

    
1023
      return docListResult;
1024
    }//addReturnfield
1025

    
1026
    /*
1027
    * A method to add relationship to return doclist hash table
1028
    */
1029
   private Hashtable addRelationship(Hashtable docListResult,
1030
                                     QuerySpecification qspec,
1031
                                     DBConnection dbconn, boolean useXMLIndex )
1032
                                     throws Exception
1033
  {
1034
    PreparedStatement pstmt = null;
1035
    ResultSet rs = null;
1036
    StringBuffer document = null;
1037
    double startRelation = System.currentTimeMillis() / 1000;
1038
    Enumeration docidkeys = docListResult.keys();
1039
    while (docidkeys.hasMoreElements())
1040
    {
1041
      //String connstring =
1042
      // "metacat://"+util.getOption("server")+"?docid=";
1043
      String connstring = "%docid=";
1044
      String docidkey = (String) docidkeys.nextElement();
1045
      pstmt = dbconn.prepareStatement(QuerySpecification
1046
                      .printRelationSQL(docidkey));
1047
      pstmt.execute();
1048
      rs = pstmt.getResultSet();
1049
      boolean tableHasRows = rs.next();
1050
      while (tableHasRows)
1051
      {
1052
        String sub = rs.getString(1);
1053
        String rel = rs.getString(2);
1054
        String obj = rs.getString(3);
1055
        String subDT = rs.getString(4);
1056
        String objDT = rs.getString(5);
1057

    
1058
        document = new StringBuffer();
1059
        document.append("<triple>");
1060
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1061
        document.append("</subject>");
1062
        if (subDT != null)
1063
        {
1064
          document.append("<subjectdoctype>").append(subDT);
1065
          document.append("</subjectdoctype>");
1066
        }
1067
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1068
        document.append("</relationship>");
1069
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1070
        document.append("</object>");
1071
        if (objDT != null)
1072
        {
1073
          document.append("<objectdoctype>").append(objDT);
1074
          document.append("</objectdoctype>");
1075
        }
1076
        document.append("</triple>");
1077

    
1078
        String removedelement = (String) docListResult.remove(docidkey);
1079
        docListResult.put(docidkey, removedelement+ document.toString());
1080
        tableHasRows = rs.next();
1081
      }//while
1082
      rs.close();
1083
      pstmt.close();
1084
    }//while
1085
    double endRelation = System.currentTimeMillis() / 1000;
1086
    MetaCatUtil.debugMessage("Time for adding relation to docListResult: "
1087
                             + (endRelation - startRelation), 30);
1088

    
1089
    return docListResult;
1090
  }//addRelation
1091

    
1092
  /**
1093
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1094
   * string as a param instead of a hashtable.
1095
   *
1096
   * @param xmlquery a string representing a query.
1097
   */
1098
   private  String transformQuery(String xmlquery)
1099
   {
1100
     xmlquery = xmlquery.trim();
1101
     int index = xmlquery.indexOf("?>");
1102
     if (index != -1)
1103
     {
1104
       return xmlquery.substring(index + 2, xmlquery.length());
1105
     }
1106
     else
1107
     {
1108
       return xmlquery;
1109
     }
1110
   }
1111

    
1112

    
1113
    /*
1114
     * A method to search if Vector contains a particular key string
1115
     */
1116
    private boolean containsKey(Vector parentidList, String parentId)
1117
    {
1118

    
1119
        Vector tempVector = null;
1120

    
1121
        for (int count = 0; count < parentidList.size(); count++) {
1122
            tempVector = (Vector) parentidList.get(count);
1123
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1124
        }
1125
        return false;
1126
    }
1127

    
1128
    /*
1129
     * A method to put key and value in Vector
1130
     */
1131
    private void putInArray(Vector parentidList, String key,
1132
            ReturnFieldValue value)
1133
    {
1134

    
1135
        Vector tempVector = null;
1136

    
1137
        for (int count = 0; count < parentidList.size(); count++) {
1138
            tempVector = (Vector) parentidList.get(count);
1139

    
1140
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1141
                tempVector.remove(1);
1142
                tempVector.add(1, value);
1143
                return;
1144
            }
1145
        }
1146

    
1147
        tempVector = new Vector();
1148
        tempVector.add(0, key);
1149
        tempVector.add(1, value);
1150
        parentidList.add(tempVector);
1151
        return;
1152
    }
1153

    
1154
    /*
1155
     * A method to get value in Vector given a key
1156
     */
1157
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1158
    {
1159

    
1160
        Vector tempVector = null;
1161

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

    
1165
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1166
                    .get(1); }
1167
        }
1168
        return null;
1169
    }
1170

    
1171
    /*
1172
     * A method to get enumeration of all values in Vector
1173
     */
1174
    private Vector getElements(Vector parentidList)
1175
    {
1176
        Vector enum = new Vector();
1177
        Vector tempVector = null;
1178

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

    
1182
            enum.add(tempVector.get(1));
1183
        }
1184
        return enum;
1185
    }
1186

    
1187
    /*
1188
     * A method to return search result after running a query which return
1189
     * field have attribue
1190
     */
1191
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
1192
            Hashtable docInformationList, String docList, boolean useXMLIndex)
1193
    {
1194
        StringBuffer XML = null;
1195
        String sql = null;
1196
        DBConnection dbconn = null;
1197
        PreparedStatement pstmt = null;
1198
        ResultSet rs = null;
1199
        int serialNumber = -1;
1200
        boolean tableHasRows = false;
1201

    
1202
        //check the parameter
1203
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1204

    
1205
        // if has attribute as return field
1206
        if (squery.containAttributeReturnField()) {
1207
            sql = squery.printAttributeQuery(docList, useXMLIndex);
1208
            try {
1209
                dbconn = DBConnectionPool
1210
                        .getDBConnection("DBQuery.getAttributeValue");
1211
                serialNumber = dbconn.getCheckOutSerialNumber();
1212
                pstmt = dbconn.prepareStatement(sql);
1213
                pstmt.execute();
1214
                rs = pstmt.getResultSet();
1215
                tableHasRows = rs.next();
1216
                while (tableHasRows) {
1217
                    String docid = rs.getString(1).trim();
1218
                    String fieldname = rs.getString(2);
1219
                    String fielddata = rs.getString(3);
1220
                    String attirbuteName = rs.getString(4);
1221
                    XML = new StringBuffer();
1222

    
1223
                    XML.append("<param name=\"");
1224
                    XML.append(fieldname);
1225
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1226
                    XML.append(attirbuteName);
1227
                    XML.append("\">");
1228
                    XML.append(fielddata);
1229
                    XML.append("</param>");
1230
                    tableHasRows = rs.next();
1231

    
1232
                    if (docInformationList.containsKey(docid)) {
1233
                        String removedelement = (String) docInformationList
1234
                                .remove(docid);
1235
                        docInformationList.put(docid, removedelement
1236
                                + XML.toString());
1237
                    } else {
1238
                        docInformationList.put(docid, XML.toString());
1239
                    }
1240
                }//while
1241
                rs.close();
1242
                pstmt.close();
1243
            } catch (Exception se) {
1244
                MetaCatUtil.debugMessage(
1245
                        "Error in DBQuery.getAttributeValue1: "
1246
                                + se.getMessage(), 30);
1247
            } finally {
1248
                try {
1249
                    pstmt.close();
1250
                }//try
1251
                catch (SQLException sqlE) {
1252
                    MetaCatUtil.debugMessage(
1253
                            "Error in DBQuery.getAttributeValue2: "
1254
                                    + sqlE.getMessage(), 30);
1255
                }//catch
1256
                finally {
1257
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
1258
                }//finally
1259
            }//finally
1260
        }//if
1261
        return docInformationList;
1262

    
1263
    }
1264

    
1265
    /*
1266
     * A method to create a query to get owner's docid list
1267
     */
1268
    private String getOwnerQuery(String owner)
1269
    {
1270
        if (owner != null) {
1271
            owner = owner.toLowerCase();
1272
        }
1273
        StringBuffer self = new StringBuffer();
1274

    
1275
        self.append("SELECT docid,docname,doctype,");
1276
        self.append("date_created, date_updated, rev ");
1277
        self.append("FROM xml_documents WHERE docid IN (");
1278
        self.append("(");
1279
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1280
        self.append("nodedata LIKE '%%%' ");
1281
        self.append(") \n");
1282
        self.append(") ");
1283
        self.append(" AND (");
1284
        self.append(" lower(user_owner) = '" + owner + "'");
1285
        self.append(") ");
1286
        return self.toString();
1287
    }
1288

    
1289
    /**
1290
     * format a structured query as an XML document that conforms to the
1291
     * pathquery.dtd and is appropriate for submission to the DBQuery
1292
     * structured query engine
1293
     *
1294
     * @param params The list of parameters that should be included in the
1295
     *            query
1296
     */
1297
    public static String createSQuery(Hashtable params)
1298
    {
1299
        StringBuffer query = new StringBuffer();
1300
        Enumeration elements;
1301
        Enumeration keys;
1302
        String filterDoctype = null;
1303
        String casesensitive = null;
1304
        String searchmode = null;
1305
        Object nextkey;
1306
        Object nextelement;
1307
        //add the xml headers
1308
        query.append("<?xml version=\"1.0\"?>\n");
1309
        query.append("<pathquery version=\"1.2\">\n");
1310

    
1311

    
1312

    
1313
        if (params.containsKey("meta_file_id")) {
1314
            query.append("<meta_file_id>");
1315
            query.append(((String[]) params.get("meta_file_id"))[0]);
1316
            query.append("</meta_file_id>");
1317
        }
1318

    
1319
        if (params.containsKey("returndoctype")) {
1320
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1321
            for (int i = 0; i < returnDoctypes.length; i++) {
1322
                String doctype = (String) returnDoctypes[i];
1323

    
1324
                if (!doctype.equals("any") && !doctype.equals("ANY")
1325
                        && !doctype.equals("")) {
1326
                    query.append("<returndoctype>").append(doctype);
1327
                    query.append("</returndoctype>");
1328
                }
1329
            }
1330
        }
1331

    
1332
        if (params.containsKey("filterdoctype")) {
1333
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1334
            for (int i = 0; i < filterDoctypes.length; i++) {
1335
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1336
                query.append("</filterdoctype>");
1337
            }
1338
        }
1339

    
1340
        if (params.containsKey("returnfield")) {
1341
            String[] returnfield = ((String[]) params.get("returnfield"));
1342
            for (int i = 0; i < returnfield.length; i++) {
1343
                query.append("<returnfield>").append(returnfield[i]);
1344
                query.append("</returnfield>");
1345
            }
1346
        }
1347

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

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

    
1364
        //allows the dynamic switching of boolean operators
1365
        if (params.containsKey("operator")) {
1366
            query.append("<querygroup operator=\""
1367
                    + ((String[]) params.get("operator"))[0] + "\">");
1368
        } else { //the default operator is UNION
1369
            query.append("<querygroup operator=\"UNION\">");
1370
        }
1371

    
1372
        if (params.containsKey("casesensitive")) {
1373
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1374
        } else {
1375
            casesensitive = "false";
1376
        }
1377

    
1378
        if (params.containsKey("searchmode")) {
1379
            searchmode = ((String[]) params.get("searchmode"))[0];
1380
        } else {
1381
            searchmode = "contains";
1382
        }
1383

    
1384
        //anyfield is a special case because it does a
1385
        //free text search. It does not have a <pathexpr>
1386
        //tag. This allows for a free text search within the structured
1387
        //query. This is useful if the INTERSECT operator is used.
1388
        if (params.containsKey("anyfield")) {
1389
            String[] anyfield = ((String[]) params.get("anyfield"));
1390
            //allow for more than one value for anyfield
1391
            for (int i = 0; i < anyfield.length; i++) {
1392
                if (!anyfield[i].equals("")) {
1393
                    query.append("<queryterm casesensitive=\"" + casesensitive
1394
                            + "\" " + "searchmode=\"" + searchmode
1395
                            + "\"><value>" + anyfield[i]
1396
                            + "</value></queryterm>");
1397
                }
1398
            }
1399
        }
1400

    
1401
        //this while loop finds the rest of the parameters
1402
        //and attempts to query for the field specified
1403
        //by the parameter.
1404
        elements = params.elements();
1405
        keys = params.keys();
1406
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1407
            nextkey = keys.nextElement();
1408
            nextelement = elements.nextElement();
1409

    
1410
            //make sure we aren't querying for any of these
1411
            //parameters since the are already in the query
1412
            //in one form or another.
1413
            Vector ignoredParams = new Vector();
1414
            ignoredParams.add("returndoctype");
1415
            ignoredParams.add("filterdoctype");
1416
            ignoredParams.add("action");
1417
            ignoredParams.add("qformat");
1418
            ignoredParams.add("anyfield");
1419
            ignoredParams.add("returnfield");
1420
            ignoredParams.add("owner");
1421
            ignoredParams.add("site");
1422
            ignoredParams.add("operator");
1423
            ignoredParams.add("sessionid");
1424

    
1425
            // Also ignore parameters listed in the properties file
1426
            // so that they can be passed through to stylesheets
1427
            String paramsToIgnore = MetaCatUtil
1428
                    .getOption("query.ignored.params");
1429
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1430
            while (st.hasMoreTokens()) {
1431
                ignoredParams.add(st.nextToken());
1432
            }
1433
            if (!ignoredParams.contains(nextkey.toString())) {
1434
                //allow for more than value per field name
1435
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1436
                    if (!((String[]) nextelement)[i].equals("")) {
1437
                        query.append("<queryterm casesensitive=\""
1438
                                + casesensitive + "\" " + "searchmode=\""
1439
                                + searchmode + "\">" + "<value>" +
1440
                                //add the query value
1441
                                ((String[]) nextelement)[i]
1442
                                + "</value><pathexpr>" +
1443
                                //add the path to query by
1444
                                nextkey.toString() + "</pathexpr></queryterm>");
1445
                    }
1446
                }
1447
            }
1448
        }
1449
        query.append("</querygroup></pathquery>");
1450
        //append on the end of the xml and return the result as a string
1451
        return query.toString();
1452
    }
1453

    
1454
    /**
1455
     * format a simple free-text value query as an XML document that conforms
1456
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1457
     * structured query engine
1458
     *
1459
     * @param value the text string to search for in the xml catalog
1460
     * @param doctype the type of documents to include in the result set -- use
1461
     *            "any" or "ANY" for unfiltered result sets
1462
     */
1463
    public static String createQuery(String value, String doctype)
1464
    {
1465
        StringBuffer xmlquery = new StringBuffer();
1466
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1467
        xmlquery.append("<pathquery version=\"1.0\">");
1468

    
1469
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1470
            xmlquery.append("<returndoctype>");
1471
            xmlquery.append(doctype).append("</returndoctype>");
1472
        }
1473

    
1474
        xmlquery.append("<querygroup operator=\"UNION\">");
1475
        //chad added - 8/14
1476
        //the if statement allows a query to gracefully handle a null
1477
        //query. Without this if a nullpointerException is thrown.
1478
        if (!value.equals("")) {
1479
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1480
            xmlquery.append("searchmode=\"contains\">");
1481
            xmlquery.append("<value>").append(value).append("</value>");
1482
            xmlquery.append("</queryterm>");
1483
        }
1484
        xmlquery.append("</querygroup>");
1485
        xmlquery.append("</pathquery>");
1486

    
1487
        return (xmlquery.toString());
1488
    }
1489

    
1490
    /**
1491
     * format a simple free-text value query as an XML document that conforms
1492
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1493
     * structured query engine
1494
     *
1495
     * @param value the text string to search for in the xml catalog
1496
     */
1497
    public static String createQuery(String value)
1498
    {
1499
        return createQuery(value, "any");
1500
    }
1501

    
1502
    /**
1503
     * Check for "READ" permission on @docid for @user and/or @group from DB
1504
     * connection
1505
     */
1506
    private boolean hasPermission(String user, String[] groups, String docid)
1507
            throws SQLException, Exception
1508
    {
1509
        // Check for READ permission on @docid for @user and/or @groups
1510
        PermissionController controller = new PermissionController(docid);
1511
        return controller.hasPermission(user, groups,
1512
                AccessControlInterface.READSTRING);
1513
    }
1514

    
1515
    /**
1516
     * Get all docIds list for a data packadge
1517
     *
1518
     * @param dataPackageDocid, the string in docId field of xml_relation table
1519
     */
1520
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1521
    {
1522
        DBConnection dbConn = null;
1523
        int serialNumber = -1;
1524
        Vector docIdList = new Vector();//return value
1525
        PreparedStatement pStmt = null;
1526
        ResultSet rs = null;
1527
        String docIdInSubjectField = null;
1528
        String docIdInObjectField = null;
1529

    
1530
        // Check the parameter
1531
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1532

    
1533
        //the query stirng
1534
        String query = "SELECT subject, object from xml_relation where docId = ?";
1535
        try {
1536
            dbConn = DBConnectionPool
1537
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1538
            serialNumber = dbConn.getCheckOutSerialNumber();
1539
            pStmt = dbConn.prepareStatement(query);
1540
            //bind the value to query
1541
            pStmt.setString(1, dataPackageDocid);
1542

    
1543
            //excute the query
1544
            pStmt.execute();
1545
            //get the result set
1546
            rs = pStmt.getResultSet();
1547
            //process the result
1548
            while (rs.next()) {
1549
                //In order to get the whole docIds in a data packadge,
1550
                //we need to put the docIds of subject and object field in
1551
                // xml_relation
1552
                //into the return vector
1553
                docIdInSubjectField = rs.getString(1);//the result docId in
1554
                                                      // subject field
1555
                docIdInObjectField = rs.getString(2);//the result docId in
1556
                                                     // object field
1557

    
1558
                //don't put the duplicate docId into the vector
1559
                if (!docIdList.contains(docIdInSubjectField)) {
1560
                    docIdList.add(docIdInSubjectField);
1561
                }
1562

    
1563
                //don't put the duplicate docId into the vector
1564
                if (!docIdList.contains(docIdInObjectField)) {
1565
                    docIdList.add(docIdInObjectField);
1566
                }
1567
            }//while
1568
            //close the pStmt
1569
            pStmt.close();
1570
        }//try
1571
        catch (SQLException e) {
1572
            MetaCatUtil.debugMessage("Error in getDocidListForDataPackage: "
1573
                    + e.getMessage(), 30);
1574
        }//catch
1575
        finally {
1576
            try {
1577
                pStmt.close();
1578
            }//try
1579
            catch (SQLException ee) {
1580
                MetaCatUtil.debugMessage(
1581
                        "Error in getDocidListForDataPackage: "
1582
                                + ee.getMessage(), 30);
1583
            }//catch
1584
            finally {
1585
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1586
            }//fianlly
1587
        }//finally
1588
        return docIdList;
1589
    }//getCurrentDocidListForDataPackadge()
1590

    
1591
    /**
1592
     * Get all docIds list for a data packadge
1593
     *
1594
     * @param dataPackageDocid, the string in docId field of xml_relation table
1595
     */
1596
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
1597
    {
1598

    
1599
        Vector docIdList = new Vector();//return value
1600
        Vector tripleList = null;
1601
        String xml = null;
1602

    
1603
        // Check the parameter
1604
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1605

    
1606
        try {
1607
            //initial a documentImpl object
1608
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocid);
1609
            //transfer to documentImpl object to string
1610
            xml = packageDocument.toString();
1611

    
1612
            //create a tripcollection object
1613
            TripleCollection tripleForPackage = new TripleCollection(
1614
                    new StringReader(xml));
1615
            //get the vetor of triples
1616
            tripleList = tripleForPackage.getCollection();
1617

    
1618
            for (int i = 0; i < tripleList.size(); i++) {
1619
                //put subject docid into docIdlist without duplicate
1620
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1621
                        .getSubject())) {
1622
                    //put subject docid into docIdlist
1623
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1624
                }
1625
                //put object docid into docIdlist without duplicate
1626
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1627
                        .getObject())) {
1628
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1629
                }
1630
            }//for
1631
        }//try
1632
        catch (Exception e) {
1633
            MetaCatUtil.debugMessage("Error in getOldVersionAllDocumentImpl: "
1634
                    + e.getMessage(), 30);
1635
        }//catch
1636

    
1637
        // return result
1638
        return docIdList;
1639
    }//getDocidListForPackageInXMLRevisions()
1640

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

    
1693
    /**
1694
     * Check if the user has the permission to export data package
1695
     *
1696
     * @param conn, the connection
1697
     * @param docId, the id need to be checked
1698
     * @param user, the name of user
1699
     * @param groups, the user's group
1700
     */
1701
    private boolean hasPermissionToExportPackage(String docId, String user,
1702
            String[] groups) throws Exception
1703
    {
1704
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1705
        return DocumentImpl.hasReadPermission(user, groups, docId);
1706
    }
1707

    
1708
    /**
1709
     * Get the current Rev for a docid in xml_documents table
1710
     *
1711
     * @param docId, the id need to get version numb If the return value is -5,
1712
     *            means no value in rev field for this docid
1713
     */
1714
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1715
            throws SQLException
1716
    {
1717
        int rev = -5;
1718
        PreparedStatement pStmt = null;
1719
        ResultSet rs = null;
1720
        String query = "SELECT rev from xml_documents where docId = ?";
1721
        DBConnection dbConn = null;
1722
        int serialNumber = -1;
1723
        try {
1724
            dbConn = DBConnectionPool
1725
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1726
            serialNumber = dbConn.getCheckOutSerialNumber();
1727
            pStmt = dbConn.prepareStatement(query);
1728
            //bind the value to query
1729
            pStmt.setString(1, docId);
1730
            //execute the query
1731
            pStmt.execute();
1732
            rs = pStmt.getResultSet();
1733
            //process the result
1734
            if (rs.next()) //There are some records for rev
1735
            {
1736
                rev = rs.getInt(1);
1737
                ;//It is the version for given docid
1738
            } else {
1739
                rev = -5;
1740
            }
1741

    
1742
        }//try
1743
        catch (SQLException e) {
1744
            MetaCatUtil.debugMessage(
1745
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1746
                            + e.getMessage(), 30);
1747
            throw e;
1748
        }//catch
1749
        finally {
1750
            try {
1751
                pStmt.close();
1752
            }//try
1753
            catch (SQLException ee) {
1754
                MetaCatUtil.debugMessage(
1755
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1756
                                + ee.getMessage(), 30);
1757
            }//catch
1758
            finally {
1759
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1760
            }//finally
1761
        }//finally
1762
        return rev;
1763
    }//getCurrentRevFromXMLDoumentsTable
1764

    
1765
    /**
1766
     * put a doc into a zip output stream
1767
     *
1768
     * @param docImpl, docmentImpl object which will be sent to zip output
1769
     *            stream
1770
     * @param zipOut, zip output stream which the docImpl will be put
1771
     * @param packageZipEntry, the zip entry name for whole package
1772
     */
1773
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1774
            ZipOutputStream zipOut, String packageZipEntry)
1775
            throws ClassNotFoundException, IOException, SQLException,
1776
            McdbException, Exception
1777
    {
1778
        byte[] byteString = null;
1779
        ZipEntry zEntry = null;
1780

    
1781
        byteString = docImpl.toString().getBytes();
1782
        //use docId as the zip entry's name
1783
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1784
                + docImpl.getDocID());
1785
        zEntry.setSize(byteString.length);
1786
        zipOut.putNextEntry(zEntry);
1787
        zipOut.write(byteString, 0, byteString.length);
1788
        zipOut.closeEntry();
1789

    
1790
    }//addDocToZipOutputStream()
1791

    
1792
    /**
1793
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1794
     * only inlcudes current version. If a DocumentImple object couldn't find
1795
     * for a docid, then the String of this docid was added to vetor rather
1796
     * than DocumentImple object.
1797
     *
1798
     * @param docIdList, a vetor hold a docid list for a data package. In
1799
     *            docid, there is not version number in it.
1800
     */
1801

    
1802
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1803
            throws McdbException, Exception
1804
    {
1805
        //Connection dbConn=null;
1806
        Vector documentImplList = new Vector();
1807
        int rev = 0;
1808

    
1809
        // Check the parameter
1810
        if (docIdList.isEmpty()) { return documentImplList; }//if
1811

    
1812
        //for every docid in vector
1813
        for (int i = 0; i < docIdList.size(); i++) {
1814
            try {
1815
                //get newest version for this docId
1816
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1817
                        .elementAt(i));
1818

    
1819
                // There is no record for this docId in xml_documents table
1820
                if (rev == -5) {
1821
                    // Rather than put DocumentImple object, put a String
1822
                    // Object(docid)
1823
                    // into the documentImplList
1824
                    documentImplList.add((String) docIdList.elementAt(i));
1825
                    // Skip other code
1826
                    continue;
1827
                }
1828

    
1829
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1830
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1831

    
1832
                //create new documentImpl object
1833
                DocumentImpl documentImplObject = new DocumentImpl(
1834
                        docidPlusVersion);
1835
                //add them to vector
1836
                documentImplList.add(documentImplObject);
1837
            }//try
1838
            catch (Exception e) {
1839
                MetaCatUtil.debugMessage("Error in getCurrentAllDocumentImpl: "
1840
                        + e.getMessage(), 30);
1841
                // continue the for loop
1842
                continue;
1843
            }
1844
        }//for
1845
        return documentImplList;
1846
    }
1847

    
1848
    /**
1849
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
1850
     * object couldn't find for a docid, then the String of this docid was
1851
     * added to vetor rather than DocumentImple object.
1852
     *
1853
     * @param docIdList, a vetor hold a docid list for a data package. In
1854
     *            docid, t here is version number in it.
1855
     */
1856
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
1857
    {
1858
        //Connection dbConn=null;
1859
        Vector documentImplList = new Vector();
1860
        String siteCode = null;
1861
        String uniqueId = null;
1862
        int rev = 0;
1863

    
1864
        // Check the parameter
1865
        if (docIdList.isEmpty()) { return documentImplList; }//if
1866

    
1867
        //for every docid in vector
1868
        for (int i = 0; i < docIdList.size(); i++) {
1869

    
1870
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1871

    
1872
            try {
1873
                //create new documentImpl object
1874
                DocumentImpl documentImplObject = new DocumentImpl(
1875
                        docidPlusVersion);
1876
                //add them to vector
1877
                documentImplList.add(documentImplObject);
1878
            }//try
1879
            catch (McdbDocNotFoundException notFoundE) {
1880
                MetaCatUtil.debugMessage(
1881
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1882
                                + notFoundE.getMessage(), 30);
1883
                // Rather than add a DocumentImple object into vetor, a String
1884
                // object
1885
                // - the doicd was added to the vector
1886
                documentImplList.add(docidPlusVersion);
1887
                // Continue the for loop
1888
                continue;
1889
            }//catch
1890
            catch (Exception e) {
1891
                MetaCatUtil.debugMessage(
1892
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1893
                                + e.getMessage(), 30);
1894
                // Continue the for loop
1895
                continue;
1896
            }//catch
1897

    
1898
        }//for
1899
        return documentImplList;
1900
    }//getOldVersionAllDocumentImple
1901

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

    
1942
    /**
1943
     * create a html summary for data package and put it into zip output stream
1944
     *
1945
     * @param docImplList, the documentImpl ojbects in data package
1946
     * @param zipOut, the zip output stream which the html should be put
1947
     * @param packageZipEntry, the zip entry name for whole package
1948
     */
1949
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
1950
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
1951
    {
1952
        StringBuffer htmlDoc = new StringBuffer();
1953
        ZipEntry zEntry = null;
1954
        byte[] byteString = null;
1955
        InputStream source;
1956
        DBTransform xmlToHtml;
1957

    
1958
        //create a DBTransform ojbect
1959
        xmlToHtml = new DBTransform();
1960
        //head of html
1961
        htmlDoc.append("<html><head></head><body>");
1962
        for (int i = 0; i < docImplList.size(); i++) {
1963
            // If this String object, this means it is missed data file
1964
            if ((((docImplList.elementAt(i)).getClass()).toString())
1965
                    .equals("class java.lang.String")) {
1966

    
1967
                htmlDoc.append("<a href=\"");
1968
                String dataFileid = (String) docImplList.elementAt(i);
1969
                htmlDoc.append("./data/").append(dataFileid).append("\">");
1970
                htmlDoc.append("Data File: ");
1971
                htmlDoc.append(dataFileid).append("</a><br>");
1972
                htmlDoc.append("<br><hr><br>");
1973

    
1974
            }//if
1975
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
1976
                    .compareTo("BIN") != 0) { //this is an xml file so we can
1977
                                              // transform it.
1978
                //transform each file individually then concatenate all of the
1979
                //transformations together.
1980

    
1981
                //for metadata xml title
1982
                htmlDoc.append("<h2>");
1983
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
1984
                        .getDocID());
1985
                //htmlDoc.append(".");
1986
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
1987
                htmlDoc.append("</h2>");
1988
                //do the actual transform
1989
                StringWriter docString = new StringWriter();
1990
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
1991
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
1992
                        "-//W3C//HTML//EN", "html", docString);
1993
                htmlDoc.append(docString.toString());
1994
                htmlDoc.append("<br><br><hr><br><br>");
1995
            }//if
1996
            else { //this is a data file so we should link to it in the html
1997
                htmlDoc.append("<a href=\"");
1998
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
1999
                        .getDocID();
2000
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2001
                htmlDoc.append("Data File: ");
2002
                htmlDoc.append(dataFileid).append("</a><br>");
2003
                htmlDoc.append("<br><hr><br>");
2004
            }//else
2005
        }//for
2006
        htmlDoc.append("</body></html>");
2007
        byteString = htmlDoc.toString().getBytes();
2008
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2009
        zEntry.setSize(byteString.length);
2010
        zipOut.putNextEntry(zEntry);
2011
        zipOut.write(byteString, 0, byteString.length);
2012
        zipOut.closeEntry();
2013
        //dbConn.close();
2014

    
2015
    }//addHtmlSummaryToZipOutputStream
2016

    
2017
    /**
2018
     * put a data packadge into a zip output stream
2019
     *
2020
     * @param docId, which the user want to put into zip output stream
2021
     * @param out, a servletoutput stream which the zip output stream will be
2022
     *            put
2023
     * @param user, the username of the user
2024
     * @param groups, the group of the user
2025
     */
2026
    public ZipOutputStream getZippedPackage(String docIdString,
2027
            ServletOutputStream out, String user, String[] groups,
2028
            String passWord) throws ClassNotFoundException, IOException,
2029
            SQLException, McdbException, NumberFormatException, Exception
2030
    {
2031
        ZipOutputStream zOut = null;
2032
        String elementDocid = null;
2033
        DocumentImpl docImpls = null;
2034
        //Connection dbConn = null;
2035
        Vector docIdList = new Vector();
2036
        Vector documentImplList = new Vector();
2037
        Vector htmlDocumentImplList = new Vector();
2038
        String packageId = null;
2039
        String rootName = "package";//the package zip entry name
2040

    
2041
        String docId = null;
2042
        int version = -5;
2043
        // Docid without revision
2044
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2045
        // revision number
2046
        version = MetaCatUtil.getVersionFromString(docIdString);
2047

    
2048
        //check if the reqused docId is a data package id
2049
        if (!isDataPackageId(docId)) {
2050

    
2051
            /*
2052
             * Exception e = new Exception("The request the doc id "
2053
             * +docIdString+ " is not a data package id");
2054
             */
2055

    
2056
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2057
            // zip
2058
            //up the single document and return the zip file.
2059
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2060

    
2061
                Exception e = new Exception("User " + user
2062
                        + " does not have permission"
2063
                        + " to export the data package " + docIdString);
2064
                throw e;
2065
            }
2066

    
2067
            docImpls = new DocumentImpl(docId);
2068
            //checking if the user has the permission to read the documents
2069
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2070
                    .getDocID())) {
2071
                zOut = new ZipOutputStream(out);
2072
                //if the docImpls is metadata
2073
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2074
                    //add metadata into zip output stream
2075
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2076
                }//if
2077
                else {
2078
                    //it is data file
2079
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2080
                    htmlDocumentImplList.add(docImpls);
2081
                }//else
2082
            }//if
2083

    
2084
            zOut.finish(); //terminate the zip file
2085
            return zOut;
2086
        }
2087
        // Check the permission of user
2088
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2089

    
2090
            Exception e = new Exception("User " + user
2091
                    + " does not have permission"
2092
                    + " to export the data package " + docIdString);
2093
            throw e;
2094
        } else //it is a packadge id
2095
        {
2096
            //store the package id
2097
            packageId = docId;
2098
            //get current version in database
2099
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2100
            //If it is for current version (-1 means user didn't specify
2101
            // revision)
2102
            if ((version == -1) || version == currentVersion) {
2103
                //get current version number
2104
                version = currentVersion;
2105
                //get package zip entry name
2106
                //it should be docId.revsion.package
2107
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2108
                        + version + MetaCatUtil.getOption("accNumSeparator")
2109
                        + "package";
2110
                //get the whole id list for data packadge
2111
                docIdList = getCurrentDocidListForDataPackage(packageId);
2112
                //get the whole documentImple object
2113
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2114

    
2115
            }//if
2116
            else if (version > currentVersion || version < -1) {
2117
                throw new Exception("The user specified docid: " + docId + "."
2118
                        + version + " doesn't exist");
2119
            }//else if
2120
            else //for an old version
2121
            {
2122

    
2123
                rootName = docIdString
2124
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2125
                //get the whole id list for data packadge
2126
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2127

    
2128
                //get the whole documentImple object
2129
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2130
            }//else
2131

    
2132
            // Make sure documentImplist is not empty
2133
            if (documentImplList.isEmpty()) { throw new Exception(
2134
                    "Couldn't find component for data package: " + packageId); }//if
2135

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

    
2178
                }//if
2179
                else {
2180
                    //create a docmentImpls object (represent xml doc) base on
2181
                    // the docId
2182
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2183
                    //checking if the user has the permission to read the
2184
                    // documents
2185
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2186
                            .getDocID())) {
2187
                        //if the docImpls is metadata
2188
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2189
                            //add metadata into zip output stream
2190
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2191
                            //add the documentImpl into the vetor which will
2192
                            // be used in html
2193
                            htmlDocumentImplList.add(docImpls);
2194

    
2195
                        }//if
2196
                        else {
2197
                            //it is data file
2198
                            addDataFileToZipOutputStream(docImpls, zOut,
2199
                                    rootName);
2200
                            htmlDocumentImplList.add(docImpls);
2201
                        }//else
2202
                    }//if
2203
                }//else
2204
            }//for
2205

    
2206
            //add html summary file
2207
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2208
                    rootName);
2209
            zOut.finish(); //terminate the zip file
2210
            //dbConn.close();
2211
            return zOut;
2212
        }//else
2213
    }//getZippedPackage()
2214

    
2215
    private class ReturnFieldValue
2216
    {
2217

    
2218
        private String docid = null; //return field value for this docid
2219

    
2220
        private String fieldValue = null;
2221

    
2222
        private String xmlFieldValue = null; //return field value in xml
2223
                                             // format
2224

    
2225
        public void setDocid(String myDocid)
2226
        {
2227
            docid = myDocid;
2228
        }
2229

    
2230
        public String getDocid()
2231
        {
2232
            return docid;
2233
        }
2234

    
2235
        public void setFieldValue(String myValue)
2236
        {
2237
            fieldValue = myValue;
2238
        }
2239

    
2240
        public String getFieldValue()
2241
        {
2242
            return fieldValue;
2243
        }
2244

    
2245
        public void setXMLFieldValue(String xml)
2246
        {
2247
            xmlFieldValue = xml;
2248
        }
2249

    
2250
        public String getXMLFieldValue()
2251
        {
2252
            return xmlFieldValue;
2253
        }
2254

    
2255
    }
2256
}
(22-22/63)