Project

General

Profile

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

    
32
package edu.ucsb.nceas.metacat;
33

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

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

    
57
import org.apache.log4j.Logger;
58

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

    
62

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

    
72
    static final int ALL = 1;
73

    
74
    static final int WRITE = 2;
75

    
76
    static final int READ = 4;
77

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

    
81
    private MetaCatUtil util = new MetaCatUtil();
82

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

    
85
    /** true if the metacat spatial option is installed **/
86
    private final boolean METACAT_SPATIAL = true;
87

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

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

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

    
118
                // Time the request if asked for
119
                double startTime = System.currentTimeMillis();
120

    
121
                // Open a connection to the database
122
                MetaCatUtil util = new MetaCatUtil();
123
                //Connection dbconn = util.openDBConnection();
124

    
125
                double connTime = System.currentTimeMillis();
126

    
127
                // Execute the query
128
                DBQuery queryobj = new DBQuery();
129
                FileReader xml = new FileReader(new File(xmlfile));
130
                Hashtable nodelist = null;
131
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
132

    
133
                // Print the reulting document listing
134
                StringBuffer result = new StringBuffer();
135
                String document = null;
136
                String docid = null;
137
                result.append("<?xml version=\"1.0\"?>\n");
138
                result.append("<resultset>\n");
139

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

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

    
175
            } catch (Exception e) {
176
                System.err.println("Error in DBQuery.main");
177
                System.err.println(e.getMessage());
178
                e.printStackTrace(System.err);
179
            }
180
        }
181
    }
182

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

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

    
201

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

    
220
  }
221

    
222

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

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

    
262

    
263

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

    
282
         DBTransform trans = new DBTransform();
283
         response.setContentType("text/html");
284

    
285
	 // if the user is a moderator, then pass a param to the 
286
         // xsl specifying the fact
287
         if(MetaCatUtil.isModerator(user, groups)){
288
        	 params.put("isModerator", new String[] {"true"});
289
         }
290

    
291
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
292
                                 "-//W3C//HTML//EN", qformat, out, params,
293
                                 sessionid);
294

    
295
        }
296
        catch(Exception e)
297
        {
298
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
299
                                +e.getMessage());
300
         }
301

    
302
      }//else
303

    
304
    }
305

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

    
334
        //checkout the dbconnection
335
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
336
        serialNumber = dbconn.getCheckOutSerialNumber();
337

    
338
        //print out the search result
339
        // search the doc list
340
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
341
                                      dbconn, useXMLIndex);
342

    
343
        
344

    
345
      } //try
346
      catch (IOException ioe)
347
      {
348
        logMetacat.error("IO error in DBQuery.findDocuments:");
349
        logMetacat.error(ioe.getMessage());
350

    
351
      }
352
      catch (SQLException e)
353
      {
354
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
355
                                 + e.getMessage());
356
      }
357
      catch (Exception ee)
358
      {
359
        logMetacat.error("Exception in DBQuery.findDocuments: "
360
                                 + ee.getMessage());
361
      }
362
      finally
363
      {
364
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
365
      } //finally
366
    }//if
367
    String closeRestultset = "</resultset>";
368
    resultset.append(closeRestultset);
369
    if (out != null)
370
    {
371
      out.println(closeRestultset);
372
    }
373

    
374
    return resultset;
375
  }//createResultDocuments
376

    
377

    
378

    
379
    /*
380
     * Find the doc list which match the query
381
     */
382
    private StringBuffer findResultDoclist(QuerySpecification qspec,
383
                                      StringBuffer resultsetBuffer,
384
                                      PrintWriter out,
385
                                      String user, String[]groups,
386
                                      DBConnection dbconn, boolean useXMLIndex )
387
                                      throws Exception
388
    {
389
      
390
      int offset = 1;
391
      // this is a hack for offset
392
      if (out == null)
393
      {
394
        // for html page, we put everything into one page
395
        offset =
396
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
397
      }
398
      else
399
      {
400
          offset =
401
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
402
      }
403

    
404
      int count = 0;
405
      int index = 0;
406
      Hashtable docListResult = new Hashtable();
407
      PreparedStatement pstmt = null;
408
      String docid = null;
409
      String docname = null;
410
      String doctype = null;
411
      String createDate = null;
412
      String updateDate = null;
413
      StringBuffer document = null;
414
      int rev = 0;
415
      String query = qspec.printSQL(useXMLIndex);
416
      String ownerQuery = getOwnerQuery(user);
417
      logMetacat.info("query: " + query);
418
      //logMetacat.info("query: "+ownerQuery);
419
      // if query is not the owner query, we need to check the permission
420
      // otherwise we don't need (owner has all permission by default)
421
      if (!query.equals(ownerQuery))
422
      {
423
        // set user name and group
424
        qspec.setUserName(user);
425
        qspec.setGroup(groups);
426
        // Get access query
427
        String accessQuery = qspec.getAccessQuery();
428
        if(!query.endsWith("WHERE")){
429
            query = query + accessQuery;
430
        } else {
431
            query = query + accessQuery.substring(4, accessQuery.length());
432
        }
433
        logMetacat.warn(" final query: " + query);
434
      }
435

    
436
      double startTime = System.currentTimeMillis() / 1000;
437
      pstmt = dbconn.prepareStatement(query);
438

    
439
      // Execute the SQL query using the JDBC connection
440
      pstmt.execute();
441
      ResultSet rs = pstmt.getResultSet();
442
      double queryExecuteTime = System.currentTimeMillis() / 1000;
443
      logMetacat.warn("Time for execute query: "
444
                    + (queryExecuteTime - startTime));
445
      boolean tableHasRows = rs.next();
446
      while (tableHasRows)
447
      {
448
        docid = rs.getString(1).trim();
449
        docname = rs.getString(2);
450
        doctype = rs.getString(3);
451
        createDate = rs.getString(4);
452
        updateDate = rs.getString(5);
453
        rev = rs.getInt(6);
454

    
455
        // if there are returndocs to match, backtracking can be performed
456
        // otherwise, just return the document that was hit
457
        Vector returndocVec = qspec.getReturnDocList();
458
         if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
459
                        && !qspec.isPercentageSearch())
460
        {
461
           logMetacat.warn("Back tracing now...");
462
           String sep = MetaCatUtil.getOption("accNumSeparator");
463
           StringBuffer btBuf = new StringBuffer();
464
           btBuf.append("select docid from xml_relation where ");
465

    
466
           //build the doctype list for the backtracking sql statement
467
           btBuf.append("packagetype in (");
468
           for (int i = 0; i < returndocVec.size(); i++)
469
           {
470
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
471
             if (i != (returndocVec.size() - 1))
472
             {
473
                btBuf.append(", ");
474
              }
475
            }
476
            btBuf.append(") ");
477
            btBuf.append("and (subject like '");
478
            btBuf.append(docid).append("'");
479
            btBuf.append("or object like '");
480
            btBuf.append(docid).append("')");
481

    
482
            PreparedStatement npstmt = dbconn.prepareStatement(btBuf.toString());
483
            //should incease usage count
484
            dbconn.increaseUsageCount(1);
485
            npstmt.execute();
486
            ResultSet btrs = npstmt.getResultSet();
487
            boolean hasBtRows = btrs.next();
488
            while (hasBtRows)
489
            {
490
               //there was a backtrackable document found
491
               DocumentImpl xmldoc = null;
492
               String packageDocid = btrs.getString(1);
493
               logMetacat.info("Getting document for docid: "
494
                                         + packageDocid);
495
                try
496
                {
497
                    //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not
498
                    // needed here
499
                    // xmldoc = new DocumentImpl(dbconn, packageDocid);
500
                    //  thus use the following to get the doc info only
501
                    //  xmldoc = new DocumentImpl(dbconn);
502
                    String accNumber = packageDocid + MetaCatUtil.getOption("accNumSeparator") +
503
                    DBUtil.getLatestRevisionInDocumentTable(packageDocid);
504
                    xmldoc = new DocumentImpl(accNumber, false);
505
                    if (xmldoc == null)
506
                    {
507
                       logMetacat.info("Document was null for: "
508
                                                + packageDocid);
509
                    }
510
                }
511
                catch (Exception e)
512
                {
513
                    System.out.println("Error getting document in "
514
                                       + "DBQuery.findDocuments: "
515
                                       + e.getMessage());
516
                }
517

    
518
                String docid_org = xmldoc.getDocID();
519
                if (docid_org == null)
520
                {
521
                   logMetacat.info("Docid_org was null.");
522
                   //continue;
523
                }
524
                docid = docid_org.trim();
525
                docname = xmldoc.getDocname();
526
                doctype = xmldoc.getDoctype();
527
                createDate = xmldoc.getCreateDate();
528
                updateDate = xmldoc.getUpdateDate();
529
                rev = xmldoc.getRev();
530
                document = new StringBuffer();
531

    
532
                String completeDocid = docid
533
                                + MetaCatUtil.getOption("accNumSeparator");
534
                completeDocid += rev;
535
                document.append("<docid>").append(completeDocid);
536
                document.append("</docid>");
537
                if (docname != null)
538
                {
539
                  document.append("<docname>" + docname + "</docname>");
540
                }
541
                if (doctype != null)
542
                {
543
                  document.append("<doctype>" + doctype + "</doctype>");
544
                }
545
                if (createDate != null)
546
                {
547
                 document.append("<createdate>" + createDate + "</createdate>");
548
                }
549
                if (updateDate != null)
550
                {
551
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
552
                }
553
                // Store the document id and the root node id
554
                docListResult.put(docid, (String) document.toString());
555
                count++;
556

    
557

    
558
                // Get the next package document linked to our hit
559
                hasBtRows = btrs.next();
560
              }//while
561
              npstmt.close();
562
              btrs.close();
563
        }
564
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
565
        {
566

    
567
           document = new StringBuffer();
568

    
569
           String completeDocid = docid
570
                            + MetaCatUtil.getOption("accNumSeparator");
571
           completeDocid += rev;
572
           document.append("<docid>").append(completeDocid).append("</docid>");
573
           if (docname != null)
574
           {
575
               document.append("<docname>" + docname + "</docname>");
576
            }
577
            if (doctype != null)
578
            {
579
               document.append("<doctype>" + doctype + "</doctype>");
580
            }
581
            if (createDate != null)
582
            {
583
                document.append("<createdate>" + createDate + "</createdate>");
584
             }
585
             if (updateDate != null)
586
             {
587
               document.append("<updatedate>" + updateDate + "</updatedate>");
588
             }
589
              // Store the document id and the root node id
590
              docListResult.put(docid, (String) document.toString());
591
              count++;
592

    
593

    
594
        }//else
595
        // when doclist reached the offset number, send out doc list and empty
596
        // the hash table
597
        if (count == offset)
598
        {
599
          //reset count
600
          count = 0;
601
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
602
                              user, groups,dbconn, useXMLIndex);
603
          // reset docListResult
604
          docListResult = new Hashtable();
605

    
606
        }
