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: sgarg $'
14
 *     '$Date: 2005-11-30 08:34:07 -0800 (Wed, 30 Nov 2005) $'
15
 * '$Revision: 2787 $'
16
 *
17
 * This program is free software; you can redistribute it and/or modify
18
 * it under the terms of the GNU General Public License as published by
19
 * the Free Software Foundation; either version 2 of the License, or
20
 * (at your option) any later version.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
 * GNU General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU General Public License
28
 * along with this program; if not, write to the Free Software
29
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30
 */
31

    
32
package edu.ucsb.nceas.metacat;
33

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

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

    
57
import org.apache.log4j.Logger;
58

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

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

    
71
    static final int ALL = 1;
72

    
73
    static final int WRITE = 2;
74

    
75
    static final int READ = 4;
76

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

    
80
    private MetaCatUtil util = new MetaCatUtil();
81

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

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

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

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

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

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

    
121
                double connTime = System.currentTimeMillis();
122

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

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

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

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

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

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

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

    
197

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

    
216
  }
217

    
218

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

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

    
258

    
259

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

    
278
         DBTransform trans = new DBTransform();
279
         response.setContentType("text/html");
280

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

    
287
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
288
                                 "-//W3C//HTML//EN", qformat, out, params,
289
                                 sessionid);
290

    
291
        }
292
        catch(Exception e)
293
        {
294
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
295
                                +e.getMessage());
296
         }
297

    
298
      }//else
299

    
300
    }
301

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

    
330
        //checkout the dbconnection
331
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
332
        serialNumber = dbconn.getCheckOutSerialNumber();
333

    
334
        //print out the search result
335
        // search the doc list
336
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
337
                                      dbconn, useXMLIndex);
338

    
339
      } //try
340
      catch (IOException ioe)
341
      {
342
        logMetacat.error("IO error in DBQuery.findDocuments:");
343
        logMetacat.error(ioe.getMessage());
344

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

    
368
    return resultset;
369
  }//createResultDocuments
370

    
371

    
372

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

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

    
429
      double startTime = System.currentTimeMillis() / 1000;
430
      pstmt = dbconn.prepareStatement(query);
431

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

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

    
459
           //build the doctype list for the backtracking sql statement
460
           btBuf.append("packagetype in (");
461
           for (int i = 0; i < returndocVec.size(); i++)
462
           {
463
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
464
             if (i != (returndocVec.size() - 1))
465
             {
466
                btBuf.append(", ");
467
              }
468
            }
469
            btBuf.append(") ");
470
            btBuf.append("and (subject like '");
471
            btBuf.append(docid).append("'");
472
            btBuf.append("or object like '");
473
            btBuf.append(docid).append("')");
474

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

    
511
                String docid_org = xmldoc.getDocID();
512
                if (docid_org == null)
513
                {
514
                   logMetacat.info("Docid_org was null.");
515
                   //continue;
516
                }
517
                docid = docid_org.trim();
518
                docname = xmldoc.getDocname();
519
                doctype = xmldoc.getDoctype();
520
                createDate = xmldoc.getCreateDate();
521
                updateDate = xmldoc.getUpdateDate();
522
                rev = xmldoc.getRev();
523
                document = new StringBuffer();
524

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

    
550

    
551
                // Get the next package document linked to our hit
552
                hasBtRows = btrs.next();
553
              }//while
554
              npstmt.close();
555
              btrs.close();
556
        }
557
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
558
        {
559

    
560
           document = new StringBuffer();
561

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

    
586

    
587
        }//else
588
        // when doclist reached the offset number, send out doc list and empty
589
        // the hash table
590
        if (count == offset)
591
        {
592
          //reset count
593
          count = 0;
594
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
595
                              user, groups,dbconn, useXMLIndex);
596
          // reset docListResult
597
          docListResult = new Hashtable();
598

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

    
615
     return resultsetBuffer;
616
    }//findReturnDoclist