607
       // Advance to the next record in the cursor
608
       tableHasRows = rs.next();
609
     }//while
610
     rs.close();
611
     pstmt.close();
612
     //if docListResult is not empty, it need to be sent.
613
     if (!docListResult.isEmpty())
614
     {
615
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
616
                              user, groups,dbconn, useXMLIndex);
617
     }
618
     double docListTime = System.currentTimeMillis() / 1000;
619
     logMetacat.warn("prepare docid list time: "
620
                    + (docListTime - queryExecuteTime));
621

    
622
     
623
     //write the persistent spatial dataset
624
     /*
625
	 if(metacatSpatialData != null){
626
		metacatSpatialData.writeTextQueryData();
627
	 }
628
      */
629

    
630
     return resultsetBuffer;
631
    }//findReturnDoclist
632

    
633

    
634
    /*
635
     * Send completed search hashtable(part of reulst)to output stream
636
     * and buffer into a buffer stream
637
     */
638
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
639
                                           StringBuffer resultset,
640
                                           PrintWriter out, Hashtable partOfDoclist,
641
                                           String user, String[]groups,
642
                                       DBConnection dbconn, boolean useXMLIndex)
643
                                       throws Exception
644
   {
645

    
646
     // check if there is a record in xml_returnfield
647
     // and get the returnfield_id and usage count
648
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
649
     boolean enterRecords = false;
650

    
651
     // get value of xml_returnfield_count
652
     int count = (new Integer(MetaCatUtil
653
                            .getOption("xml_returnfield_count")))
654
                            .intValue();
655

    
656
     // set enterRecords to true if usage_count is more than the offset
657
     // specified in metacat.properties
658
     if(usage_count > count){
659
         enterRecords = true;
660
     }
661

    
662
     if(returnfield_id < 0){
663
         logMetacat.warn("Error in getting returnfield id from"
664
                                  + "xml_returnfield table");
665
	enterRecords = false;
666
     }
667

    
668
     // get the hashtable containing the docids that already in the
669
     // xml_queryresult table
670
     logMetacat.info("size of partOfDoclist before"
671
                             + " docidsInQueryresultTable(): "
672
                             + partOfDoclist.size());
673
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
674
                                                        partOfDoclist, dbconn);
675

    
676
     // remove the keys in queryresultDocList from partOfDoclist
677
     Enumeration _keys = queryresultDocList.keys();
678
     while (_keys.hasMoreElements()){
679
         partOfDoclist.remove(_keys.nextElement());
680
     }
681

    
682
     // backup the keys-elements in partOfDoclist to check later
683
     // if the doc entry is indexed yet
684
     Hashtable partOfDoclistBackup = new Hashtable();
685
     _keys = partOfDoclist.keys();
686
     while (_keys.hasMoreElements()){
687
	 Object key = _keys.nextElement();
688
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
689
     }
690

    
691
     logMetacat.info("size of partOfDoclist after"
692
                             + " docidsInQueryresultTable(): "
693
                             + partOfDoclist.size());
694

    
695
     //add return fields for the documents in partOfDoclist
696
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
697
                                        dbconn, useXMLIndex );
698
     //add relationship part part docid list for the documents in partOfDocList
699
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
700

    
701

    
702
     Enumeration keys = partOfDoclist.keys();
703
     String key = null;
704
     String element = null;
705
     String query = null;
706
     int offset = (new Integer(MetaCatUtil
707
                               .getOption("queryresult_string_length")))
708
                               .intValue();
709
     while (keys.hasMoreElements())
710
     {
711
         key = (String) keys.nextElement();
712
         element = (String)partOfDoclist.get(key);
713

    
714
	 // check if the enterRecords is true, elements is not null, element's
715
         // length is less than the limit of table column and if the document
716
         // has been indexed already
717
         if(enterRecords && element != null
718
		&& element.length() < offset
719
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
720
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
721
                 + "queryresult_string) VALUES (?, ?, ?)";
722

    
723
             PreparedStatement pstmt = null;
724
             pstmt = dbconn.prepareStatement(query);
725
             pstmt.setInt(1, returnfield_id);
726
             pstmt.setString(2, key);
727
             pstmt.setString(3, element);
728

    
729
             dbconn.increaseUsageCount(1);
730
             pstmt.execute();
731
             pstmt.close();
732
         }
733

    
734
         // A string with element
735
         String xmlElement = "  <document>" + element + "</document>";
736

    
737
         //send single element to output
738
         if (out != null)
739
         {
740
             out.println(xmlElement);
741
         }
742
         resultset.append(xmlElement);
743
     }//while
744

    
745

    
746
     keys = queryresultDocList.keys();
747
     while (keys.hasMoreElements())
748
     {
749
         key = (String) keys.nextElement();
750
         element = (String)queryresultDocList.get(key);
751
         // A string with element
752
         String xmlElement = "  <document>" + element + "</document>";
753
         //send single element to output
754
         if (out != null)
755
         {
756
             out.println(xmlElement);
757
         }
758
         resultset.append(xmlElement);
759
     }//while
760

    
761
     return resultset;
762
 }
763

    
764
   /**
765
    * Get the docids already in xml_queryresult table and corresponding
766
    * queryresultstring as a hashtable
767
    */
768
   private Hashtable docidsInQueryresultTable(int returnfield_id,
769
                                              Hashtable partOfDoclist,
770
                                              DBConnection dbconn){
771

    
772
         Hashtable returnValue = new Hashtable();
773
         PreparedStatement pstmt = null;
774
         ResultSet rs = null;
775

    
776
         // get partOfDoclist as string for the query
777
         Enumeration keylist = partOfDoclist.keys();
778
         StringBuffer doclist = new StringBuffer();
779
         while (keylist.hasMoreElements())
780
         {
781
             doclist.append("'");
782
             doclist.append((String) keylist.nextElement());
783
             doclist.append("',");
784
         }//while
785

    
786

    
787
         if (doclist.length() > 0)
788
         {
789
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
790

    
791
             // the query to find out docids from xml_queryresult
792
             String query = "select docid, queryresult_string from "
793
                          + "xml_queryresult where returnfield_id = " +
794
                          returnfield_id +" and docid in ("+ doclist + ")";
795
             logMetacat.info("Query to get docids from xml_queryresult:"
796
                                      + query);
797

    
798
             try {
799
                 // prepare and execute the query
800
                 pstmt = dbconn.prepareStatement(query);
801
                 dbconn.increaseUsageCount(1);
802
                 pstmt.execute();
803
                 rs = pstmt.getResultSet();
804
                 boolean tableHasRows = rs.next();
805
                 while (tableHasRows) {
806
                     // store the returned results in the returnValue hashtable
807
                     String key = rs.getString(1);
808
                     String element = rs.getString(2);
809

    
810
                     if(element != null){
811
                         returnValue.put(key, element);
812
                     } else {
813
                         logMetacat.info("Null elment found ("
814
                         + "DBQuery.docidsInQueryresultTable)");
815
                     }
816
                     tableHasRows = rs.next();
817
                 }
818
                 rs.close();
819
                 pstmt.close();
820
             } catch (Exception e){
821
                 logMetacat.error("Error getting docids from "
822
                                          + "queryresult in "
823
                                          + "DBQuery.docidsInQueryresultTable: "
824
                                          + e.getMessage());
825
              }
826
         }
827
         return returnValue;
828
     }
829

    
830

    
831
   /**
832
    * Method to get id from xml_returnfield table
833
    * for a given query specification
834
    */
835
   private int returnfield_id;
836
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
837
                                           DBConnection dbconn){
838
       int id = -1;
839
       int count = 1;
840
       PreparedStatement pstmt = null;
841
       ResultSet rs = null;
842
       String returnfield = qspec.getSortedReturnFieldString();
843

    
844
       // query for finding the id from xml_returnfield
845
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
846
            + "WHERE returnfield_string LIKE ?";
847
       logMetacat.info("ReturnField Query:" + query);
848

    
849
       try {
850
           // prepare and run the query
851
           pstmt = dbconn.prepareStatement(query);
852
           pstmt.setString(1,returnfield);
853
           dbconn.increaseUsageCount(1);
854
           pstmt.execute();
855
           rs = pstmt.getResultSet();
856
           boolean tableHasRows = rs.next();
857

    
858
           // if record found then increase the usage count
859
           // else insert a new record and get the id of the new record
860
           if(tableHasRows){
861
               // get the id
862
               id = rs.getInt(1);
863
               count = rs.getInt(2) + 1;
864
               rs.close();
865
               pstmt.close();
866

    
867
               // increase the usage count
868
               query = "UPDATE xml_returnfield SET usage_count ='" + count
869
                   + "' WHERE returnfield_id ='"+ id +"'";
870
               logMetacat.info("ReturnField Table Update:"+ query);
871

    
872
               pstmt = dbconn.prepareStatement(query);
873
               dbconn.increaseUsageCount(1);
874
               pstmt.execute();
875
               pstmt.close();
876

    
877
           } else {
878
               rs.close();
879
               pstmt.close();
880

    
881
               // insert a new record
882
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
883
                   + "VALUES (?, '1')";
884
               logMetacat.info("ReturnField Table Insert:"+ query);
885
               pstmt = dbconn.prepareStatement(query);
886
               pstmt.setString(1, returnfield);
887
               dbconn.increaseUsageCount(1);
888
               pstmt.execute();
889
               pstmt.close();
890

    
891
               // get the id of the new record
892
               query = "SELECT returnfield_id FROM xml_returnfield "
893
                   + "WHERE returnfield_string LIKE ?";
894
               logMetacat.info("ReturnField query after Insert:" + query);
895
               pstmt = dbconn.prepareStatement(query);
896
               pstmt.setString(1, returnfield);
897

    
898
               dbconn.increaseUsageCount(1);
899
               pstmt.execute();
900
               rs = pstmt.getResultSet();
901
               if(rs.next()){
902
                   id = rs.getInt(1);
903
               } else {
904
                   id = -1;
905
               }
906
               rs.close();
907
               pstmt.close();
908
           }
909

    
910
       } catch (Exception e){
911
           logMetacat.error("Error getting id from xml_returnfield in "
912
                                     + "DBQuery.getXmlReturnfieldsTableId: "
913
                                     + e.getMessage());
914
           id = -1;
915
       }
916

    
917
       returnfield_id = id;
918
       return count;
919
   }
920

    
921

    
922
    /*
923
     * A method to add return field to return doclist hash table
924
     */
925
    private Hashtable addReturnfield(Hashtable docListResult,
926
                                      QuerySpecification qspec,
927
                                      String user, String[]groups,
928
                                      DBConnection dbconn, boolean useXMLIndex )
929
                                      throws Exception
930
    {
931
      PreparedStatement pstmt = null;
932
      ResultSet rs = null;
933
      String docid = null;
934
      String fieldname = null;
935
      String fielddata = null;
936
      String relation = null;
937

    
938
      if (qspec.containsExtendedSQL())
939
      {
940
        qspec.setUserName(user);
941
        qspec.setGroup(groups);
942
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
943
        Vector results = new Vector();
944
        Enumeration keylist = docListResult.keys();
945
        StringBuffer doclist = new StringBuffer();
946
        Vector parentidList = new Vector();
947
        Hashtable returnFieldValue = new Hashtable();
948
        while (keylist.hasMoreElements())
949
        {
950
          doclist.append("'");
951
          doclist.append((String) keylist.nextElement());
952
          doclist.append("',");
953
        }
954
        if (doclist.length() > 0)
955
        {
956
          Hashtable controlPairs = new Hashtable();
957
          double extendedQueryStart = System.currentTimeMillis() / 1000;
958
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
959
          // check if user has permission to see the return field data
960
          String accessControlSQL =
961
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
962
          pstmt = dbconn.prepareStatement(accessControlSQL);
963
          //increase dbconnection usage count
964
          dbconn.increaseUsageCount(1);
965
          pstmt.execute();
966
          rs = pstmt.getResultSet();
967
          boolean tableHasRows = rs.next();
968
          while (tableHasRows)
969
          {
970
            long startNodeId = rs.getLong(1);
971
            long endNodeId = rs.getLong(2);
972
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
973
            tableHasRows = rs.next();
974
          }
975

    
976
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
977
           logMetacat.info( "Time for execute access extended query: "
978
                          + (extendedAccessQueryEnd - extendedQueryStart));
979

    
980
           String extendedQuery =
981
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
982
           logMetacat.warn("Extended query: " + extendedQuery);
983

    
984
           if(extendedQuery != null){
985
               pstmt = dbconn.prepareStatement(extendedQuery);
986
               //increase dbconnection usage count
987
               dbconn.increaseUsageCount(1);
988
               pstmt.execute();
989
               rs = pstmt.getResultSet();
990
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
991
               logMetacat.info(
992
                   "Time for execute extended query: "
993
                   + (extendedQueryEnd - extendedQueryStart));
994
               tableHasRows = rs.next();
995
               while (tableHasRows) {
996
                   ReturnFieldValue returnValue = new ReturnFieldValue();
997
                   docid = rs.getString(1).trim();
998
                   fieldname = rs.getString(2);
999
                   fielddata = rs.getString(3);
1000
                   fielddata = MetaCatUtil.normalize(fielddata);
1001
                   String parentId = rs.getString(4);
1002
                   StringBuffer value = new StringBuffer();
1003

    
1004
                   // if xml_index is used, there would be just one record per nodeid
1005
                   // as xml_index just keeps one entry for each path
1006
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1007
                       // don't need to merger nodedata
1008
                       value.append("<param name=\"");
1009
                       value.append(fieldname);
1010
                       value.append("\">");
1011
                       value.append(fielddata);
1012
                       value.append("</param>");
1013
                       //set returnvalue
1014
                       returnValue.setDocid(docid);
1015
                       returnValue.setFieldValue(fielddata);
1016
                       returnValue.setXMLFieldValue(value.toString());
1017
                       // Store it in hastable
1018
                       putInArray(parentidList, parentId, returnValue);
1019
                   }
1020
                   else {
1021
                       // need to merge nodedata if they have same parent id and
1022
                       // node type is text
1023
                       fielddata = (String) ( (ReturnFieldValue)
1024
                                             getArrayValue(
1025
                           parentidList, parentId)).getFieldValue()
1026
                           + fielddata;
1027
                       value.append("<param name=\"");
1028
                       value.append(fieldname);
1029
                       value.append("\">");
1030
                       value.append(fielddata);
1031
                       value.append("</param>");
1032
                       returnValue.setDocid(docid);
1033
                       returnValue.setFieldValue(fielddata);
1034
                       returnValue.setXMLFieldValue(value.toString());
1035
                       // remove the old return value from paretnidList
1036
                       parentidList.remove(parentId);
1037
                       // store the new return value in parentidlit
1038
                       putInArray(parentidList, parentId, returnValue);
1039
                   }
1040
                   tableHasRows = rs.next();
1041
               } //while
1042
               rs.close();
1043
               pstmt.close();
1044

    
1045
               // put the merger node data info into doclistReult
1046
               Enumeration xmlFieldValue = (getElements(parentidList)).
1047
                   elements();
1048
               while (xmlFieldValue.hasMoreElements()) {
1049
                   ReturnFieldValue object =
1050
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1051
                   docid = object.getDocid();
1052
                   if (docListResult.containsKey(docid)) {
1053
                       String removedelement = (String) docListResult.
1054
                           remove(docid);
1055
                       docListResult.
1056
                           put(docid,
1057
                               removedelement + object.getXMLFieldValue());
1058
                   }
1059
                   else {
1060
                       docListResult.put(docid, object.getXMLFieldValue());
1061
                   }
1062
               } //while
1063
               double docListResultEnd = System.currentTimeMillis() / 1000;
1064
               logMetacat.warn(
1065
                   "Time for prepare doclistresult after"
1066
                   + " execute extended query: "
1067
                   + (docListResultEnd - extendedQueryEnd));
1068
           }
1069

    
1070
           // get attribures return
1071
           docListResult = getAttributeValueForReturn(qspec,
1072
                           docListResult, doclist.toString(), useXMLIndex);
1073
       }//if doclist lenght is great than zero
1074

    
1075
     }//if has extended query