617

    
618

    
619
    /*
620
     * Send completed search hashtable(part of reulst)to output stream
621
     * and buffer into a buffer stream
622
     */
623
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
624
                                           StringBuffer resultset,
625
                                           PrintWriter out, Hashtable partOfDoclist,
626
                                           String user, String[]groups,
627
                                       DBConnection dbconn, boolean useXMLIndex)
628
                                       throws Exception
629
   {
630

    
631
     // check if there is a record in xml_returnfield
632
     // and get the returnfield_id and usage count
633
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
634
     boolean enterRecords = false;
635

    
636
     // get value of xml_returnfield_count
637
     int count = (new Integer(MetaCatUtil
638
                            .getOption("xml_returnfield_count")))
639
                            .intValue();
640

    
641
     // set enterRecords to true if usage_count is more than the offset
642
     // specified in metacat.properties
643
     if(usage_count > count){
644
         enterRecords = true;
645
     }
646

    
647
     if(returnfield_id < 0){
648
         logMetacat.warn("Error in getting returnfield id from"
649
                                  + "xml_returnfield table");
650
	enterRecords = false;
651
     }
652

    
653
     // get the hashtable containing the docids that already in the
654
     // xml_queryresult table
655
     logMetacat.info("size of partOfDoclist before"
656
                             + " docidsInQueryresultTable(): "
657
                             + partOfDoclist.size());
658
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
659
                                                        partOfDoclist, dbconn);
660

    
661
     // remove the keys in queryresultDocList from partOfDoclist
662
     Enumeration _keys = queryresultDocList.keys();
663
     while (_keys.hasMoreElements()){
664
         partOfDoclist.remove(_keys.nextElement());
665
     }
666

    
667
     // backup the keys-elements in partOfDoclist to check later
668
     // if the doc entry is indexed yet
669
     Hashtable partOfDoclistBackup = new Hashtable();
670
     _keys = partOfDoclist.keys();
671
     while (_keys.hasMoreElements()){
672
	 Object key = _keys.nextElement();
673
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
674
     }
675

    
676
     logMetacat.info("size of partOfDoclist after"
677
                             + " docidsInQueryresultTable(): "
678
                             + partOfDoclist.size());
679

    
680
     //add return fields for the documents in partOfDoclist
681
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
682
                                        dbconn, useXMLIndex );
683
     //add relationship part part docid list for the documents in partOfDocList
684
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
685

    
686

    
687
     Enumeration keys = partOfDoclist.keys();
688
     String key = null;
689
     String element = null;
690
     String query = null;
691
     int offset = (new Integer(MetaCatUtil
692
                               .getOption("queryresult_string_length")))
693
                               .intValue();
694
     while (keys.hasMoreElements())
695
     {
696
         key = (String) keys.nextElement();
697
         element = (String)partOfDoclist.get(key);
698

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

    
708
             PreparedStatement pstmt = null;
709
             pstmt = dbconn.prepareStatement(query);
710
             pstmt.setInt(1, returnfield_id);
711
             pstmt.setString(2, key);
712
             pstmt.setString(3, element);
713

    
714
             dbconn.increaseUsageCount(1);
715
             pstmt.execute();
716
             pstmt.close();
717
         }
718

    
719
         // A string with element
720
         String xmlElement = "  <document>" + element + "</document>";
721

    
722
         //send single element to output
723
         if (out != null)
724
         {
725
             out.println(xmlElement);
726
         }
727
         resultset.append(xmlElement);
728
     }//while
729

    
730

    
731
     keys = queryresultDocList.keys();
732
     while (keys.hasMoreElements())
733
     {
734
         key = (String) keys.nextElement();
735
         element = (String)queryresultDocList.get(key);
736
         // A string with element
737
         String xmlElement = "  <document>" + element + "</document>";
738
         //send single element to output
739
         if (out != null)
740
         {
741
             out.println(xmlElement);
742
         }
743
         resultset.append(xmlElement);
744
     }//while