1076

    
1077
      return docListResult;
1078
    }//addReturnfield
1079

    
1080
    /*
1081
    * A method to add relationship to return doclist hash table
1082
    */
1083
   private Hashtable addRelationship(Hashtable docListResult,
1084
                                     QuerySpecification qspec,
1085
                                     DBConnection dbconn, boolean useXMLIndex )
1086
                                     throws Exception
1087
  {
1088
    PreparedStatement pstmt = null;
1089
    ResultSet rs = null;
1090
    StringBuffer document = null;
1091
    double startRelation = System.currentTimeMillis() / 1000;
1092
    Enumeration docidkeys = docListResult.keys();
1093
    while (docidkeys.hasMoreElements())
1094
    {
1095
      //String connstring =
1096
      // "metacat://"+util.getOption("server")+"?docid=";
1097
      String connstring = "%docid=";
1098
      String docidkey = (String) docidkeys.nextElement();
1099
      pstmt = dbconn.prepareStatement(QuerySpecification
1100
                      .printRelationSQL(docidkey));
1101
      pstmt.execute();
1102
      rs = pstmt.getResultSet();
1103
      boolean tableHasRows = rs.next();
1104
      while (tableHasRows)
1105
      {
1106
        String sub = rs.getString(1);
1107
        String rel = rs.getString(2);
1108
        String obj = rs.getString(3);
1109
        String subDT = rs.getString(4);
1110
        String objDT = rs.getString(5);
1111

    
1112
        document = new StringBuffer();
1113
        document.append("<triple>");
1114
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1115
        document.append("</subject>");
1116
        if (subDT != null)
1117
        {
1118
          document.append("<subjectdoctype>").append(subDT);
1119
          document.append("</subjectdoctype>");
1120
        }
1121
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1122
        document.append("</relationship>");
1123
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1124
        document.append("</object>");
1125
        if (objDT != null)
1126
        {
1127
          document.append("<objectdoctype>").append(objDT);
1128
          document.append("</objectdoctype>");
1129
        }
1130
        document.append("</triple>");
1131

    
1132
        String removedelement = (String) docListResult.remove(docidkey);
1133
        docListResult.put(docidkey, removedelement+ document.toString());
1134
        tableHasRows = rs.next();
1135
      }//while
1136
      rs.close();
1137
      pstmt.close();
1138
    }//while
1139
    double endRelation = System.currentTimeMillis() / 1000;
1140
    logMetacat.info("Time for adding relation to docListResult: "
1141
                             + (endRelation - startRelation));
1142

    
1143
    return docListResult;
1144
  }//addRelation
1145

    
1146
  /**
1147
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1148
   * string as a param instead of a hashtable.
1149
   *
1150
   * @param xmlquery a string representing a query.
1151
   */
1152
   private  String transformQuery(String xmlquery)
1153
   {
1154
     xmlquery = xmlquery.trim();
1155
     int index = xmlquery.indexOf("?>");
1156
     if (index != -1)
1157
     {
1158
       return xmlquery.substring(index + 2, xmlquery.length());
1159
     }
1160
     else
1161
     {
1162
       return xmlquery;
1163
     }
1164
   }
1165

    
1166

    
1167
    /*
1168
     * A method to search if Vector contains a particular key string
1169
     */
1170
    private boolean containsKey(Vector parentidList, String parentId)
1171
    {
1172

    
1173
        Vector tempVector = null;
1174

    
1175
        for (int count = 0; count < parentidList.size(); count++) {
1176
            tempVector = (Vector) parentidList.get(count);
1177
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1178
        }
1179
        return false;
1180
    }
1181

    
1182
    /*
1183
     * A method to put key and value in Vector
1184
     */
1185
    private void putInArray(Vector parentidList, String key,
1186
            ReturnFieldValue value)
1187
    {
1188

    
1189
        Vector tempVector = null;
1190

    
1191
        for (int count = 0; count < parentidList.size(); count++) {
1192
            tempVector = (Vector) parentidList.get(count);
1193

    
1194
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1195
                tempVector.remove(1);
1196
                tempVector.add(1, value);
1197
                return;
1198
            }
1199
        }
1200

    
1201
        tempVector = new Vector();
1202
        tempVector.add(0, key);
1203
        tempVector.add(1, value);
1204
        parentidList.add(tempVector);
1205
        return;
1206
    }
1207

    
1208
    /*
1209
     * A method to get value in Vector given a key
1210
     */
1211
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1212
    {
1213

    
1214
        Vector tempVector = null;
1215

    
1216
        for (int count = 0; count < parentidList.size(); count++) {
1217
            tempVector = (Vector) parentidList.get(count);
1218

    
1219
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1220
                    .get(1); }
1221
        }
1222
        return null;
1223
    }
1224

    
1225
    /*
1226
     * A method to get enumeration of all values in Vector
1227
     */
1228
    private Vector getElements(Vector parentidList)
1229
    {
1230
        Vector enumVector = new Vector();
1231
        Vector tempVector = null;
1232

    
1233
        for (int count = 0; count < parentidList.size(); count++) {
1234
            tempVector = (Vector) parentidList.get(count);
1235

    
1236
            enumVector.add(tempVector.get(1));
1237
        }
1238
        return enumVector;
1239
    }
1240

    
1241
    /*
1242
     * A method to return search result after running a query which return
1243
     * field have attribue
1244
     */
1245
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
1246
            Hashtable docInformationList, String docList, boolean useXMLIndex)
1247
    {
1248
        StringBuffer XML = null;
1249
        String sql = null;
1250
        DBConnection dbconn = null;
1251
        PreparedStatement pstmt = null;
1252
        ResultSet rs = null;
1253
        int serialNumber = -1;
1254
        boolean tableHasRows = false;
1255

    
1256
        //check the parameter
1257
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1258

    
1259
        // if has attribute as return field
1260
        if (squery.containsAttributeReturnField()) {
1261
            sql = squery.printAttributeQuery(docList, useXMLIndex);
1262
            try {
1263
                dbconn = DBConnectionPool
1264
                        .getDBConnection("DBQuery.getAttributeValue");
1265
                serialNumber = dbconn.getCheckOutSerialNumber();
1266
                pstmt = dbconn.prepareStatement(sql);
1267
                pstmt.execute();
1268
                rs = pstmt.getResultSet();
1269
                tableHasRows = rs.next();
1270
                while (tableHasRows) {
1271
                    String docid = rs.getString(1).trim();
1272
                    String fieldname = rs.getString(2);
1273
                    String fielddata = rs.getString(3);
1274
                    String attirbuteName = rs.getString(4);
1275
                    XML = new StringBuffer();
1276

    
1277
                    XML.append("<param name=\"");
1278
                    XML.append(fieldname);
1279
                    XML.append("/");
1280
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1281
                    XML.append(attirbuteName);
1282
                    XML.append("\">");
1283
                    XML.append(fielddata);
1284
                    XML.append("</param>");
1285
                    tableHasRows = rs.next();
1286

    
1287
                    if (docInformationList.containsKey(docid)) {
1288
                        String removedelement = (String) docInformationList
1289
                                .remove(docid);
1290
                        docInformationList.put(docid, removedelement
1291
                                + XML.toString());
1292
                    } else {
1293
                        docInformationList.put(docid, XML.toString());
1294
                    }
1295
                }//while
1296
                rs.close();
1297
                pstmt.close();
1298
            } catch (Exception se) {
1299
                logMetacat.error(
1300
                        "Error in DBQuery.getAttributeValue1: "
1301
                                + se.getMessage());
1302
            } finally {
1303
                try {
1304
                    pstmt.close();
1305
                }//try
1306
                catch (SQLException sqlE) {
1307
                    logMetacat.error(
1308
                            "Error in DBQuery.getAttributeValue2: "
1309
                                    + sqlE.getMessage());
1310
                }//catch
1311
                finally {
1312
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
1313
                }//finally
1314
            }//finally
1315
        }//if
1316
        return docInformationList;
1317

    
1318
    }