745

    
746
     return resultset;
747
 }
748

    
749
   /**
750
    * Get the docids already in xml_queryresult table and corresponding
751
    * queryresultstring as a hashtable
752
    */
753
   private Hashtable docidsInQueryresultTable(int returnfield_id,
754
                                              Hashtable partOfDoclist,
755
                                              DBConnection dbconn){
756

    
757
         Hashtable returnValue = new Hashtable();
758
         PreparedStatement pstmt = null;
759
         ResultSet rs = null;
760

    
761
         // get partOfDoclist as string for the query
762
         Enumeration keylist = partOfDoclist.keys();
763
         StringBuffer doclist = new StringBuffer();
764
         while (keylist.hasMoreElements())
765
         {
766
             doclist.append("'");
767
             doclist.append((String) keylist.nextElement());
768
             doclist.append("',");
769
         }//while
770

    
771

    
772
         if (doclist.length() > 0)
773
         {
774
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
775

    
776
             // the query to find out docids from xml_queryresult
777
             String query = "select docid, queryresult_string from "
778
                          + "xml_queryresult where returnfield_id = " +
779
                          returnfield_id +" and docid in ("+ doclist + ")";
780
             logMetacat.info("Query to get docids from xml_queryresult:"
781
                                      + query);
782

    
783
             try {
784
                 // prepare and execute the query
785
                 pstmt = dbconn.prepareStatement(query);
786
                 dbconn.increaseUsageCount(1);
787
                 pstmt.execute();
788
                 rs = pstmt.getResultSet();
789
                 boolean tableHasRows = rs.next();
790
                 while (tableHasRows) {
791
                     // store the returned results in the returnValue hashtable
792
                     String key = rs.getString(1);
793
                     String element = rs.getString(2);
794

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

    
815

    
816
   /**
817
    * Method to get id from xml_returnfield table
818
    * for a given query specification
819
    */
820
   private int returnfield_id;
821
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
822
                                           DBConnection dbconn){
823
       int id = -1;
824
       int count = 1;
825
       PreparedStatement pstmt = null;
826
       ResultSet rs = null;
827
       String returnfield = qspec.getSortedReturnFieldString();
828

    
829
       // query for finding the id from xml_returnfield
830
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
831
            + "WHERE returnfield_string LIKE ?";
832
       logMetacat.info("ReturnField Query:" + query);
833

    
834
       try {
835
           // prepare and run the query
836
           pstmt = dbconn.prepareStatement(query);
837
           pstmt.setString(1,returnfield);
838
           dbconn.increaseUsageCount(1);
839
           pstmt.execute();
840
           rs = pstmt.getResultSet();
841
           boolean tableHasRows = rs.next();
842

    
843
           // if record found then increase the usage count
844
           // else insert a new record and get the id of the new record
845
           if(tableHasRows){
846
               // get the id
847
               id = rs.getInt(1);
848
               count = rs.getInt(2) + 1;
849
               rs.close();
850
               pstmt.close();
851

    
852
               // increase the usage count
853
               query = "UPDATE xml_returnfield SET usage_count ='" + count
854
                   + "' WHERE returnfield_id ='"+ id +"'";
855
               logMetacat.info("ReturnField Table Update:"+ query);
856

    
857
               pstmt = dbconn.prepareStatement(query);
858
               dbconn.increaseUsageCount(1);
859
               pstmt.execute();
860
               pstmt.close();
861

    
862
           } else {
863
               rs.close();
864
               pstmt.close();
865

    
866
               // insert a new record
867
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
868
                   + "VALUES (?, '1')";
869
               logMetacat.info("ReturnField Table Insert:"+ query);
870
               pstmt = dbconn.prepareStatement(query);
871
               pstmt.setString(1, returnfield);
872
               dbconn.increaseUsageCount(1);
873
               pstmt.execute();
874
               pstmt.close();
875

    
876
               // get the id of the new record
877
               query = "SELECT returnfield_id FROM xml_returnfield "
878
                   + "WHERE returnfield_string LIKE ?";
879
               logMetacat.info("ReturnField query after Insert:" + query);
880
               pstmt = dbconn.prepareStatement(query);
881
               pstmt.setString(1, returnfield);
882

    
883
               dbconn.increaseUsageCount(1);
884
               pstmt.execute();
885
               rs = pstmt.getResultSet();
886
               if(rs.next()){
887
                   id = rs.getInt(1);
888
               } else {
889
                   id = -1;
890
               }
891
               rs.close();
892
               pstmt.close();
893
           }
894

    
895
       } catch (Exception e){
896
           logMetacat.error("Error getting id from xml_returnfield in "
897
                                     + "DBQuery.getXmlReturnfieldsTableId: "
898
                                     + e.getMessage());
899
           id = -1;
900
       }
901

    
902
       returnfield_id = id;
903
       return count;
904
   }
905

    
906

    
907
    /*
908
     * A method to add return field to return doclist hash table
909
     */
910
    private Hashtable addReturnfield(Hashtable docListResult,
911
                                      QuerySpecification qspec,
912
                                      String user, String[]groups,
913
                                      DBConnection dbconn, boolean useXMLIndex )
914
                                      throws Exception
915
    {
916
      PreparedStatement pstmt = null;
917
      ResultSet rs = null;
918
      String docid = null;
919
      String fieldname = null;
920
      String fielddata = null;
921
      String relation = null;
922

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

    
961
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
962
           logMetacat.info( "Time for execute access extended query: "
963
                          + (extendedAccessQueryEnd - extendedQueryStart));
964

    
965
           String extendedQuery =
966
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
967
           logMetacat.warn("Extended query: " + extendedQuery);
968

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

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

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

    
1055
           // get attribures return
1056
           docListResult = getAttributeValueForReturn(qspec,
1057
                           docListResult, doclist.toString(), useXMLIndex);
1058
       }//if doclist lenght is great than zero
1059

    
1060
     }//if has extended query
1061

    
1062
      return docListResult;
1063
    }//addReturnfield
1064

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

    
1097
        document = new StringBuffer();
1098
        document.append("<triple>");
1099
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1100
        document.append("</subject>");
1101
        if (subDT != null)
1102
        {
1103
          document.append("<subjectdoctype>").append(subDT);
1104
          document.append("</subjectdoctype>");
1105
        }
1106
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1107
        document.append("</relationship>");
1108
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1109
        document.append("</object>");
1110
        if (objDT != null)
1111
        {
1112
          document.append("<objectdoctype>").append(objDT);
1113
          document.append("</objectdoctype>");
1114
        }
1115
        document.append("</triple>");
1116

    
1117
        String removedelement = (String) docListResult.remove(docidkey);
1118
        docListResult.put(docidkey, removedelement+ document.toString());
1119
        tableHasRows = rs.next();
1120
      }//while