1319

    
1320
    /*
1321
     * A method to create a query to get owner's docid list
1322
     */
1323
    private String getOwnerQuery(String owner)
1324
    {
1325
        if (owner != null) {
1326
            owner = owner.toLowerCase();
1327
        }
1328
        StringBuffer self = new StringBuffer();
1329

    
1330
        self.append("SELECT docid,docname,doctype,");
1331
        self.append("date_created, date_updated, rev ");
1332
        self.append("FROM xml_documents WHERE docid IN (");
1333
        self.append("(");
1334
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1335
        self.append("nodedata LIKE '%%%' ");
1336
        self.append(") \n");
1337
        self.append(") ");
1338
        self.append(" AND (");
1339
        self.append(" lower(user_owner) = '" + owner + "'");
1340
        self.append(") ");
1341
        return self.toString();
1342
    }
1343

    
1344
    /**
1345
     * format a structured query as an XML document that conforms to the
1346
     * pathquery.dtd and is appropriate for submission to the DBQuery
1347
     * structured query engine
1348
     *
1349
     * @param params The list of parameters that should be included in the
1350
     *            query
1351
     */
1352
    public static String createSQuery(Hashtable params)
1353
    {
1354
        StringBuffer query = new StringBuffer();
1355
        Enumeration elements;
1356
        Enumeration keys;
1357
        String filterDoctype = null;
1358
        String casesensitive = null;
1359
        String searchmode = null;
1360
        Object nextkey;
1361
        Object nextelement;
1362
        //add the xml headers
1363
        query.append("<?xml version=\"1.0\"?>\n");
1364
        query.append("<pathquery version=\"1.2\">\n");
1365

    
1366

    
1367

    
1368
        if (params.containsKey("meta_file_id")) {
1369
            query.append("<meta_file_id>");
1370
            query.append(((String[]) params.get("meta_file_id"))[0]);
1371
            query.append("</meta_file_id>");
1372
        }
1373

    
1374
        if (params.containsKey("returndoctype")) {
1375
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1376
            for (int i = 0; i < returnDoctypes.length; i++) {
1377
                String doctype = (String) returnDoctypes[i];
1378

    
1379
                if (!doctype.equals("any") && !doctype.equals("ANY")
1380
                        && !doctype.equals("")) {
1381
                    query.append("<returndoctype>").append(doctype);
1382
                    query.append("</returndoctype>");
1383
                }
1384
            }
1385
        }
1386

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

    
1395
        if (params.containsKey("returnfield")) {
1396
            String[] returnfield = ((String[]) params.get("returnfield"));
1397
            for (int i = 0; i < returnfield.length; i++) {
1398
                query.append("<returnfield>").append(returnfield[i]);
1399
                query.append("</returnfield>");
1400
            }
1401
        }
1402

    
1403
        if (params.containsKey("owner")) {
1404
            String[] owner = ((String[]) params.get("owner"));
1405
            for (int i = 0; i < owner.length; i++) {
1406
                query.append("<owner>").append(owner[i]);
1407
                query.append("</owner>");
1408
            }
1409
        }
1410

    
1411
        if (params.containsKey("site")) {
1412
            String[] site = ((String[]) params.get("site"));
1413
            for (int i = 0; i < site.length; i++) {
1414
                query.append("<site>").append(site[i]);
1415
                query.append("</site>");
1416
            }
1417
        }
1418

    
1419
        //allows the dynamic switching of boolean operators
1420
        if (params.containsKey("operator")) {
1421
            query.append("<querygroup operator=\""
1422
                    + ((String[]) params.get("operator"))[0] + "\">");
1423
        } else { //the default operator is UNION
1424
            query.append("<querygroup operator=\"UNION\">");
1425
        }
1426

    
1427
        if (params.containsKey("casesensitive")) {
1428
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1429
        } else {
1430
            casesensitive = "false";
1431
        }
1432

    
1433
        if (params.containsKey("searchmode")) {
1434
            searchmode = ((String[]) params.get("searchmode"))[0];
1435
        } else {
1436
            searchmode = "contains";
1437
        }
1438

    
1439
        //anyfield is a special case because it does a
1440
        //free text search. It does not have a <pathexpr>
1441
        //tag. This allows for a free text search within the structured
1442
        //query. This is useful if the INTERSECT operator is used.
1443
        if (params.containsKey("anyfield")) {
1444
            String[] anyfield = ((String[]) params.get("anyfield"));
1445
            //allow for more than one value for anyfield
1446
            for (int i = 0; i < anyfield.length; i++) {
1447
                if (!anyfield[i].equals("")) {
1448
                    query.append("<queryterm casesensitive=\"" + casesensitive
1449
                            + "\" " + "searchmode=\"" + searchmode
1450
                            + "\"><value>" + anyfield[i]
1451
                            + "</value></queryterm>");
1452
                }
1453
            }
1454
        }
1455

    
1456
        //this while loop finds the rest of the parameters
1457
        //and attempts to query for the field specified
1458
        //by the parameter.
1459
        elements = params.elements();
1460
        keys = params.keys();
1461
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1462
            nextkey = keys.nextElement();
1463
            nextelement = elements.nextElement();
1464

    
1465
            //make sure we aren't querying for any of these
1466
            //parameters since the are already in the query
1467
            //in one form or another.
1468
            Vector ignoredParams = new Vector();
1469
            ignoredParams.add("returndoctype");
1470
            ignoredParams.add("filterdoctype");
1471
            ignoredParams.add("action");
1472
            ignoredParams.add("qformat");
1473
            ignoredParams.add("anyfield");
1474
            ignoredParams.add("returnfield");
1475
            ignoredParams.add("owner");
1476
            ignoredParams.add("site");
1477
            ignoredParams.add("operator");
1478
            ignoredParams.add("sessionid");
1479

    
1480
            // Also ignore parameters listed in the properties file
1481
            // so that they can be passed through to stylesheets
1482
            String paramsToIgnore = MetaCatUtil
1483
                    .getOption("query.ignored.params");
1484
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1485
            while (st.hasMoreTokens()) {
1486
                ignoredParams.add(st.nextToken());
1487
            }
1488
            if (!ignoredParams.contains(nextkey.toString())) {
1489
                //allow for more than value per field name
1490
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1491
                    if (!((String[]) nextelement)[i].equals("")) {
1492
                        query.append("<queryterm casesensitive=\""
1493
                                + casesensitive + "\" " + "searchmode=\""
1494
                                + searchmode + "\">" + "<value>" +
1495
                                //add the query value
1496
                                ((String[]) nextelement)[i]
1497
                                + "</value><pathexpr>" +
1498
                                //add the path to query by
1499
                                nextkey.toString() + "</pathexpr></queryterm>");
1500
                    }
1501
                }
1502
            }
1503
        }
1504
        query.append("</querygroup></pathquery>");
1505
        //append on the end of the xml and return the result as a string
1506
        return query.toString();
1507
    }
1508

    
1509
    /**
1510
     * format a simple free-text value query as an XML document that conforms
1511
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1512
     * structured query engine
1513
     *
1514
     * @param value the text string to search for in the xml catalog
1515
     * @param doctype the type of documents to include in the result set -- use
1516
     *            "any" or "ANY" for unfiltered result sets
1517
     */
1518
    public static String createQuery(String value, String doctype)
1519
    {
1520
        StringBuffer xmlquery = new StringBuffer();
1521
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1522
        xmlquery.append("<pathquery version=\"1.0\">");
1523

    
1524
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1525
            xmlquery.append("<returndoctype>");
1526
            xmlquery.append(doctype).append("</returndoctype>");
1527
        }
1528

    
1529
        xmlquery.append("<querygroup operator=\"UNION\">");
1530
        //chad added - 8/14
1531
        //the if statement allows a query to gracefully handle a null
1532
        //query. Without this if a nullpointerException is thrown.
1533
        if (!value.equals("")) {
1534
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1535
            xmlquery.append("searchmode=\"contains\">");
1536
            xmlquery.append("<value>").append(value).append("</value>");
1537
            xmlquery.append("</queryterm>");
1538
        }
1539
        xmlquery.append("</querygroup>");
1540
        xmlquery.append("</pathquery>");
1541

    
1542
        return (xmlquery.toString());
1543
    }
1544

    
1545
    /**
1546
     * format a simple free-text value query as an XML document that conforms
1547
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1548
     * structured query engine
1549
     *
1550
     * @param value the text string to search for in the xml catalog
1551
     */
1552
    public static String createQuery(String value)
1553
    {
1554
        return createQuery(value, "any");
1555
    }
1556

    
1557
    /**
1558
     * Check for "READ" permission on @docid for @user and/or @group from DB
1559
     * connection
1560
     */
1561
    private boolean hasPermission(String user, String[] groups, String docid)
1562
            throws SQLException, Exception
1563
    {
1564
        // Check for READ permission on @docid for @user and/or @groups
1565
        PermissionController controller = new PermissionController(docid);
1566
        return controller.hasPermission(user, groups,
1567
                AccessControlInterface.READSTRING);
1568
    }
1569

    
1570
    /**
1571
     * Get all docIds list for a data packadge
1572
     *
1573
     * @param dataPackageDocid, the string in docId field of xml_relation table
1574
     */
1575
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1576
    {
1577
        DBConnection dbConn = null;
1578
        int serialNumber = -1;
1579
        Vector docIdList = new Vector();//return value
1580
        PreparedStatement pStmt = null;
1581
        ResultSet rs = null;
1582
        String docIdInSubjectField = null;
1583
        String docIdInObjectField = null;
1584

    
1585
        // Check the parameter
1586
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1587

    
1588
        //the query stirng
1589
        String query = "SELECT subject, object from xml_relation where docId = ?";
1590
        try {
1591
            dbConn = DBConnectionPool
1592
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1593
            serialNumber = dbConn.getCheckOutSerialNumber();
1594
            pStmt = dbConn.prepareStatement(query);
1595
            //bind the value to query
1596
            pStmt.setString(1, dataPackageDocid);
1597

    
1598
            //excute the query
1599
            pStmt.execute();
1600
            //get the result set
1601
            rs = pStmt.getResultSet();
1602
            //process the result
1603
            while (rs.next()) {
1604
                //In order to get the whole docIds in a data packadge,
1605
                //we need to put the docIds of subject and object field in
1606
                // xml_relation
1607
                //into the return vector
1608
                docIdInSubjectField = rs.getString(1);//the result docId in
1609
                                                      // subject field
1610
                docIdInObjectField = rs.getString(2);//the result docId in
1611
                                                     // object field
1612

    
1613
                //don't put the duplicate docId into the vector
1614
                if (!docIdList.contains(docIdInSubjectField)) {
1615
                    docIdList.add(docIdInSubjectField);
1616
                }
1617

    
1618
                //don't put the duplicate docId into the vector
1619
                if (!docIdList.contains(docIdInObjectField)) {
1620
                    docIdList.add(docIdInObjectField);
1621
                }
1622
            }//while
1623
            //close the pStmt
1624
            pStmt.close();
1625
        }//try
1626
        catch (SQLException e) {
1627
            logMetacat.error("Error in getDocidListForDataPackage: "
1628
                    + e.getMessage());
1629
        }//catch
1630
        finally {
1631
            try {
1632
                pStmt.close();
1633
            }//try
1634
            catch (SQLException ee) {
1635
                logMetacat.error(
1636
                        "Error in getDocidListForDataPackage: "
1637
                                + ee.getMessage());
1638
            }//catch
1639
            finally {
1640
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1641
            }//fianlly
1642
        }//finally
1643
        return docIdList;
1644
    }//getCurrentDocidListForDataPackadge()
1645

    
1646
    /**
1647
     * Get all docIds list for a data packadge
1648
     *
1649
     * @param dataPackageDocid, the string in docId field of xml_relation table
1650
     */
1651
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1652
    {
1653

    
1654
        Vector docIdList = new Vector();//return value
1655
        Vector tripleList = null;
1656
        String xml = null;
1657

    
1658
        // Check the parameter
1659
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1660

    
1661
        try {
1662
            //initial a documentImpl object
1663
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1664
            //transfer to documentImpl object to string
1665
            xml = packageDocument.toString();
1666

    
1667
            //create a tripcollection object
1668
            TripleCollection tripleForPackage = new TripleCollection(
1669
                    new StringReader(xml));
1670
            //get the vetor of triples
1671
            tripleList = tripleForPackage.getCollection();
1672

    
1673
            for (int i = 0; i < tripleList.size(); i++) {
1674
                //put subject docid into docIdlist without duplicate
1675
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1676
                        .getSubject())) {
1677
                    //put subject docid into docIdlist
1678
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1679
                }
1680
                //put object docid into docIdlist without duplicate
1681
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1682
                        .getObject())) {
1683
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1684
                }
1685
            }//for
1686
        }//try
1687
        catch (Exception e) {
1688
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1689
                    + e.getMessage());
1690
        }//catch
1691

    
1692
        // return result
1693
        return docIdList;
1694
    }//getDocidListForPackageInXMLRevisions()
1695

    
1696
    /**
1697
     * Check if the docId is a data packadge id. If the id is a data packadage
1698
     * id, it should be store in the docId fields in xml_relation table. So we
1699
     * can use a query to get the entries which the docId equals the given
1700
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1701
     * it is.
1702
     *
1703
     * @param docId, the id need to be checked
1704
     */
1705
    private boolean isDataPackageId(String docId)
1706
    {
1707
        boolean result = false;
1708
        PreparedStatement pStmt = null;
1709
        ResultSet rs = null;
1710
        String query = "SELECT docId from xml_relation where docId = ?";
1711
        DBConnection dbConn = null;
1712
        int serialNumber = -1;
1713
        try {
1714
            dbConn = DBConnectionPool
1715
                    .getDBConnection("DBQuery.isDataPackageId");
1716
            serialNumber = dbConn.getCheckOutSerialNumber();
1717
            pStmt = dbConn.prepareStatement(query);
1718
            //bind the value to query
1719
            pStmt.setString(1, docId);
1720
            //execute the query
1721
            pStmt.execute();
1722
            rs = pStmt.getResultSet();
1723
            //process the result
1724
            if (rs.next()) //There are some records for the id in docId fields
1725
            {
1726
                result = true;//It is a data packadge id
1727
            }
1728
            pStmt.close();
1729
        }//try
1730
        catch (SQLException e) {
1731
            logMetacat.error("Error in isDataPackageId: "
1732
                    + e.getMessage());
1733
        } finally {
1734
            try {
1735
                pStmt.close();
1736
            }//try
1737
            catch (SQLException ee) {
1738
                logMetacat.error("Error in isDataPackageId: "
1739
                        + ee.getMessage());
1740
            }//catch
1741
            finally {
1742
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1743
            }//finally
1744
        }//finally
1745
        return result;
1746
    }//isDataPackageId()
1747

    
1748
    /**
1749
     * Check if the user has the permission to export data package
1750
     *
1751
     * @param conn, the connection
1752
     * @param docId, the id need to be checked
1753
     * @param user, the name of user
1754
     * @param groups, the user's group
1755
     */
1756
    private boolean hasPermissionToExportPackage(String docId, String user,
1757
            String[] groups) throws Exception
1758
    {
1759
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1760
        return DocumentImpl.hasReadPermission(user, groups, docId);
1761
    }
1762

    
1763
    /**
1764
     * Get the current Rev for a docid in xml_documents table
1765
     *
1766
     * @param docId, the id need to get version numb If the return value is -5,
1767
     *            means no value in rev field for this docid
1768
     */
1769
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1770
            throws SQLException