1121
      rs.close();
1122
      pstmt.close();
1123
    }//while
1124
    double endRelation = System.currentTimeMillis() / 1000;
1125
    logMetacat.info("Time for adding relation to docListResult: "
1126
                             + (endRelation - startRelation));
1127

    
1128
    return docListResult;
1129
  }//addRelation
1130

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

    
1151

    
1152
    /*
1153
     * A method to search if Vector contains a particular key string
1154
     */
1155
    private boolean containsKey(Vector parentidList, String parentId)
1156
    {
1157

    
1158
        Vector tempVector = null;
1159

    
1160
        for (int count = 0; count < parentidList.size(); count++) {
1161
            tempVector = (Vector) parentidList.get(count);
1162
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1163
        }
1164
        return false;
1165
    }
1166

    
1167
    /*
1168
     * A method to put key and value in Vector
1169
     */
1170
    private void putInArray(Vector parentidList, String key,
1171
            ReturnFieldValue value)
1172
    {
1173

    
1174
        Vector tempVector = null;
1175

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

    
1179
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1180
                tempVector.remove(1);
1181
                tempVector.add(1, value);
1182
                return;
1183
            }
1184
        }
1185

    
1186
        tempVector = new Vector();
1187
        tempVector.add(0, key);
1188
        tempVector.add(1, value);