1771
    {
1772
        int rev = -5;
1773
        PreparedStatement pStmt = null;
1774
        ResultSet rs = null;
1775
        String query = "SELECT rev from xml_documents where docId = ?";
1776
        DBConnection dbConn = null;
1777
        int serialNumber = -1;
1778
        try {
1779
            dbConn = DBConnectionPool
1780
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1781
            serialNumber = dbConn.getCheckOutSerialNumber();
1782
            pStmt = dbConn.prepareStatement(query);
1783
            //bind the value to query
1784
            pStmt.setString(1, docId);
1785
            //execute the query
1786
            pStmt.execute();
1787
            rs = pStmt.getResultSet();
1788
            //process the result
1789
            if (rs.next()) //There are some records for rev
1790
            {
1791
                rev = rs.getInt(1);
1792
                ;//It is the version for given docid
1793
            } else {
1794
                rev = -5;
1795
            }
1796

    
1797
        }//try
1798
        catch (SQLException e) {
1799
            logMetacat.error(
1800
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1801
                            + e.getMessage());
1802
            throw e;
1803
        }//catch
1804
        finally {
1805
            try {
1806
                pStmt.close();
1807
            }//try
1808
            catch (SQLException ee) {
1809
                logMetacat.error(
1810
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1811
                                + ee.getMessage());
1812
            }//catch
1813
            finally {
1814
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1815
            }//finally
1816
        }//finally
1817
        return rev;
1818
    }//getCurrentRevFromXMLDoumentsTable
1819

    
1820
    /**
1821
     * put a doc into a zip output stream
1822
     *
1823
     * @param docImpl, docmentImpl object which will be sent to zip output
1824
     *            stream
1825
     * @param zipOut, zip output stream which the docImpl will be put
1826
     * @param packageZipEntry, the zip entry name for whole package
1827
     */
1828
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1829
            ZipOutputStream zipOut, String packageZipEntry)
1830
            throws ClassNotFoundException, IOException, SQLException,
1831
            McdbException, Exception
1832
    {
1833
        byte[] byteString = null;
1834
        ZipEntry zEntry = null;
1835

    
1836
        byteString = docImpl.toString().getBytes();
1837
        //use docId as the zip entry's name
1838
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1839
                + docImpl.getDocID());
1840
        zEntry.setSize(byteString.length);
1841
        zipOut.putNextEntry(zEntry);
1842
        zipOut.write(byteString, 0, byteString.length);
1843
        zipOut.closeEntry();
1844

    
1845
    }//addDocToZipOutputStream()
1846

    
1847
    /**
1848
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1849
     * only inlcudes current version. If a DocumentImple object couldn't find
1850
     * for a docid, then the String of this docid was added to vetor rather
1851
     * than DocumentImple object.
1852
     *
1853
     * @param docIdList, a vetor hold a docid list for a data package. In
1854
     *            docid, there is not version number in it.
1855
     */
1856

    
1857
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1858
            throws McdbException, Exception
1859
    {
1860
        //Connection dbConn=null;
1861
        Vector documentImplList = new Vector();
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
            try {
1870
                //get newest version for this docId
1871
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1872
                        .elementAt(i));
1873

    
1874
                // There is no record for this docId in xml_documents table
1875
                if (rev == -5) {
1876
                    // Rather than put DocumentImple object, put a String
1877
                    // Object(docid)
1878
                    // into the documentImplList
1879
                    documentImplList.add((String) docIdList.elementAt(i));
1880
                    // Skip other code
1881
                    continue;
1882
                }
1883

    
1884
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1885
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1886

    
1887
                //create new documentImpl object
1888
                DocumentImpl documentImplObject = new DocumentImpl(
1889
                        docidPlusVersion);
1890
                //add them to vector
1891
                documentImplList.add(documentImplObject);
1892
            }//try
1893
            catch (Exception e) {
1894
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
1895
                        + e.getMessage());
1896
                // continue the for loop
1897
                continue;
1898
            }
1899
        }//for
1900
        return documentImplList;
1901
    }
1902

    
1903
    /**
1904
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
1905
     * object couldn't find for a docid, then the String of this docid was
1906
     * added to vetor rather than DocumentImple object.
1907
     *
1908
     * @param docIdList, a vetor hold a docid list for a data package. In
1909
     *            docid, t here is version number in it.
1910
     */
1911
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
1912
    {
1913
        //Connection dbConn=null;
1914
        Vector documentImplList = new Vector();
1915
        String siteCode = null;
1916
        String uniqueId = null;
1917
        int rev = 0;
1918

    
1919
        // Check the parameter
1920
        if (docIdList.isEmpty()) { return documentImplList; }//if
1921

    
1922
        //for every docid in vector
1923
        for (int i = 0; i < docIdList.size(); i++) {
1924

    
1925
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1926

    
1927
            try {
1928
                //create new documentImpl object
1929
                DocumentImpl documentImplObject = new DocumentImpl(
1930
                        docidPlusVersion);
1931
                //add them to vector
1932
                documentImplList.add(documentImplObject);
1933
            }//try
1934
            catch (McdbDocNotFoundException notFoundE) {
1935
                logMetacat.error(
1936
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1937
                                + notFoundE.getMessage());
1938
                // Rather than add a DocumentImple object into vetor, a String
1939
                // object
1940
                // - the doicd was added to the vector
1941
                documentImplList.add(docidPlusVersion);
1942
                // Continue the for loop
1943
                continue;
1944
            }//catch
1945
            catch (Exception e) {
1946
                logMetacat.error(
1947
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
1948
                                + e.getMessage());
1949
                // Continue the for loop
1950
                continue;
1951
            }//catch
1952

    
1953
        }//for
1954
        return documentImplList;
1955
    }//getOldVersionAllDocumentImple
1956

    
1957
    /**
1958
     * put a data file into a zip output stream
1959
     *
1960
     * @param docImpl, docmentImpl object which will be sent to zip output
1961
     *            stream
1962
     * @param zipOut, the zip output stream which the docImpl will be put
1963
     * @param packageZipEntry, the zip entry name for whole package
1964
     */
1965
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
1966
            ZipOutputStream zipOut, String packageZipEntry)
1967
            throws ClassNotFoundException, IOException, SQLException,
1968
            McdbException, Exception
1969
    {
1970
        byte[] byteString = null;
1971
        ZipEntry zEntry = null;
1972
        // this is data file; add file to zip
1973
        String filePath = MetaCatUtil.getOption("datafilepath");
1974
        if (!filePath.endsWith("/")) {
1975
            filePath += "/";
1976
        }
1977
        String fileName = filePath + docImpl.getDocID();
1978
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
1979
        zipOut.putNextEntry(zEntry);
1980
        FileInputStream fin = null;
1981
        try {
1982
            fin = new FileInputStream(fileName);
1983
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1984
            int b = fin.read(buf);
1985
            while (b != -1) {
1986
                zipOut.write(buf, 0, b);
1987
                b = fin.read(buf);
1988
            }//while
1989
            zipOut.closeEntry();
1990
        }//try
1991
        catch (IOException ioe) {
1992
            logMetacat.error("There is an exception: "
1993
                    + ioe.getMessage());
1994
        }//catch
1995
    }//addDataFileToZipOutputStream()
1996

    
1997
    /**
1998
     * create a html summary for data package and put it into zip output stream
1999
     *
2000
     * @param docImplList, the documentImpl ojbects in data package
2001
     * @param zipOut, the zip output stream which the html should be put
2002
     * @param packageZipEntry, the zip entry name for whole package
2003
     */
2004
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2005
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2006
    {
2007
        StringBuffer htmlDoc = new StringBuffer();
2008
        ZipEntry zEntry = null;
2009
        byte[] byteString = null;
2010
        InputStream source;
2011
        DBTransform xmlToHtml;
2012

    
2013
        //create a DBTransform ojbect
2014
        xmlToHtml = new DBTransform();
2015
        //head of html
2016
        htmlDoc.append("<html><head></head><body>");
2017
        for (int i = 0; i < docImplList.size(); i++) {
2018
            // If this String object, this means it is missed data file
2019
            if ((((docImplList.elementAt(i)).getClass()).toString())
2020
                    .equals("class java.lang.String")) {
2021

    
2022
                htmlDoc.append("<a href=\"");
2023
                String dataFileid = (String) docImplList.elementAt(i);
2024
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2025
                htmlDoc.append("Data File: ");
2026
                htmlDoc.append(dataFileid).append("</a><br>");
2027
                htmlDoc.append("<br><hr><br>");
2028

    
2029
            }//if
2030
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2031
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2032
                                              // transform it.
2033
                //transform each file individually then concatenate all of the
2034
                //transformations together.
2035

    
2036
                //for metadata xml title
2037
                htmlDoc.append("<h2>");
2038
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2039
                        .getDocID());
2040
                //htmlDoc.append(".");
2041
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2042
                htmlDoc.append("</h2>");
2043
                //do the actual transform
2044
                StringWriter docString = new StringWriter();
2045
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2046
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2047
                        "-//W3C//HTML//EN", "html", docString);
2048
                htmlDoc.append(docString.toString());
2049
                htmlDoc.append("<br><br><hr><br><br>");
2050
            }//if
2051
            else { //this is a data file so we should link to it in the html
2052
                htmlDoc.append("<a href=\"");
2053
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2054
                        .getDocID();
2055
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2056
                htmlDoc.append("Data File: ");
2057
                htmlDoc.append(dataFileid).append("</a><br>");
2058
                htmlDoc.append("<br><hr><br>");
2059
            }//else
2060
        }//for
2061
        htmlDoc.append("</body></html>");
2062
        byteString = htmlDoc.toString().getBytes();
2063
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2064
        zEntry.setSize(byteString.length);
2065
        zipOut.putNextEntry(zEntry);
2066
        zipOut.write(byteString, 0, byteString.length);
2067
        zipOut.closeEntry();
2068
        //dbConn.close();
2069

    
2070
    }//addHtmlSummaryToZipOutputStream
2071

    
2072
    /**
2073
     * put a data packadge into a zip output stream
2074
     *
2075
     * @param docId, which the user want to put into zip output stream,it has version
2076
     * @param out, a servletoutput stream which the zip output stream will be
2077
     *            put
2078
     * @param user, the username of the user
2079
     * @param groups, the group of the user
2080
     */
2081
    public ZipOutputStream getZippedPackage(String docIdString,
2082
            ServletOutputStream out, String user, String[] groups,
2083
            String passWord) throws ClassNotFoundException, IOException,
2084
            SQLException, McdbException, NumberFormatException, Exception
2085
    {
2086
        ZipOutputStream zOut = null;
2087
        String elementDocid = null;
2088
        DocumentImpl docImpls = null;
2089
        //Connection dbConn = null;
2090
        Vector docIdList = new Vector();
2091
        Vector documentImplList = new Vector();
2092
        Vector htmlDocumentImplList = new Vector();
2093
        String packageId = null;
2094
        String rootName = "package";//the package zip entry name
2095

    
2096
        String docId = null;
2097
        int version = -5;
2098
        // Docid without revision
2099
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2100
        // revision number
2101
        version = MetaCatUtil.getVersionFromString(docIdString);
2102

    
2103
        //check if the reqused docId is a data package id
2104
        if (!isDataPackageId(docId)) {
2105

    
2106
            /*
2107
             * Exception e = new Exception("The request the doc id "
2108
             * +docIdString+ " is not a data package id");
2109
             */
2110

    
2111
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2112
            // zip
2113
            //up the single document and return the zip file.
2114
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2115

    
2116
                Exception e = new Exception("User " + user
2117
                        + " does not have permission"
2118
                        + " to export the data package " + docIdString);
2119
                throw e;
2120
            }
2121

    
2122
            docImpls = new DocumentImpl(docIdString);
2123
            //checking if the user has the permission to read the documents
2124
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2125
                    .getDocID())) {
2126
                zOut = new ZipOutputStream(out);
2127
                //if the docImpls is metadata
2128
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2129
                    //add metadata into zip output stream
2130
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2131
                }//if
2132
                else {
2133
                    //it is data file
2134
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2135
                    htmlDocumentImplList.add(docImpls);
2136
                }//else
2137
            }//if
2138

    
2139
            zOut.finish(); //terminate the zip file
2140
            return zOut;
2141
        }
2142
        // Check the permission of user
2143
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2144

    
2145
            Exception e = new Exception("User " + user
2146
                    + " does not have permission"
2147
                    + " to export the data package " + docIdString);
2148
            throw e;
2149
        } else //it is a packadge id
2150
        {
2151
            //store the package id
2152
            packageId = docId;
2153
            //get current version in database
2154
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2155
            //If it is for current version (-1 means user didn't specify
2156
            // revision)
2157
            if ((version == -1) || version == currentVersion) {
2158
                //get current version number
2159
                version = currentVersion;
2160
                //get package zip entry name
2161
                //it should be docId.revsion.package
2162
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2163
                        + version + MetaCatUtil.getOption("accNumSeparator")
2164
                        + "package";
2165
                //get the whole id list for data packadge
2166
                docIdList = getCurrentDocidListForDataPackage(packageId);
2167
                //get the whole documentImple object
2168
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2169

    
2170
            }//if
2171
            else if (version > currentVersion || version < -1) {
2172
                throw new Exception("The user specified docid: " + docId + "."
2173
                        + version + " doesn't exist");
2174
            }//else if
2175
            else //for an old version
2176
            {
2177

    
2178
                rootName = docIdString
2179
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2180
                //get the whole id list for data packadge
2181
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2182

    
2183
                //get the whole documentImple object
2184
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2185
            }//else
2186

    
2187
            // Make sure documentImplist is not empty
2188
            if (documentImplList.isEmpty()) { throw new Exception(
2189
                    "Couldn't find component for data package: " + packageId); }//if
2190

    
2191
            zOut = new ZipOutputStream(out);
2192
            //put every element into zip output stream
2193
            for (int i = 0; i < documentImplList.size(); i++) {
2194
                // if the object in the vetor is String, this means we couldn't
2195
                // find
2196
                // the document locally, we need find it remote
2197
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2198
                        .equals("class java.lang.String")) {
2199
                    // Get String object from vetor
2200
                    String documentId = (String) documentImplList.elementAt(i);
2201
                    logMetacat.info("docid: " + documentId);
2202
                    // Get doicd without revision
2203
                    String docidWithoutRevision = MetaCatUtil
2204
                            .getDocIdFromString(documentId);
2205
                    logMetacat.info("docidWithoutRevsion: "
2206
                            + docidWithoutRevision);
2207
                    // Get revision
2208
                    String revision = MetaCatUtil
2209
                            .getRevisionStringFromString(documentId);
2210
                    logMetacat.info("revsion from docIdentifier: "
2211
                            + revision);
2212
                    // Zip entry string
2213
                    String zipEntryPath = rootName + "/data/";
2214
                    // Create a RemoteDocument object
2215
                    RemoteDocument remoteDoc = new RemoteDocument(
2216
                            docidWithoutRevision, revision, user, passWord,
2217
                            zipEntryPath);
2218
                    // Here we only read data file from remote metacat
2219
                    String docType = remoteDoc.getDocType();
2220
                    if (docType != null) {
2221
                        if (docType.equals("BIN")) {
2222
                            // Put remote document to zip output
2223
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2224
                            // Add String object to htmlDocumentImplList
2225
                            String elementInHtmlList = remoteDoc
2226
                                    .getDocIdWithoutRevsion()
2227
                                    + MetaCatUtil.getOption("accNumSeparator")
2228
                                    + remoteDoc.getRevision();
2229
                            htmlDocumentImplList.add(elementInHtmlList);
2230
                        }//if
2231
                    }//if
2232

    
2233
                }//if
2234
                else {
2235
                    //create a docmentImpls object (represent xml doc) base on
2236
                    // the docId
2237
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2238
                    //checking if the user has the permission to read the
2239
                    // documents
2240
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2241
                            .getDocID())) {
2242
                        //if the docImpls is metadata
2243
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2244
                            //add metadata into zip output stream
2245
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2246
                            //add the documentImpl into the vetor which will
2247
                            // be used in html
2248
                            htmlDocumentImplList.add(docImpls);
2249

    
2250
                        }//if
2251
                        else {
2252
                            //it is data file
2253
                            addDataFileToZipOutputStream(docImpls, zOut,
2254
                                    rootName);
2255
                            htmlDocumentImplList.add(docImpls);
2256
                        }//else
2257
                    }//if
2258
                }//else
2259
            }//for
2260

    
2261
            //add html summary file
2262
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2263
                    rootName);
2264
            zOut.finish(); //terminate the zip file
2265
            //dbConn.close();
2266
            return zOut;
2267
        }//else
2268
    }//getZippedPackage()
2269

    
2270
    private class ReturnFieldValue
2271
    {
2272

    
2273
        private String docid = null; //return field value for this docid
2274

    
2275
        private String fieldValue = null;
2276

    
2277
        private String xmlFieldValue = null; //return field value in xml
2278
                                             // format
2279

    
2280
        public void setDocid(String myDocid)
2281
        {
2282
            docid = myDocid;
2283
        }
2284

    
2285
        public String getDocid()
2286
        {
2287
            return docid;
2288
        }
2289

    
2290
        public void setFieldValue(String myValue)
2291
        {
2292
            fieldValue = myValue;
2293
        }
2294

    
2295
        public String getFieldValue()
2296
        {
2297
            return fieldValue;
2298
        }
2299

    
2300
        public void setXMLFieldValue(String xml)
2301
        {
2302
            xmlFieldValue = xml;
2303
        }
2304

    
2305
        public String getXMLFieldValue()
2306
        {
2307
            return xmlFieldValue;
2308
        }
2309

    
2310
    }
2311
}
(21-21/65)