1189
        parentidList.add(tempVector);
1190
        return;
1191
    }
1192

    
1193
    /*
1194
     * A method to get value in Vector given a key
1195
     */
1196
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1197
    {
1198

    
1199
        Vector tempVector = null;
1200

    
1201
        for (int count = 0; count < parentidList.size(); count++) {
1202
            tempVector = (Vector) parentidList.get(count);
1203

    
1204
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1205
                    .get(1); }
1206
        }
1207
        return null;
1208
    }
1209

    
1210
    /*
1211
     * A method to get enumeration of all values in Vector
1212
     */
1213
    private Vector getElements(Vector parentidList)
1214
    {
1215
        Vector enumVector = new Vector();
1216
        Vector tempVector = null;
1217

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

    
1221
            enumVector.add(tempVector.get(1));
1222
        }
1223
        return enumVector;
1224
    }
1225

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

    
1241
        //check the parameter
1242
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1243

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

    
1262
                    XML.append("<param name=\"");
1263
                    XML.append(fieldname);
1264
                    XML.append("/");
1265
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1266
                    XML.append(attirbuteName);
1267
                    XML.append("\">");
1268
                    XML.append(fielddata);
1269
                    XML.append("</param>");
1270
                    tableHasRows = rs.next();
1271

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

    
1303
    }
1304

    
1305
    /*
1306
     * A method to create a query to get owner's docid list
1307
     */
1308
    private String getOwnerQuery(String owner)
1309
    {
1310
        if (owner != null) {
1311
            owner = owner.toLowerCase();
1312
        }
1313
        StringBuffer self = new StringBuffer();
1314

    
1315
        self.append("SELECT docid,docname,doctype,");
1316
        self.append("date_created, date_updated, rev ");
1317
        self.append("FROM xml_documents WHERE docid IN (");
1318
        self.append("(");
1319
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1320
        self.append("nodedata LIKE '%%%' ");
1321
        self.append(") \n");
1322
        self.append(") ");
1323
        self.append(" AND (");
1324
        self.append(" lower(user_owner) = '" + owner + "'");
1325
        self.append(") ");
1326
        return self.toString();
1327
    }
1328

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

    
1351

    
1352

    
1353
        if (params.containsKey("meta_file_id")) {
1354
            query.append("<meta_file_id>");
1355
            query.append(((String[]) params.get("meta_file_id"))[0]);
1356
            query.append("</meta_file_id>");
1357
        }
1358

    
1359
        if (params.containsKey("returndoctype")) {
1360
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1361
            for (int i = 0; i < returnDoctypes.length; i++) {
1362
                String doctype = (String) returnDoctypes[i];
1363

    
1364
                if (!doctype.equals("any") && !doctype.equals("ANY")
1365
                        && !doctype.equals("")) {
1366
                    query.append("<returndoctype>").append(doctype);
1367
                    query.append("</returndoctype>");
1368
                }
1369
            }
1370
        }
1371

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

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

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

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

    
1404
        //allows the dynamic switching of boolean operators
1405
        if (params.containsKey("operator")) {
1406
            query.append("<querygroup operator=\""
1407
                    + ((String[]) params.get("operator"))[0] + "\">");
1408
        } else { //the default operator is UNION
1409
            query.append("<querygroup operator=\"UNION\">");
1410
        }
1411

    
1412
        if (params.containsKey("casesensitive")) {
1413
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1414
        } else {
1415
            casesensitive = "false";
1416
        }
1417

    
1418
        if (params.containsKey("searchmode")) {
1419
            searchmode = ((String[]) params.get("searchmode"))[0];
1420
        } else {
1421
            searchmode = "contains";
1422
        }
1423

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

    
1441
        //this while loop finds the rest of the parameters
1442
        //and attempts to query for the field specified
1443
        //by the parameter.
1444
        elements = params.elements();
1445
        keys = params.keys();
1446
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1447
            nextkey = keys.nextElement();
1448
            nextelement = elements.nextElement();
1449

    
1450
            //make sure we aren't querying for any of these
1451
            //parameters since the are already in the query
1452
            //in one form or another.
1453
            Vector ignoredParams = new Vector();
1454
            ignoredParams.add("returndoctype");
1455
            ignoredParams.add("filterdoctype");
1456
            ignoredParams.add("action");
1457
            ignoredParams.add("qformat");
1458
            ignoredParams.add("anyfield");
1459
            ignoredParams.add("returnfield");
1460
            ignoredParams.add("owner");
1461
            ignoredParams.add("site");
1462
            ignoredParams.add("operator");
1463
            ignoredParams.add("sessionid");
1464

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

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

    
1509
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1510
            xmlquery.append("<returndoctype>");
1511
            xmlquery.append(doctype).append("</returndoctype>");
1512
        }
1513

    
1514
        xmlquery.append("<querygroup operator=\"UNION\">");
1515
        //chad added - 8/14
1516
        //the if statement allows a query to gracefully handle a null
1517
        //query. Without this if a nullpointerException is thrown.
1518
        if (!value.equals("")) {
1519
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1520
            xmlquery.append("searchmode=\"contains\">");
1521
            xmlquery.append("<value>").append(value).append("</value>");
1522
            xmlquery.append("</queryterm>");
1523
        }
1524
        xmlquery.append("</querygroup>");
1525
        xmlquery.append("</pathquery>");
1526

    
1527
        return (xmlquery.toString());
1528
    }
1529

    
1530
    /**
1531
     * format a simple free-text value query as an XML document that conforms
1532
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1533
     * structured query engine
1534
     *
1535
     * @param value the text string to search for in the xml catalog
1536
     */
1537
    public static String createQuery(String value)
1538
    {
1539
        return createQuery(value, "any");
1540
    }
1541

    
1542
    /**
1543
     * Check for "READ" permission on @docid for @user and/or @group from DB
1544
     * connection
1545
     */
1546
    private boolean hasPermission(String user, String[] groups, String docid)
1547
            throws SQLException, Exception
1548
    {
1549
        // Check for READ permission on @docid for @user and/or @groups
1550
        PermissionController controller = new PermissionController(docid);
1551
        return controller.hasPermission(user, groups,
1552
                AccessControlInterface.READSTRING);
1553
    }
1554

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

    
1570
        // Check the parameter
1571
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1572

    
1573
        //the query stirng
1574
        String query = "SELECT subject, object from xml_relation where docId = ?";
1575
        try {
1576
            dbConn = DBConnectionPool
1577
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1578
            serialNumber = dbConn.getCheckOutSerialNumber();
1579
            pStmt = dbConn.prepareStatement(query);
1580
            //bind the value to query
1581
            pStmt.setString(1, dataPackageDocid);
1582

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

    
1598
                //don't put the duplicate docId into the vector
1599
                if (!docIdList.contains(docIdInSubjectField)) {
1600
                    docIdList.add(docIdInSubjectField);
1601
                }
1602

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

    
1631
    /**
1632
     * Get all docIds list for a data packadge
1633
     *
1634
     * @param dataPackageDocid, the string in docId field of xml_relation table
1635
     */
1636
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1637
    {
1638

    
1639
        Vector docIdList = new Vector();//return value
1640
        Vector tripleList = null;
1641
        String xml = null;
1642

    
1643
        // Check the parameter
1644
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1645

    
1646
        try {
1647
            //initial a documentImpl object
1648
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1649
            //transfer to documentImpl object to string
1650
            xml = packageDocument.toString();
1651

    
1652
            //create a tripcollection object
1653
            TripleCollection tripleForPackage = new TripleCollection(
1654
                    new StringReader(xml));
1655
            //get the vetor of triples
1656
            tripleList = tripleForPackage.getCollection();
1657

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

    
1677
        // return result
1678
        return docIdList;
1679
    }//getDocidListForPackageInXMLRevisions()
1680

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

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

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

    
1782
        }//try
1783
        catch (SQLException e) {
1784
            logMetacat.error(
1785
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1786
                            + e.getMessage());
1787
            throw e;
1788
        }//catch
1789
        finally {
1790
            try {
1791
                pStmt.close();
1792
            }//try
1793
            catch (SQLException ee) {
1794
                logMetacat.error(
1795
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1796
                                + ee.getMessage());
1797
            }//catch
1798
            finally {
1799
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1800
            }//finally
1801
        }//finally
1802
        return rev;
1803
    }//getCurrentRevFromXMLDoumentsTable
1804

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

    
1821
        byteString = docImpl.toString().getBytes();
1822
        //use docId as the zip entry's name
1823
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1824
                + docImpl.getDocID());
1825
        zEntry.setSize(byteString.length);
1826
        zipOut.putNextEntry(zEntry);
1827
        zipOut.write(byteString, 0, byteString.length);
1828
        zipOut.closeEntry();
1829

    
1830
    }//addDocToZipOutputStream()
1831

    
1832
    /**
1833
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1834
     * only inlcudes current version. If a DocumentImple object couldn't find
1835
     * for a docid, then the String of this docid was added to vetor rather
1836
     * than DocumentImple object.
1837
     *
1838
     * @param docIdList, a vetor hold a docid list for a data package. In
1839
     *            docid, there is not version number in it.
1840
     */
1841

    
1842
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1843
            throws McdbException, Exception
1844
    {
1845
        //Connection dbConn=null;
1846
        Vector documentImplList = new Vector();
1847
        int rev = 0;
1848

    
1849
        // Check the parameter
1850
        if (docIdList.isEmpty()) { return documentImplList; }//if
1851

    
1852
        //for every docid in vector
1853
        for (int i = 0; i < docIdList.size(); i++) {
1854
            try {
1855
                //get newest version for this docId
1856
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1857
                        .elementAt(i));
1858

    
1859
                // There is no record for this docId in xml_documents table
1860
                if (rev == -5) {
1861
                    // Rather than put DocumentImple object, put a String
1862
                    // Object(docid)
1863
                    // into the documentImplList
1864
                    documentImplList.add((String) docIdList.elementAt(i));
1865
                    // Skip other code
1866
                    continue;
1867
                }
1868

    
1869
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1870
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1871

    
1872
                //create new documentImpl object
1873
                DocumentImpl documentImplObject = new DocumentImpl(
1874
                        docidPlusVersion);
1875
                //add them to vector
1876
                documentImplList.add(documentImplObject);
1877
            }//try
1878
            catch (Exception e) {
1879
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
1880
                        + e.getMessage());
1881
                // continue the for loop
1882
                continue;
1883
            }
1884
        }//for
1885
        return documentImplList;
1886
    }
1887

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

    
1904
        // Check the parameter
1905
        if (docIdList.isEmpty()) { return documentImplList; }//if
1906

    
1907
        //for every docid in vector
1908
        for (int i = 0; i < docIdList.size(); i++) {
1909

    
1910
            String docidPlusVersion = (String) (docIdList.elementAt(i));
1911

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

    
1938
        }//for
1939
        return documentImplList;
1940
    }//getOldVersionAllDocumentImple
1941

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

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

    
1998
        //create a DBTransform ojbect
1999
        xmlToHtml = new DBTransform();
2000
        //head of html
2001
        htmlDoc.append("<html><head></head><body>");
2002
        for (int i = 0; i < docImplList.size(); i++) {
2003
            // If this String object, this means it is missed data file
2004
            if ((((docImplList.elementAt(i)).getClass()).toString())
2005
                    .equals("class java.lang.String")) {
2006

    
2007
                htmlDoc.append("<a href=\"");
2008
                String dataFileid = (String) docImplList.elementAt(i);
2009
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2010
                htmlDoc.append("Data File: ");
2011
                htmlDoc.append(dataFileid).append("</a><br>");
2012
                htmlDoc.append("<br><hr><br>");
2013

    
2014
            }//if
2015
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2016
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2017
                                              // transform it.
2018
                //transform each file individually then concatenate all of the
2019
                //transformations together.
2020

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

    
2055
    }//addHtmlSummaryToZipOutputStream
2056

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

    
2081
        String docId = null;
2082
        int version = -5;
2083
        // Docid without revision
2084
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2085
        // revision number
2086
        version = MetaCatUtil.getVersionFromString(docIdString);
2087

    
2088
        //check if the reqused docId is a data package id
2089
        if (!isDataPackageId(docId)) {
2090

    
2091
            /*
2092
             * Exception e = new Exception("The request the doc id "
2093
             * +docIdString+ " is not a data package id");
2094
             */
2095

    
2096
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2097
            // zip
2098
            //up the single document and return the zip file.
2099
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2100

    
2101
                Exception e = new Exception("User " + user
2102
                        + " does not have permission"
2103
                        + " to export the data package " + docIdString);
2104
                throw e;
2105
            }
2106

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

    
2124
            zOut.finish(); //terminate the zip file
2125
            return zOut;
2126
        }
2127
        // Check the permission of user
2128
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2129

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

    
2155
            }//if
2156
            else if (version > currentVersion || version < -1) {
2157
                throw new Exception("The user specified docid: " + docId + "."
2158
                        + version + " doesn't exist");
2159
            }//else if
2160
            else //for an old version
2161
            {
2162

    
2163
                rootName = docIdString
2164
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2165
                //get the whole id list for data packadge
2166
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2167

    
2168
                //get the whole documentImple object
2169
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2170
            }//else
2171

    
2172
            // Make sure documentImplist is not empty
2173
            if (documentImplList.isEmpty()) { throw new Exception(
2174
                    "Couldn't find component for data package: " + packageId); }//if
2175

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

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

    
2235
                        }//if
2236
                        else {
2237
                            //it is data file
2238
                            addDataFileToZipOutputStream(docImpls, zOut,
2239
                                    rootName);
2240
                            htmlDocumentImplList.add(docImpls);
2241
                        }//else
2242
                    }//if
2243
                }//else
2244
            }//for
2245

    
2246
            //add html summary file
2247
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2248
                    rootName);
2249
            zOut.finish(); //terminate the zip file
2250
            //dbConn.close();
2251
            return zOut;
2252
        }//else
2253
    }//getZippedPackage()
2254

    
2255
    private class ReturnFieldValue
2256
    {
2257

    
2258
        private String docid = null; //return field value for this docid
2259

    
2260
        private String fieldValue = null;
2261

    
2262
        private String xmlFieldValue = null; //return field value in xml
2263
                                             // format
2264

    
2265
        public void setDocid(String myDocid)
2266
        {
2267
            docid = myDocid;
2268
        }
2269

    
2270
        public String getDocid()
2271
        {
2272
            return docid;
2273
        }
2274

    
2275
        public void setFieldValue(String myValue)
2276
        {
2277
            fieldValue = myValue;
2278
        }
2279

    
2280
        public String getFieldValue()
2281
        {
2282
            return fieldValue;
2283
        }
2284

    
2285
        public void setXMLFieldValue(String xml)
2286
        {
2287
            xmlFieldValue = xml;
2288
        }
2289

    
2290
        public String getXMLFieldValue()
2291
        {
2292
            return xmlFieldValue;
2293
        }
2294

    
2295
    }
2296
}
(21-21/64)