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

    
31
package edu.ucsb.nceas.metacat;
32

    
33
import java.io.BufferedWriter;
34
import java.io.File;
35
import java.io.FileInputStream;
36
import java.io.FileOutputStream;
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.io.OutputStream;
45
import java.sql.PreparedStatement;
46
import java.sql.ResultSet;
47
import java.sql.SQLException;
48
import java.util.Enumeration;
49
import java.util.Hashtable;
50
import java.util.StringTokenizer;
51
import java.util.Vector;
52
import java.util.zip.ZipEntry;
53
import java.util.zip.ZipOutputStream;
54

    
55
import javax.servlet.ServletOutputStream;
56
import javax.servlet.http.HttpServletResponse;
57
import javax.servlet.http.HttpSession;
58

    
59
import org.apache.log4j.Logger;
60

    
61
import org.w3c.dom.*;
62
import javax.xml.parsers.DocumentBuilderFactory;
63
import org.xml.sax.InputSource;
64
import org.w3c.dom.ls.*;
65

    
66
import edu.ucsb.nceas.morpho.datapackage.Triple;
67
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
68

    
69

    
70
/**
71
 * A Class that searches a relational DB for elements and attributes that have
72
 * free text matches a query string, or structured query matches to a path
73
 * specified node in the XML hierarchy. It returns a result set consisting of
74
 * the document ID for each document that satisfies the query
75
 */
76
public class DBQuery
77
{
78

    
79
    static final int ALL = 1;
80

    
81
    static final int WRITE = 2;
82

    
83
    static final int READ = 4;
84

    
85
    //private Connection conn = null;
86
    private String parserName = null;
87

    
88
    private MetaCatUtil util = new MetaCatUtil();
89

    
90
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
91

    
92
    /** true if the metacat spatial option is installed **/
93
    private final boolean METACAT_SPATIAL = true;
94

    
95
    /** useful if you just want to grab a list of docids **/
96
    Vector docidOverride = new Vector();
97

    
98
    /**
99
     * the main routine used to test the DBQuery utility.
100
     * <p>
101
     * Usage: java DBQuery <xmlfile>
102
     *
103
     * @param xmlfile the filename of the xml file containing the query
104
     */
105
    static public void main(String[] args)
106
    {
107

    
108
        if (args.length < 1) {
109
            System.err.println("Wrong number of arguments!!!");
110
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
111
            return;
112
        } else {
113
            try {
114

    
115
                int i = 0;
116
                boolean showRuntime = false;
117
                boolean useXMLIndex = false;
118
                if (args[i].equals("-t")) {
119
                    showRuntime = true;
120
                    i++;
121
                }
122
                if (args[i].equals("-index")) {
123
                    useXMLIndex = true;
124
                    i++;
125
                }
126
                String xmlfile = args[i];
127

    
128
                // Time the request if asked for
129
                double startTime = System.currentTimeMillis();
130

    
131
                // Open a connection to the database
132
                MetaCatUtil util = new MetaCatUtil();
133
                //Connection dbconn = util.openDBConnection();
134

    
135
                double connTime = System.currentTimeMillis();
136

    
137
                // Execute the query
138
                DBQuery queryobj = new DBQuery();
139
                FileReader xml = new FileReader(new File(xmlfile));
140
                Hashtable nodelist = null;
141
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
142

    
143
                // Print the reulting document listing
144
                StringBuffer result = new StringBuffer();
145
                String document = null;
146
                String docid = null;
147
                result.append("<?xml version=\"1.0\"?>\n");
148
                result.append("<resultset>\n");
149

    
150
                if (!showRuntime) {
151
                    Enumeration doclist = nodelist.keys();
152
                    while (doclist.hasMoreElements()) {
153
                        docid = (String) doclist.nextElement();
154
                        document = (String) nodelist.get(docid);
155
                        result.append("  <document>\n    " + document
156
                                + "\n  </document>\n");
157
                    }
158

    
159
                    result.append("</resultset>\n");
160
                }
161
                // Time the request if asked for
162
                double stopTime = System.currentTimeMillis();
163
                double dbOpenTime = (connTime - startTime) / 1000;
164
                double readTime = (stopTime - connTime) / 1000;
165
                double executionTime = (stopTime - startTime) / 1000;
166
                if (showRuntime) {
167
                    System.out.print("  " + executionTime);
168
                    System.out.print("  " + dbOpenTime);
169
                    System.out.print("  " + readTime);
170
                    System.out.print("  " + nodelist.size());
171
                    System.out.println();
172
                }
173
                //System.out.println(result);
174
                //write into a file "result.txt"
175
                if (!showRuntime) {
176
                    File f = new File("./result.txt");
177
                    FileWriter fw = new FileWriter(f);
178
                    BufferedWriter out = new BufferedWriter(fw);
179
                    out.write(result.toString());
180
                    out.flush();
181
                    out.close();
182
                    fw.close();
183
                }
184

    
185
            } catch (Exception e) {
186
                System.err.println("Error in DBQuery.main");
187
                System.err.println(e.getMessage());
188
                e.printStackTrace(System.err);
189
            }
190
        }
191
    }
192

    
193
    /**
194
     * construct an instance of the DBQuery class
195
     *
196
     * <p>
197
     * Generally, one would call the findDocuments() routine after creating an
198
     * instance to specify the search query
199
     * </p>
200
     *
201

    
202
     * @param parserName the fully qualified name of a Java class implementing
203
     *            the org.xml.sax.XMLReader interface
204
     */
205
    public DBQuery()
206
    {
207
        String parserName = MetaCatUtil.getOption("saxparser");
208
        this.parserName = parserName;
209
    }
210

    
211
    /**
212
     * 
213
     * Construct an instance of DBQuery Class
214
     * BUT accept a docid Vector that will supersede
215
     * the query.printSQL() method
216
     *
217
     * If a docid Vector is passed in,
218
     * the docids will be used to create a simple IN query 
219
     * without the multiple subselects of the printSQL() method
220
     *
221
     * Using this constructor, we just check for 
222
     * a docidOverride Vector in the findResultDoclist() method
223
     *
224
     * @param docids List of docids to display in the resultset
225
     */
226
    public DBQuery(Vector docids)
227
    {
228
        this.docidOverride = docids;
229
        String parserName = MetaCatUtil.getOption("saxparser");
230
        this.parserName = parserName;
231
    }
232

    
233
  /**
234
   * Method put the search result set into out printerwriter
235
   * @param resoponse the return response
236
   * @param out the output printer
237
   * @param params the paratermer hashtable
238
   * @param user the user name (it maybe different to the one in param)
239
   * @param groups the group array
240
   * @param sessionid  the sessionid
241
   */
242
  public void findDocuments(HttpServletResponse response,
243
                                       PrintWriter out, Hashtable params,
244
                                       String user, String[] groups,
245
                                       String sessionid)
246
  {
247
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
248
               .booleanValue();
249
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
250

    
251
  }
252

    
253

    
254
    /**
255
     * Method put the search result set into out printerwriter
256
     * @param resoponse the return response
257
     * @param out the output printer
258
     * @param params the paratermer hashtable
259
     * @param user the user name (it maybe different to the one in param)
260
     * @param groups the group array
261
     * @param sessionid  the sessionid
262
     */
263
    public void findDocuments(HttpServletResponse response,
264
                                         PrintWriter out, Hashtable params,
265
                                         String user, String[] groups,
266
                                         String sessionid, boolean useXMLIndex)
267
    {
268
      int pagesize = 0;
269
      int pagestart = 0;
270
      
271
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
272
      {
273
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
274
        String pagestartStr = ((String[])params.get("pagestart"))[0];
275
        if(pagesizeStr != null && pagestartStr != null)
276
        {
277
          pagesize = (new Integer(pagesizeStr)).intValue();
278
          pagestart = (new Integer(pagestartStr)).intValue();
279
        }
280
      }
281
      
282
      // get query and qformat
283
      String xmlquery = ((String[])params.get("query"))[0];
284

    
285
      logMetacat.warn("SESSIONID: " + sessionid);
286
      logMetacat.warn("xmlquery: " + xmlquery);
287
      String qformat = ((String[])params.get("qformat"))[0];
288
      logMetacat.warn("qformat: " + qformat);
289
      // Get the XML query and covert it into a SQL statment
290
      QuerySpecification qspec = null;
291
      if ( xmlquery != null)
292
      {
293
         xmlquery = transformQuery(xmlquery);
294
         try
295
         {
296
           qspec = new QuerySpecification(xmlquery,
297
                                          parserName,
298
                                          MetaCatUtil.getOption("accNumSeparator"));
299
         }
300
         catch (Exception ee)
301
         {
302
           logMetacat.error("error generating QuerySpecification object"
303
                                    +" in DBQuery.findDocuments"
304
                                    + ee.getMessage());
305
         }
306
      }
307

    
308

    
309

    
310
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
311
      {
312
        //xml format
313
        response.setContentType("text/xml");
314
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex, 
315
          pagesize, pagestart, sessionid);
316
      }//if
317
      else
318
      {
319
        //knb format, in this case we will get whole result and sent it out
320
        response.setContentType("text/html");
321
        PrintWriter nonout = null;
322
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
323
                                                groups, useXMLIndex, pagesize, 
324
                                                pagestart, sessionid);
325
        
326
        //transfer the xml to html
327
        try
328
        {
329

    
330
         DBTransform trans = new DBTransform();
331
         response.setContentType("text/html");
332

    
333
         // if the user is a moderator, then pass a param to the 
334
         // xsl specifying the fact
335
         if(MetaCatUtil.isModerator(user, groups)){
336
        	 params.put("isModerator", new String[] {"true"});
337
         }
338

    
339
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
340
                                 "-//W3C//HTML//EN", qformat, out, params,
341
                                 sessionid);
342

    
343
        }
344
        catch(Exception e)
345
        {
346
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
347
                                +e.getMessage());
348
         }
349

    
350
      }//else
351

    
352
  }
353
    
354
  /**
355
   * this method parses the xml results in the string buffer and returns
356
   * just those required by the paging params.
357
   */
358
  private StringBuffer getPagedResult(MetacatResultSet mrs, int pagestart, 
359
    int pagesize)
360
  {
361
    //logMetacat.warn(mrs.toString());
362
    if(pagesize == 0)
363
    { //if pagesize is 0 then we return the whole resultset
364
      return new StringBuffer(mrs.toString());
365
    }
366
    
367
    return new StringBuffer(mrs.serializeToXML(pagestart, pagestart + pagesize));
368
  }
369
  
370
  
371
  /**
372
   * Transforms a hashtable of documents to an xml or html result and sent
373
   * the content to outputstream. Keep going untill hastable is empty. stop it.
374
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
375
   * to xmlquery String
376
   * @param xmlquery
377
   * @param qspec
378
   * @param out
379
   * @param user
380
   * @param groups
381
   * @param useXMLIndex
382
   * @param sessionid
383
   * @return
384
   */
385
    public StringBuffer createResultDocument(String xmlquery,
386
                                              QuerySpecification qspec,
387
                                              PrintWriter out,
388
                                              String user, String[] groups,
389
                                              boolean useXMLIndex)
390
    {
391
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"");
392
    }
393

    
394
  /*
395
   * Transforms a hashtable of documents to an xml or html result and sent
396
   * the content to outputstream. Keep going untill hastable is empty. stop it.
397
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
398
   * to xmlquery String
399
   */
400
  public StringBuffer createResultDocument(String xmlquery,
401
                                            QuerySpecification qspec,
402
                                            PrintWriter out,
403
                                            String user, String[] groups,
404
                                            boolean useXMLIndex, int pagesize,
405
                                            int pagestart, String sessionid)
406
  {
407
    DBConnection dbconn = null;
408
    int serialNumber = -1;
409
    StringBuffer resultset = new StringBuffer();
410

    
411
    //try to get the cached version first    
412
    Hashtable sessionHash = MetaCatServlet.getSessionHash();
413
    HttpSession sess = (HttpSession)sessionHash.get(sessionid);
414

    
415
    QuerySpecification cachedQuerySpec = null;
416
    if (sess != null)
417
    {
418
    	cachedQuerySpec = (QuerySpecification)sess.getAttribute("query");
419
    }
420
    
421
    if(cachedQuerySpec != null && 
422
       cachedQuerySpec.printSQL(false).equals(qspec.printSQL(false)))
423
    { //use the cached resultset if the query was the same as the last
424
      MetacatResultSet mrs = (MetacatResultSet)sess.getAttribute("results");
425
      logMetacat.info("Using cached query results.");
426
      //if the query is the same and the session contains the query
427
      //results, return those instead of rerunning the query
428
      if(mrs != null)
429
      { //print and return the cached buffer
430
        StringBuffer pagedResultBuffer = getPagedResult(mrs, pagestart, 
431
          pagesize);
432
        if(out != null)
433
        {
434
          out.println("<?xml version=\"1.0\"?>\n");
435
          out.println("<resultset>\n");
436
          out.println("  <query>" + xmlquery + "</query>\n");
437
          out.println(pagedResultBuffer.toString());
438
          out.println("\n</resultset>\n");
439
        }
440
        String returnString = "<?xml version=\"1.0\"?>\n";
441
        returnString += "<resultset>\n";
442
        returnString += "  <query>" + xmlquery + "</query>\n";
443
        returnString += pagedResultBuffer.toString();
444
        returnString += "\n</resultset>\n";
445
        return new StringBuffer(returnString);
446
      }
447
    }
448
    
449
    //no cached results...go on with a normal query
450
    
451
    resultset.append("<?xml version=\"1.0\"?>\n");
452
    resultset.append("<resultset>\n");
453
    resultset.append("  <query>" + xmlquery + "</query>");
454
    //send out a new query
455
    if (out != null)
456
    {
457
      out.println(resultset.toString());
458
    }
459
    if (qspec != null)
460
    {
461
      try
462
      {
463

    
464
        //checkout the dbconnection
465
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
466
        serialNumber = dbconn.getCheckOutSerialNumber();
467

    
468
        //print out the search result
469
        // search the doc list
470
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
471
                                      dbconn, useXMLIndex, pagesize, pagestart, 
472
                                      sessionid);
473
      } //try
474
      catch (IOException ioe)
475
      {
476
        logMetacat.error("IO error in DBQuery.findDocuments:");
477
        logMetacat.error(ioe.getMessage());
478

    
479
      }
480
      catch (SQLException e)
481
      {
482
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
483
                                 + e.getMessage());
484
      }
485
      catch (Exception ee)
486
      {
487
        logMetacat.error("Exception in DBQuery.findDocuments: "
488
                                 + ee.getMessage());
489
        ee.printStackTrace();
490
      }
491
      finally
492
      {
493
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
494
      } //finally
495
    }//if
496
    String closeRestultset = "</resultset>";
497
    resultset.append(closeRestultset);
498
    if (out != null)
499
    {
500
      out.println(closeRestultset);
501
    }
502

    
503
    try
504
    {
505
      //cache the query result and the query
506
      logMetacat.info("Caching query and resultset");
507
      sess.setAttribute("query", qspec);
508
      MetacatResultSet mrs = new MetacatResultSet(resultset.toString());
509
      sess.setAttribute("results", mrs);
510
      StringBuffer pagedResultBuffer = getPagedResult(mrs, pagestart, pagesize);
511
      String returnString = "<?xml version=\"1.0\"?>\n";
512
      returnString += "<resultset>\n";
513
      returnString += "  <query>" + xmlquery + "</query>\n";
514
      returnString += pagedResultBuffer.toString();
515
      returnString += "\n</resultset>\n";
516
      return new StringBuffer(returnString);
517
    }
518
    catch(Exception e)
519
    {
520
      logMetacat.error("Could not parse resultset: " + e.getMessage());
521
      //e.printStackTrace();
522
    }
523
    
524
    //default to returning the whole resultset
525
    return resultset;
526
  }//createResultDocuments
527

    
528
    /*
529
     * Find the doc list which match the query
530
     */
531
    private StringBuffer findResultDoclist(QuerySpecification qspec,
532
                                      StringBuffer resultsetBuffer,
533
                                      PrintWriter out,
534
                                      String user, String[]groups,
535
                                      DBConnection dbconn, boolean useXMLIndex,
536
                                      int pagesize, int pagestart, String sessionid)
537
                                      throws Exception
538
    {
539
      String query = null;
540
      int count = 0;
541
      int index = 0;
542
      Hashtable docListResult = new Hashtable();
543
      PreparedStatement pstmt = null;
544
      String docid = null;
545
      String docname = null;
546
      String doctype = null;
547
      String createDate = null;
548
      String updateDate = null;
549
      StringBuffer document = null;
550
      int rev = 0;
551
      double startTime = 0;
552
      int offset = 1;
553
      
554
      ResultSet rs = null;
555
        
556
      offset = 1;
557
      // this is a hack for offset
558
      if (out == null)
559
      {
560
        // for html page, we put everything into one page
561
        offset =
562
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
563
      }
564
      else
565
      {
566
          offset =
567
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
568
      }
569

    
570
      /*
571
       * Check the docidOverride Vector
572
       * if defined, we bypass the qspec.printSQL() method
573
       * and contruct a simpler query based on a 
574
       * list of docids rather than a bunch of subselects
575
       */
576
      if ( this.docidOverride.size() == 0 ) {
577
          query = qspec.printSQL(useXMLIndex);
578
      } else {
579
          logMetacat.info("*** docid override " + this.docidOverride.size());
580
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
581
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
582
          for (int i = 0; i < docidOverride.size(); i++) {  
583
              queryBuffer.append("'");
584
              queryBuffer.append( (String)docidOverride.elementAt(i) );
585
              queryBuffer.append("',");
586
          }
587
          // empty string hack 
588
          queryBuffer.append( "'') " );
589
          query = queryBuffer.toString();
590
      } 
591

    
592
      String ownerQuery = getOwnerQuery(user);
593
      logMetacat.info("\n\n\n query: " + query);
594
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
595
      // if query is not the owner query, we need to check the permission
596
      // otherwise we don't need (owner has all permission by default)
597
      if (!query.equals(ownerQuery))
598
      {
599
        // set user name and group
600
        qspec.setUserName(user);
601
        qspec.setGroup(groups);
602
        // Get access query
603
        String accessQuery = qspec.getAccessQuery();
604
        if(!query.endsWith("WHERE")){
605
            query = query + accessQuery;
606
        } else {
607
            query = query + accessQuery.substring(4, accessQuery.length());
608
        }
609
        logMetacat.warn("\n\n\n final query: " + query);
610
      }
611

    
612
      startTime = System.currentTimeMillis() / 1000;
613
      pstmt = dbconn.prepareStatement(query);
614
      rs = pstmt.executeQuery();
615
      //now we need to process the resultset based on pagesize and pagestart
616
      //if they are not 0
617
      double queryExecuteTime = System.currentTimeMillis() / 1000;
618
      logMetacat.warn("Time to execute query: "
619
                    + (queryExecuteTime - startTime));
620
      boolean tableHasRows = rs.next();
621
      while (tableHasRows)
622
      {
623
        docid = rs.getString(1).trim();
624
        docname = rs.getString(2);
625
        doctype = rs.getString(3);
626
        createDate = rs.getString(4);
627
        updateDate = rs.getString(5);
628
        rev = rs.getInt(6);
629

    
630
        // if there are returndocs to match, backtracking can be performed
631
        // otherwise, just return the document that was hit
632
        Vector returndocVec = qspec.getReturnDocList();
633
         if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
634
                        && !qspec.isPercentageSearch())
635
         {
636
           logMetacat.warn("Back tracing now...");
637
           String sep = MetaCatUtil.getOption("accNumSeparator");
638
           StringBuffer btBuf = new StringBuffer();
639
           btBuf.append("select docid from xml_relation where ");
640

    
641
           //build the doctype list for the backtracking sql statement
642
           btBuf.append("packagetype in (");
643
           for (int i = 0; i < returndocVec.size(); i++)
644
           {
645
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
646
             if (i != (returndocVec.size() - 1))
647
             {
648
                btBuf.append(", ");
649
              }
650
            }
651
            btBuf.append(") ");
652
            btBuf.append("and (subject like '");
653
            btBuf.append(docid).append("'");
654
            btBuf.append("or object like '");
655
            btBuf.append(docid).append("')");
656

    
657
            PreparedStatement npstmt = dbconn.prepareStatement(btBuf.toString());
658
            //should incease usage count
659
            dbconn.increaseUsageCount(1);
660
            npstmt.execute();
661
            ResultSet btrs = npstmt.getResultSet();
662
            boolean hasBtRows = btrs.next();
663
            while (hasBtRows)
664
            {
665
               //there was a backtrackable document found
666
               DocumentImpl xmldoc = null;
667
               String packageDocid = btrs.getString(1);
668
               logMetacat.info("Getting document for docid: "
669
                                         + packageDocid);
670
                try
671
                {
672
                    //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not
673
                    // needed here
674
                    // xmldoc = new DocumentImpl(dbconn, packageDocid);
675
                    //  thus use the following to get the doc info only
676
                    //  xmldoc = new DocumentImpl(dbconn);
677
                    String accNumber = packageDocid + MetaCatUtil.getOption("accNumSeparator") +
678
                    DBUtil.getLatestRevisionInDocumentTable(packageDocid);
679
                    xmldoc = new DocumentImpl(accNumber, false);
680
                    if (xmldoc == null)
681
                    {
682
                       logMetacat.info("Document was null for: "
683
                                                + packageDocid);
684
                    }
685
                }
686
                catch (Exception e)
687
                {
688
                    System.out.println("Error getting document in "
689
                                       + "DBQuery.findDocuments: "
690
                                       + e.getMessage());
691
                }
692

    
693
                String docid_org = xmldoc.getDocID();
694
                if (docid_org == null)
695
                {
696
                   logMetacat.info("Docid_org was null.");
697
                   //continue;
698
                }
699
                docid = docid_org.trim();
700
                docname = xmldoc.getDocname();
701
                doctype = xmldoc.getDoctype();
702
                createDate = xmldoc.getCreateDate();
703
                updateDate = xmldoc.getUpdateDate();
704
                rev = xmldoc.getRev();
705
                document = new StringBuffer();
706

    
707
                String completeDocid = docid
708
                                + MetaCatUtil.getOption("accNumSeparator");
709
                completeDocid += rev;
710
                document.append("<docid>").append(completeDocid);
711
                document.append("</docid>");
712
                if (docname != null)
713
                {
714
                  document.append("<docname>" + docname + "</docname>");
715
                }
716
                if (doctype != null)
717
                {
718
                  document.append("<doctype>" + doctype + "</doctype>");
719
                }
720
                if (createDate != null)
721
                {
722
                 document.append("<createdate>" + createDate + "</createdate>");
723
                }
724
                if (updateDate != null)
725
                {
726
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
727
                }
728
                // Store the document id and the root node id
729
                docListResult.put(docid, (String) document.toString());
730
                count++;
731

    
732

    
733
                // Get the next package document linked to our hit
734
                hasBtRows = btrs.next();
735
              }//while
736
              npstmt.close();
737
              btrs.close();
738
        }
739
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
740
        {
741

    
742
           document = new StringBuffer();
743

    
744
           String completeDocid = docid
745
                            + MetaCatUtil.getOption("accNumSeparator");
746
           completeDocid += rev;
747
           document.append("<docid>").append(completeDocid).append("</docid>");
748
           if (docname != null)
749
           {
750
               document.append("<docname>" + docname + "</docname>");
751
           }
752
           if (doctype != null)
753
           {
754
              document.append("<doctype>" + doctype + "</doctype>");
755
           }
756
           if (createDate != null)
757
           {
758
               document.append("<createdate>" + createDate + "</createdate>");
759
           }
760
           if (updateDate != null)
761
           {
762
             document.append("<updatedate>" + updateDate + "</updatedate>");
763
           }
764
           // Store the document id and the root node id
765
           docListResult.put(docid, (String) document.toString());
766
           count++;
767

    
768
        }//else
769
        // when doclist reached the offset number, send out doc list and empty
770
        // the hash table
771
        if (count == offset)
772
        {
773
          //reset count
774
          count = 0;
775
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
776
                              user, groups,dbconn, useXMLIndex);
777
          // reset docListResult
778
          docListResult = new Hashtable();
779

    
780
        }
781
       // Advance to the next record in the cursor
782
       tableHasRows = rs.next();
783
     }//while
784
     rs.close();
785
     pstmt.close();
786
     //if docListResult is not empty, it need to be sent.
787
     if (!docListResult.isEmpty())
788
     {
789
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
790
                              user, groups,dbconn, useXMLIndex);
791
     }
792
     double docListTime = System.currentTimeMillis() / 1000;
793
     logMetacat.warn("prepare docid list time: "
794
                    + (docListTime - queryExecuteTime));
795

    
796
     return resultsetBuffer;
797
    }//findReturnDoclist
798

    
799

    
800
    /*
801
     * Send completed search hashtable(part of reulst)to output stream
802
     * and buffer into a buffer stream
803
     */
804
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
805
                                           StringBuffer resultset,
806
                                           PrintWriter out, Hashtable partOfDoclist,
807
                                           String user, String[]groups,
808
                                       DBConnection dbconn, boolean useXMLIndex)
809
                                       throws Exception
810
   {
811

    
812
     // check if there is a record in xml_returnfield
813
     // and get the returnfield_id and usage count
814
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
815
     boolean enterRecords = false;
816

    
817
     // get value of xml_returnfield_count
818
     int count = (new Integer(MetaCatUtil
819
                            .getOption("xml_returnfield_count")))
820
                            .intValue();
821

    
822
     // set enterRecords to true if usage_count is more than the offset
823
     // specified in metacat.properties
824
     if(usage_count > count){
825
         enterRecords = true;
826
     }
827

    
828
     if(returnfield_id < 0){
829
         logMetacat.warn("Error in getting returnfield id from"
830
                                  + "xml_returnfield table");
831
	enterRecords = false;
832
     }
833

    
834
     // get the hashtable containing the docids that already in the
835
     // xml_queryresult table
836
     logMetacat.info("size of partOfDoclist before"
837
                             + " docidsInQueryresultTable(): "
838
                             + partOfDoclist.size());
839
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
840
                                                        partOfDoclist, dbconn);
841

    
842
     // remove the keys in queryresultDocList from partOfDoclist
843
     Enumeration _keys = queryresultDocList.keys();
844
     while (_keys.hasMoreElements()){
845
         partOfDoclist.remove(_keys.nextElement());
846
     }
847

    
848
     // backup the keys-elements in partOfDoclist to check later
849
     // if the doc entry is indexed yet
850
     Hashtable partOfDoclistBackup = new Hashtable();
851
     _keys = partOfDoclist.keys();
852
     while (_keys.hasMoreElements()){
853
	 Object key = _keys.nextElement();
854
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
855
     }
856

    
857
     logMetacat.info("size of partOfDoclist after"
858
                             + " docidsInQueryresultTable(): "
859
                             + partOfDoclist.size());
860

    
861
     //add return fields for the documents in partOfDoclist
862
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
863
                                        dbconn, useXMLIndex );
864
     //add relationship part part docid list for the documents in partOfDocList
865
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
866

    
867

    
868
     Enumeration keys = partOfDoclist.keys();
869
     String key = null;
870
     String element = null;
871
     String query = null;
872
     int offset = (new Integer(MetaCatUtil
873
                               .getOption("queryresult_string_length")))
874
                               .intValue();
875
     while (keys.hasMoreElements())
876
     {
877
         key = (String) keys.nextElement();
878
         element = (String)partOfDoclist.get(key);
879

    
880
	 // check if the enterRecords is true, elements is not null, element's
881
         // length is less than the limit of table column and if the document
882
         // has been indexed already
883
         if(enterRecords && element != null
884
		&& element.length() < offset
885
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
886
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
887
                 + "queryresult_string) VALUES (?, ?, ?)";
888

    
889
             PreparedStatement pstmt = null;
890
             pstmt = dbconn.prepareStatement(query);
891
             pstmt.setInt(1, returnfield_id);
892
             pstmt.setString(2, key);
893
             pstmt.setString(3, element);
894

    
895
             dbconn.increaseUsageCount(1);
896
             pstmt.execute();
897
             pstmt.close();
898
         }
899

    
900
         // A string with element
901
         String xmlElement = "  <document>" + element + "</document>";
902

    
903
         //send single element to output
904
         if (out != null)
905
         {
906
             out.println(xmlElement);
907
         }
908
         resultset.append(xmlElement);
909
     }//while
910

    
911

    
912
     keys = queryresultDocList.keys();
913
     while (keys.hasMoreElements())
914
     {
915
         key = (String) keys.nextElement();
916
         element = (String)queryresultDocList.get(key);
917
         // A string with element
918
         String xmlElement = "  <document>" + element + "</document>";
919
         //send single element to output
920
         if (out != null)
921
         {
922
             out.println(xmlElement);
923
         }
924
         resultset.append(xmlElement);
925
     }//while
926

    
927
     return resultset;
928
 }
929

    
930
   /**
931
    * Get the docids already in xml_queryresult table and corresponding
932
    * queryresultstring as a hashtable
933
    */
934
   private Hashtable docidsInQueryresultTable(int returnfield_id,
935
                                              Hashtable partOfDoclist,
936
                                              DBConnection dbconn){
937

    
938
         Hashtable returnValue = new Hashtable();
939
         PreparedStatement pstmt = null;
940
         ResultSet rs = null;
941

    
942
         // get partOfDoclist as string for the query
943
         Enumeration keylist = partOfDoclist.keys();
944
         StringBuffer doclist = new StringBuffer();
945
         while (keylist.hasMoreElements())
946
         {
947
             doclist.append("'");
948
             doclist.append((String) keylist.nextElement());
949
             doclist.append("',");
950
         }//while
951

    
952

    
953
         if (doclist.length() > 0)
954
         {
955
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
956

    
957
             // the query to find out docids from xml_queryresult
958
             String query = "select docid, queryresult_string from "
959
                          + "xml_queryresult where returnfield_id = " +
960
                          returnfield_id +" and docid in ("+ doclist + ")";
961
             logMetacat.info("Query to get docids from xml_queryresult:"
962
                                      + query);
963

    
964
             try {
965
                 // prepare and execute the query
966
                 pstmt = dbconn.prepareStatement(query);
967
                 dbconn.increaseUsageCount(1);
968
                 pstmt.execute();
969
                 rs = pstmt.getResultSet();
970
                 boolean tableHasRows = rs.next();
971
                 while (tableHasRows) {
972
                     // store the returned results in the returnValue hashtable
973
                     String key = rs.getString(1);
974
                     String element = rs.getString(2);
975

    
976
                     if(element != null){
977
                         returnValue.put(key, element);
978
                     } else {
979
                         logMetacat.info("Null elment found ("
980
                         + "DBQuery.docidsInQueryresultTable)");
981
                     }
982
                     tableHasRows = rs.next();
983
                 }
984
                 rs.close();
985
                 pstmt.close();
986
             } catch (Exception e){
987
                 logMetacat.error("Error getting docids from "
988
                                          + "queryresult in "
989
                                          + "DBQuery.docidsInQueryresultTable: "
990
                                          + e.getMessage());
991
              }
992
         }
993
         return returnValue;
994
     }
995

    
996

    
997
   /**
998
    * Method to get id from xml_returnfield table
999
    * for a given query specification
1000
    */
1001
   private int returnfield_id;
1002
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1003
                                           DBConnection dbconn){
1004
       int id = -1;
1005
       int count = 1;
1006
       PreparedStatement pstmt = null;
1007
       ResultSet rs = null;
1008
       String returnfield = qspec.getSortedReturnFieldString();
1009

    
1010
       // query for finding the id from xml_returnfield
1011
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1012
            + "WHERE returnfield_string LIKE ?";
1013
       logMetacat.info("ReturnField Query:" + query);
1014

    
1015
       try {
1016
           // prepare and run the query
1017
           pstmt = dbconn.prepareStatement(query);
1018
           pstmt.setString(1,returnfield);
1019
           dbconn.increaseUsageCount(1);
1020
           pstmt.execute();
1021
           rs = pstmt.getResultSet();
1022
           boolean tableHasRows = rs.next();
1023

    
1024
           // if record found then increase the usage count
1025
           // else insert a new record and get the id of the new record
1026
           if(tableHasRows){
1027
               // get the id
1028
               id = rs.getInt(1);
1029
               count = rs.getInt(2) + 1;
1030
               rs.close();
1031
               pstmt.close();
1032

    
1033
               // increase the usage count
1034
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1035
                   + "' WHERE returnfield_id ='"+ id +"'";
1036
               logMetacat.info("ReturnField Table Update:"+ query);
1037

    
1038
               pstmt = dbconn.prepareStatement(query);
1039
               dbconn.increaseUsageCount(1);
1040
               pstmt.execute();
1041
               pstmt.close();
1042

    
1043
           } else {
1044
               rs.close();
1045
               pstmt.close();
1046

    
1047
               // insert a new record
1048
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1049
                   + "VALUES (?, '1')";
1050
               logMetacat.info("ReturnField Table Insert:"+ query);
1051
               pstmt = dbconn.prepareStatement(query);
1052
               pstmt.setString(1, returnfield);
1053
               dbconn.increaseUsageCount(1);
1054
               pstmt.execute();
1055
               pstmt.close();
1056

    
1057
               // get the id of the new record
1058
               query = "SELECT returnfield_id FROM xml_returnfield "
1059
                   + "WHERE returnfield_string LIKE ?";
1060
               logMetacat.info("ReturnField query after Insert:" + query);
1061
               pstmt = dbconn.prepareStatement(query);
1062
               pstmt.setString(1, returnfield);
1063

    
1064
               dbconn.increaseUsageCount(1);
1065
               pstmt.execute();
1066
               rs = pstmt.getResultSet();
1067
               if(rs.next()){
1068
                   id = rs.getInt(1);
1069
               } else {
1070
                   id = -1;
1071
               }
1072
               rs.close();
1073
               pstmt.close();
1074
           }
1075

    
1076
       } catch (Exception e){
1077
           logMetacat.error("Error getting id from xml_returnfield in "
1078
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1079
                                     + e.getMessage());
1080
           id = -1;
1081
       }
1082

    
1083
       returnfield_id = id;
1084
       return count;
1085
   }
1086

    
1087

    
1088
    /*
1089
     * A method to add return field to return doclist hash table
1090
     */
1091
    private Hashtable addReturnfield(Hashtable docListResult,
1092
                                      QuerySpecification qspec,
1093
                                      String user, String[]groups,
1094
                                      DBConnection dbconn, boolean useXMLIndex )
1095
                                      throws Exception
1096
    {
1097
      PreparedStatement pstmt = null;
1098
      ResultSet rs = null;
1099
      String docid = null;
1100
      String fieldname = null;
1101
      String fielddata = null;
1102
      String relation = null;
1103

    
1104
      if (qspec.containsExtendedSQL())
1105
      {
1106
        qspec.setUserName(user);
1107
        qspec.setGroup(groups);
1108
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1109
        Vector results = new Vector();
1110
        Enumeration keylist = docListResult.keys();
1111
        StringBuffer doclist = new StringBuffer();
1112
        Vector parentidList = new Vector();
1113
        Hashtable returnFieldValue = new Hashtable();
1114
        while (keylist.hasMoreElements())
1115
        {
1116
          doclist.append("'");
1117
          doclist.append((String) keylist.nextElement());
1118
          doclist.append("',");
1119
        }
1120
        if (doclist.length() > 0)
1121
        {
1122
          Hashtable controlPairs = new Hashtable();
1123
          double extendedQueryStart = System.currentTimeMillis() / 1000;
1124
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1125
          // check if user has permission to see the return field data
1126
          String accessControlSQL =
1127
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
1128
          pstmt = dbconn.prepareStatement(accessControlSQL);
1129
          //increase dbconnection usage count
1130
          dbconn.increaseUsageCount(1);
1131
          pstmt.execute();
1132
          rs = pstmt.getResultSet();
1133
          boolean tableHasRows = rs.next();
1134
          while (tableHasRows)
1135
          {
1136
            long startNodeId = rs.getLong(1);
1137
            long endNodeId = rs.getLong(2);
1138
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
1139
            tableHasRows = rs.next();
1140
          }
1141

    
1142
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
1143
           logMetacat.info( "Time for execute access extended query: "
1144
                          + (extendedAccessQueryEnd - extendedQueryStart));
1145

    
1146
           String extendedQuery =
1147
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
1148
           logMetacat.warn("Extended query: " + extendedQuery);
1149

    
1150
           if(extendedQuery != null){
1151
               pstmt = dbconn.prepareStatement(extendedQuery);
1152
               //increase dbconnection usage count
1153
               dbconn.increaseUsageCount(1);
1154
               pstmt.execute();
1155
               rs = pstmt.getResultSet();
1156
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
1157
               logMetacat.info(
1158
                   "Time for execute extended query: "
1159
                   + (extendedQueryEnd - extendedQueryStart));
1160
               tableHasRows = rs.next();
1161
               while (tableHasRows) {
1162
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1163
                   docid = rs.getString(1).trim();
1164
                   fieldname = rs.getString(2);
1165
                   fielddata = rs.getString(3);
1166
                   fielddata = MetaCatUtil.normalize(fielddata);
1167
                   String parentId = rs.getString(4);
1168
                   StringBuffer value = new StringBuffer();
1169

    
1170
                   // if xml_index is used, there would be just one record per nodeid
1171
                   // as xml_index just keeps one entry for each path
1172
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1173
                       // don't need to merger nodedata
1174
                       value.append("<param name=\"");
1175
                       value.append(fieldname);
1176
                       value.append("\">");
1177
                       value.append(fielddata);
1178
                       value.append("</param>");
1179
                       //set returnvalue
1180
                       returnValue.setDocid(docid);
1181
                       returnValue.setFieldValue(fielddata);
1182
                       returnValue.setXMLFieldValue(value.toString());
1183
                       // Store it in hastable
1184
                       putInArray(parentidList, parentId, returnValue);
1185
                   }
1186
                   else {
1187
                       // need to merge nodedata if they have same parent id and
1188
                       // node type is text
1189
                       fielddata = (String) ( (ReturnFieldValue)
1190
                                             getArrayValue(
1191
                           parentidList, parentId)).getFieldValue()
1192
                           + fielddata;
1193
                       value.append("<param name=\"");
1194
                       value.append(fieldname);
1195
                       value.append("\">");
1196
                       value.append(fielddata);
1197
                       value.append("</param>");
1198
                       returnValue.setDocid(docid);
1199
                       returnValue.setFieldValue(fielddata);
1200
                       returnValue.setXMLFieldValue(value.toString());
1201
                       // remove the old return value from paretnidList
1202
                       parentidList.remove(parentId);
1203
                       // store the new return value in parentidlit
1204
                       putInArray(parentidList, parentId, returnValue);
1205
                   }
1206
                   tableHasRows = rs.next();
1207
               } //while
1208
               rs.close();
1209
               pstmt.close();
1210

    
1211
               // put the merger node data info into doclistReult
1212
               Enumeration xmlFieldValue = (getElements(parentidList)).
1213
                   elements();
1214
               while (xmlFieldValue.hasMoreElements()) {
1215
                   ReturnFieldValue object =
1216
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1217
                   docid = object.getDocid();
1218
                   if (docListResult.containsKey(docid)) {
1219
                       String removedelement = (String) docListResult.
1220
                           remove(docid);
1221
                       docListResult.
1222
                           put(docid,
1223
                               removedelement + object.getXMLFieldValue());
1224
                   }
1225
                   else {
1226
                       docListResult.put(docid, object.getXMLFieldValue());
1227
                   }
1228
               } //while
1229
               double docListResultEnd = System.currentTimeMillis() / 1000;
1230
               logMetacat.warn(
1231
                   "Time for prepare doclistresult after"
1232
                   + " execute extended query: "
1233
                   + (docListResultEnd - extendedQueryEnd));
1234
           }
1235

    
1236
           // get attribures return
1237
           docListResult = getAttributeValueForReturn(qspec,
1238
                           docListResult, doclist.toString(), useXMLIndex);
1239
       }//if doclist lenght is great than zero
1240

    
1241
     }//if has extended query
1242

    
1243
      return docListResult;
1244
    }//addReturnfield
1245

    
1246
    /*
1247
    * A method to add relationship to return doclist hash table
1248
    */
1249
   private Hashtable addRelationship(Hashtable docListResult,
1250
                                     QuerySpecification qspec,
1251
                                     DBConnection dbconn, boolean useXMLIndex )
1252
                                     throws Exception
1253
  {
1254
    PreparedStatement pstmt = null;
1255
    ResultSet rs = null;
1256
    StringBuffer document = null;
1257
    double startRelation = System.currentTimeMillis() / 1000;
1258
    Enumeration docidkeys = docListResult.keys();
1259
    while (docidkeys.hasMoreElements())
1260
    {
1261
      //String connstring =
1262
      // "metacat://"+util.getOption("server")+"?docid=";
1263
      String connstring = "%docid=";
1264
      String docidkey = (String) docidkeys.nextElement();
1265
      pstmt = dbconn.prepareStatement(QuerySpecification
1266
                      .printRelationSQL(docidkey));
1267
      pstmt.execute();
1268
      rs = pstmt.getResultSet();
1269
      boolean tableHasRows = rs.next();
1270
      while (tableHasRows)
1271
      {
1272
        String sub = rs.getString(1);
1273
        String rel = rs.getString(2);
1274
        String obj = rs.getString(3);
1275
        String subDT = rs.getString(4);
1276
        String objDT = rs.getString(5);
1277

    
1278
        document = new StringBuffer();
1279
        document.append("<triple>");
1280
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1281
        document.append("</subject>");
1282
        if (subDT != null)
1283
        {
1284
          document.append("<subjectdoctype>").append(subDT);
1285
          document.append("</subjectdoctype>");
1286
        }
1287
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1288
        document.append("</relationship>");
1289
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1290
        document.append("</object>");
1291
        if (objDT != null)
1292
        {
1293
          document.append("<objectdoctype>").append(objDT);
1294
          document.append("</objectdoctype>");
1295
        }
1296
        document.append("</triple>");
1297

    
1298
        String removedelement = (String) docListResult.remove(docidkey);
1299
        docListResult.put(docidkey, removedelement+ document.toString());
1300
        tableHasRows = rs.next();
1301
      }//while
1302
      rs.close();
1303
      pstmt.close();
1304
    }//while
1305
    double endRelation = System.currentTimeMillis() / 1000;
1306
    logMetacat.info("Time for adding relation to docListResult: "
1307
                             + (endRelation - startRelation));
1308

    
1309
    return docListResult;
1310
  }//addRelation
1311

    
1312
  /**
1313
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1314
   * string as a param instead of a hashtable.
1315
   *
1316
   * @param xmlquery a string representing a query.
1317
   */
1318
   private  String transformQuery(String xmlquery)
1319
   {
1320
     xmlquery = xmlquery.trim();
1321
     int index = xmlquery.indexOf("?>");
1322
     if (index != -1)
1323
     {
1324
       return xmlquery.substring(index + 2, xmlquery.length());
1325
     }
1326
     else
1327
     {
1328
       return xmlquery;
1329
     }
1330
   }
1331

    
1332

    
1333
    /*
1334
     * A method to search if Vector contains a particular key string
1335
     */
1336
    private boolean containsKey(Vector parentidList, String parentId)
1337
    {
1338

    
1339
        Vector tempVector = null;
1340

    
1341
        for (int count = 0; count < parentidList.size(); count++) {
1342
            tempVector = (Vector) parentidList.get(count);
1343
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1344
        }
1345
        return false;
1346
    }
1347

    
1348
    /*
1349
     * A method to put key and value in Vector
1350
     */
1351
    private void putInArray(Vector parentidList, String key,
1352
            ReturnFieldValue value)
1353
    {
1354

    
1355
        Vector tempVector = null;
1356

    
1357
        for (int count = 0; count < parentidList.size(); count++) {
1358
            tempVector = (Vector) parentidList.get(count);
1359

    
1360
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1361
                tempVector.remove(1);
1362
                tempVector.add(1, value);
1363
                return;
1364
            }
1365
        }
1366

    
1367
        tempVector = new Vector();
1368
        tempVector.add(0, key);
1369
        tempVector.add(1, value);
1370
        parentidList.add(tempVector);
1371
        return;
1372
    }
1373

    
1374
    /*
1375
     * A method to get value in Vector given a key
1376
     */
1377
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1378
    {
1379

    
1380
        Vector tempVector = null;
1381

    
1382
        for (int count = 0; count < parentidList.size(); count++) {
1383
            tempVector = (Vector) parentidList.get(count);
1384

    
1385
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1386
                    .get(1); }
1387
        }
1388
        return null;
1389
    }
1390

    
1391
    /*
1392
     * A method to get enumeration of all values in Vector
1393
     */
1394
    private Vector getElements(Vector parentidList)
1395
    {
1396
        Vector enumVector = new Vector();
1397
        Vector tempVector = null;
1398

    
1399
        for (int count = 0; count < parentidList.size(); count++) {
1400
            tempVector = (Vector) parentidList.get(count);
1401

    
1402
            enumVector.add(tempVector.get(1));
1403
        }
1404
        return enumVector;
1405
    }
1406

    
1407
    /*
1408
     * A method to return search result after running a query which return
1409
     * field have attribue
1410
     */
1411
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
1412
            Hashtable docInformationList, String docList, boolean useXMLIndex)
1413
    {
1414
        StringBuffer XML = null;
1415
        String sql = null;
1416
        DBConnection dbconn = null;
1417
        PreparedStatement pstmt = null;
1418
        ResultSet rs = null;
1419
        int serialNumber = -1;
1420
        boolean tableHasRows = false;
1421

    
1422
        //check the parameter
1423
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1424

    
1425
        // if has attribute as return field
1426
        if (squery.containsAttributeReturnField()) {
1427
            sql = squery.printAttributeQuery(docList, useXMLIndex);
1428
            try {
1429
                dbconn = DBConnectionPool
1430
                        .getDBConnection("DBQuery.getAttributeValue");
1431
                serialNumber = dbconn.getCheckOutSerialNumber();
1432
                pstmt = dbconn.prepareStatement(sql);
1433
                pstmt.execute();
1434
                rs = pstmt.getResultSet();
1435
                tableHasRows = rs.next();
1436
                while (tableHasRows) {
1437
                    String docid = rs.getString(1).trim();
1438
                    String fieldname = rs.getString(2);
1439
                    String fielddata = rs.getString(3);
1440
                    String attirbuteName = rs.getString(4);
1441
                    XML = new StringBuffer();
1442

    
1443
                    XML.append("<param name=\"");
1444
                    XML.append(fieldname);
1445
                    XML.append("/");
1446
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1447
                    XML.append(attirbuteName);
1448
                    XML.append("\">");
1449
                    XML.append(fielddata);
1450
                    XML.append("</param>");
1451
                    tableHasRows = rs.next();
1452

    
1453
                    if (docInformationList.containsKey(docid)) {
1454
                        String removedelement = (String) docInformationList
1455
                                .remove(docid);
1456
                        docInformationList.put(docid, removedelement
1457
                                + XML.toString());
1458
                    } else {
1459
                        docInformationList.put(docid, XML.toString());
1460
                    }
1461
                }//while
1462
                rs.close();
1463
                pstmt.close();
1464
            } catch (Exception se) {
1465
                logMetacat.error(
1466
                        "Error in DBQuery.getAttributeValue1: "
1467
                                + se.getMessage());
1468
            } finally {
1469
                try {
1470
                    pstmt.close();
1471
                }//try
1472
                catch (SQLException sqlE) {
1473
                    logMetacat.error(
1474
                            "Error in DBQuery.getAttributeValue2: "
1475
                                    + sqlE.getMessage());
1476
                }//catch
1477
                finally {
1478
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
1479
                }//finally
1480
            }//finally
1481
        }//if
1482
        return docInformationList;
1483

    
1484
    }
1485

    
1486
    /*
1487
     * A method to create a query to get owner's docid list
1488
     */
1489
    private String getOwnerQuery(String owner)
1490
    {
1491
        if (owner != null) {
1492
            owner = owner.toLowerCase();
1493
        }
1494
        StringBuffer self = new StringBuffer();
1495

    
1496
        self.append("SELECT docid,docname,doctype,");
1497
        self.append("date_created, date_updated, rev ");
1498
        self.append("FROM xml_documents WHERE docid IN (");
1499
        self.append("(");
1500
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1501
        self.append("nodedata LIKE '%%%' ");
1502
        self.append(") \n");
1503
        self.append(") ");
1504
        self.append(" AND (");
1505
        self.append(" lower(user_owner) = '" + owner + "'");
1506
        self.append(") ");
1507
        return self.toString();
1508
    }
1509

    
1510
    /**
1511
     * format a structured query as an XML document that conforms to the
1512
     * pathquery.dtd and is appropriate for submission to the DBQuery
1513
     * structured query engine
1514
     *
1515
     * @param params The list of parameters that should be included in the
1516
     *            query
1517
     */
1518
    public static String createSQuery(Hashtable params)
1519
    {
1520
        StringBuffer query = new StringBuffer();
1521
        Enumeration elements;
1522
        Enumeration keys;
1523
        String filterDoctype = null;
1524
        String casesensitive = null;
1525
        String searchmode = null;
1526
        Object nextkey;
1527
        Object nextelement;
1528
        //add the xml headers
1529
        query.append("<?xml version=\"1.0\"?>\n");
1530
        query.append("<pathquery version=\"1.2\">\n");
1531

    
1532

    
1533

    
1534
        if (params.containsKey("meta_file_id")) {
1535
            query.append("<meta_file_id>");
1536
            query.append(((String[]) params.get("meta_file_id"))[0]);
1537
            query.append("</meta_file_id>");
1538
        }
1539

    
1540
        if (params.containsKey("returndoctype")) {
1541
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1542
            for (int i = 0; i < returnDoctypes.length; i++) {
1543
                String doctype = (String) returnDoctypes[i];
1544

    
1545
                if (!doctype.equals("any") && !doctype.equals("ANY")
1546
                        && !doctype.equals("")) {
1547
                    query.append("<returndoctype>").append(doctype);
1548
                    query.append("</returndoctype>");
1549
                }
1550
            }
1551
        }
1552

    
1553
        if (params.containsKey("filterdoctype")) {
1554
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1555
            for (int i = 0; i < filterDoctypes.length; i++) {
1556
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1557
                query.append("</filterdoctype>");
1558
            }
1559
        }
1560

    
1561
        if (params.containsKey("returnfield")) {
1562
            String[] returnfield = ((String[]) params.get("returnfield"));
1563
            for (int i = 0; i < returnfield.length; i++) {
1564
                query.append("<returnfield>").append(returnfield[i]);
1565
                query.append("</returnfield>");
1566
            }
1567
        }
1568

    
1569
        if (params.containsKey("owner")) {
1570
            String[] owner = ((String[]) params.get("owner"));
1571
            for (int i = 0; i < owner.length; i++) {
1572
                query.append("<owner>").append(owner[i]);
1573
                query.append("</owner>");
1574
            }
1575
        }
1576

    
1577
        if (params.containsKey("site")) {
1578
            String[] site = ((String[]) params.get("site"));
1579
            for (int i = 0; i < site.length; i++) {
1580
                query.append("<site>").append(site[i]);
1581
                query.append("</site>");
1582
            }
1583
        }
1584

    
1585
        //allows the dynamic switching of boolean operators
1586
        if (params.containsKey("operator")) {
1587
            query.append("<querygroup operator=\""
1588
                    + ((String[]) params.get("operator"))[0] + "\">");
1589
        } else { //the default operator is UNION
1590
            query.append("<querygroup operator=\"UNION\">");
1591
        }
1592

    
1593
        if (params.containsKey("casesensitive")) {
1594
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1595
        } else {
1596
            casesensitive = "false";
1597
        }
1598

    
1599
        if (params.containsKey("searchmode")) {
1600
            searchmode = ((String[]) params.get("searchmode"))[0];
1601
        } else {
1602
            searchmode = "contains";
1603
        }
1604

    
1605
        //anyfield is a special case because it does a
1606
        //free text search. It does not have a <pathexpr>
1607
        //tag. This allows for a free text search within the structured
1608
        //query. This is useful if the INTERSECT operator is used.
1609
        if (params.containsKey("anyfield")) {
1610
            String[] anyfield = ((String[]) params.get("anyfield"));
1611
            //allow for more than one value for anyfield
1612
            for (int i = 0; i < anyfield.length; i++) {
1613
                if (!anyfield[i].equals("")) {
1614
                    query.append("<queryterm casesensitive=\"" + casesensitive
1615
                            + "\" " + "searchmode=\"" + searchmode
1616
                            + "\"><value>" + anyfield[i]
1617
                            + "</value></queryterm>");
1618
                }
1619
            }
1620
        }
1621

    
1622
        //this while loop finds the rest of the parameters
1623
        //and attempts to query for the field specified
1624
        //by the parameter.
1625
        elements = params.elements();
1626
        keys = params.keys();
1627
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1628
            nextkey = keys.nextElement();
1629
            nextelement = elements.nextElement();
1630

    
1631
            //make sure we aren't querying for any of these
1632
            //parameters since the are already in the query
1633
            //in one form or another.
1634
            Vector ignoredParams = new Vector();
1635
            ignoredParams.add("returndoctype");
1636
            ignoredParams.add("filterdoctype");
1637
            ignoredParams.add("action");
1638
            ignoredParams.add("qformat");
1639
            ignoredParams.add("anyfield");
1640
            ignoredParams.add("returnfield");
1641
            ignoredParams.add("owner");
1642
            ignoredParams.add("site");
1643
            ignoredParams.add("operator");
1644
            ignoredParams.add("sessionid");
1645
            ignoredParams.add("pagesize");
1646
            ignoredParams.add("pagestart");
1647

    
1648
            // Also ignore parameters listed in the properties file
1649
            // so that they can be passed through to stylesheets
1650
            String paramsToIgnore = MetaCatUtil
1651
                    .getOption("query.ignored.params");
1652
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1653
            while (st.hasMoreTokens()) {
1654
                ignoredParams.add(st.nextToken());
1655
            }
1656
            if (!ignoredParams.contains(nextkey.toString())) {
1657
                //allow for more than value per field name
1658
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1659
                    if (!((String[]) nextelement)[i].equals("")) {
1660
                        query.append("<queryterm casesensitive=\""
1661
                                + casesensitive + "\" " + "searchmode=\""
1662
                                + searchmode + "\">" + "<value>" +
1663
                                //add the query value
1664
                                ((String[]) nextelement)[i]
1665
                                + "</value><pathexpr>" +
1666
                                //add the path to query by
1667
                                nextkey.toString() + "</pathexpr></queryterm>");
1668
                    }
1669
                }
1670
            }
1671
        }
1672
        query.append("</querygroup></pathquery>");
1673
        //append on the end of the xml and return the result as a string
1674
        return query.toString();
1675
    }
1676

    
1677
    /**
1678
     * format a simple free-text value query as an XML document that conforms
1679
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1680
     * structured query engine
1681
     *
1682
     * @param value the text string to search for in the xml catalog
1683
     * @param doctype the type of documents to include in the result set -- use
1684
     *            "any" or "ANY" for unfiltered result sets
1685
     */
1686
    public static String createQuery(String value, String doctype)
1687
    {
1688
        StringBuffer xmlquery = new StringBuffer();
1689
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1690
        xmlquery.append("<pathquery version=\"1.0\">");
1691

    
1692
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1693
            xmlquery.append("<returndoctype>");
1694
            xmlquery.append(doctype).append("</returndoctype>");
1695
        }
1696

    
1697
        xmlquery.append("<querygroup operator=\"UNION\">");
1698
        //chad added - 8/14
1699
        //the if statement allows a query to gracefully handle a null
1700
        //query. Without this if a nullpointerException is thrown.
1701
        if (!value.equals("")) {
1702
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1703
            xmlquery.append("searchmode=\"contains\">");
1704
            xmlquery.append("<value>").append(value).append("</value>");
1705
            xmlquery.append("</queryterm>");
1706
        }
1707
        xmlquery.append("</querygroup>");
1708
        xmlquery.append("</pathquery>");
1709

    
1710
        return (xmlquery.toString());
1711
    }
1712

    
1713
    /**
1714
     * format a simple free-text value query as an XML document that conforms
1715
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1716
     * structured query engine
1717
     *
1718
     * @param value the text string to search for in the xml catalog
1719
     */
1720
    public static String createQuery(String value)
1721
    {
1722
        return createQuery(value, "any");
1723
    }
1724

    
1725
    /**
1726
     * Check for "READ" permission on @docid for @user and/or @group from DB
1727
     * connection
1728
     */
1729
    private boolean hasPermission(String user, String[] groups, String docid)
1730
            throws SQLException, Exception
1731
    {
1732
        // Check for READ permission on @docid for @user and/or @groups
1733
        PermissionController controller = new PermissionController(docid);
1734
        return controller.hasPermission(user, groups,
1735
                AccessControlInterface.READSTRING);
1736
    }
1737

    
1738
    /**
1739
     * Get all docIds list for a data packadge
1740
     *
1741
     * @param dataPackageDocid, the string in docId field of xml_relation table
1742
     */
1743
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1744
    {
1745
        DBConnection dbConn = null;
1746
        int serialNumber = -1;
1747
        Vector docIdList = new Vector();//return value
1748
        PreparedStatement pStmt = null;
1749
        ResultSet rs = null;
1750
        String docIdInSubjectField = null;
1751
        String docIdInObjectField = null;
1752

    
1753
        // Check the parameter
1754
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1755

    
1756
        //the query stirng
1757
        String query = "SELECT subject, object from xml_relation where docId = ?";
1758
        try {
1759
            dbConn = DBConnectionPool
1760
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1761
            serialNumber = dbConn.getCheckOutSerialNumber();
1762
            pStmt = dbConn.prepareStatement(query);
1763
            //bind the value to query
1764
            pStmt.setString(1, dataPackageDocid);
1765

    
1766
            //excute the query
1767
            pStmt.execute();
1768
            //get the result set
1769
            rs = pStmt.getResultSet();
1770
            //process the result
1771
            while (rs.next()) {
1772
                //In order to get the whole docIds in a data packadge,
1773
                //we need to put the docIds of subject and object field in
1774
                // xml_relation
1775
                //into the return vector
1776
                docIdInSubjectField = rs.getString(1);//the result docId in
1777
                                                      // subject field
1778
                docIdInObjectField = rs.getString(2);//the result docId in
1779
                                                     // object field
1780

    
1781
                //don't put the duplicate docId into the vector
1782
                if (!docIdList.contains(docIdInSubjectField)) {
1783
                    docIdList.add(docIdInSubjectField);
1784
                }
1785

    
1786
                //don't put the duplicate docId into the vector
1787
                if (!docIdList.contains(docIdInObjectField)) {
1788
                    docIdList.add(docIdInObjectField);
1789
                }
1790
            }//while
1791
            //close the pStmt
1792
            pStmt.close();
1793
        }//try
1794
        catch (SQLException e) {
1795
            logMetacat.error("Error in getDocidListForDataPackage: "
1796
                    + e.getMessage());
1797
        }//catch
1798
        finally {
1799
            try {
1800
                pStmt.close();
1801
            }//try
1802
            catch (SQLException ee) {
1803
                logMetacat.error(
1804
                        "Error in getDocidListForDataPackage: "
1805
                                + ee.getMessage());
1806
            }//catch
1807
            finally {
1808
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1809
            }//fianlly
1810
        }//finally
1811
        return docIdList;
1812
    }//getCurrentDocidListForDataPackadge()
1813

    
1814
    /**
1815
     * Get all docIds list for a data packadge
1816
     *
1817
     * @param dataPackageDocid, the string in docId field of xml_relation table
1818
     */
1819
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1820
    {
1821

    
1822
        Vector docIdList = new Vector();//return value
1823
        Vector tripleList = null;
1824
        String xml = null;
1825

    
1826
        // Check the parameter
1827
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1828

    
1829
        try {
1830
            //initial a documentImpl object
1831
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1832
            //transfer to documentImpl object to string
1833
            xml = packageDocument.toString();
1834

    
1835
            //create a tripcollection object
1836
            TripleCollection tripleForPackage = new TripleCollection(
1837
                    new StringReader(xml));
1838
            //get the vetor of triples
1839
            tripleList = tripleForPackage.getCollection();
1840

    
1841
            for (int i = 0; i < tripleList.size(); i++) {
1842
                //put subject docid into docIdlist without duplicate
1843
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1844
                        .getSubject())) {
1845
                    //put subject docid into docIdlist
1846
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1847
                }
1848
                //put object docid into docIdlist without duplicate
1849
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1850
                        .getObject())) {
1851
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1852
                }
1853
            }//for
1854
        }//try
1855
        catch (Exception e) {
1856
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1857
                    + e.getMessage());
1858
        }//catch
1859

    
1860
        // return result
1861
        return docIdList;
1862
    }//getDocidListForPackageInXMLRevisions()
1863

    
1864
    /**
1865
     * Check if the docId is a data packadge id. If the id is a data packadage
1866
     * id, it should be store in the docId fields in xml_relation table. So we
1867
     * can use a query to get the entries which the docId equals the given
1868
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1869
     * it is.
1870
     *
1871
     * @param docId, the id need to be checked
1872
     */
1873
    private boolean isDataPackageId(String docId)
1874
    {
1875
        boolean result = false;
1876
        PreparedStatement pStmt = null;
1877
        ResultSet rs = null;
1878
        String query = "SELECT docId from xml_relation where docId = ?";
1879
        DBConnection dbConn = null;
1880
        int serialNumber = -1;
1881
        try {
1882
            dbConn = DBConnectionPool
1883
                    .getDBConnection("DBQuery.isDataPackageId");
1884
            serialNumber = dbConn.getCheckOutSerialNumber();
1885
            pStmt = dbConn.prepareStatement(query);
1886
            //bind the value to query
1887
            pStmt.setString(1, docId);
1888
            //execute the query
1889
            pStmt.execute();
1890
            rs = pStmt.getResultSet();
1891
            //process the result
1892
            if (rs.next()) //There are some records for the id in docId fields
1893
            {
1894
                result = true;//It is a data packadge id
1895
            }
1896
            pStmt.close();
1897
        }//try
1898
        catch (SQLException e) {
1899
            logMetacat.error("Error in isDataPackageId: "
1900
                    + e.getMessage());
1901
        } finally {
1902
            try {
1903
                pStmt.close();
1904
            }//try
1905
            catch (SQLException ee) {
1906
                logMetacat.error("Error in isDataPackageId: "
1907
                        + ee.getMessage());
1908
            }//catch
1909
            finally {
1910
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1911
            }//finally
1912
        }//finally
1913
        return result;
1914
    }//isDataPackageId()
1915

    
1916
    /**
1917
     * Check if the user has the permission to export data package
1918
     *
1919
     * @param conn, the connection
1920
     * @param docId, the id need to be checked
1921
     * @param user, the name of user
1922
     * @param groups, the user's group
1923
     */
1924
    private boolean hasPermissionToExportPackage(String docId, String user,
1925
            String[] groups) throws Exception
1926
    {
1927
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1928
        return DocumentImpl.hasReadPermission(user, groups, docId);
1929
    }
1930

    
1931
    /**
1932
     * Get the current Rev for a docid in xml_documents table
1933
     *
1934
     * @param docId, the id need to get version numb If the return value is -5,
1935
     *            means no value in rev field for this docid
1936
     */
1937
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1938
            throws SQLException
1939
    {
1940
        int rev = -5;
1941
        PreparedStatement pStmt = null;
1942
        ResultSet rs = null;
1943
        String query = "SELECT rev from xml_documents where docId = ?";
1944
        DBConnection dbConn = null;
1945
        int serialNumber = -1;
1946
        try {
1947
            dbConn = DBConnectionPool
1948
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1949
            serialNumber = dbConn.getCheckOutSerialNumber();
1950
            pStmt = dbConn.prepareStatement(query);
1951
            //bind the value to query
1952
            pStmt.setString(1, docId);
1953
            //execute the query
1954
            pStmt.execute();
1955
            rs = pStmt.getResultSet();
1956
            //process the result
1957
            if (rs.next()) //There are some records for rev
1958
            {
1959
                rev = rs.getInt(1);
1960
                ;//It is the version for given docid
1961
            } else {
1962
                rev = -5;
1963
            }
1964

    
1965
        }//try
1966
        catch (SQLException e) {
1967
            logMetacat.error(
1968
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1969
                            + e.getMessage());
1970
            throw e;
1971
        }//catch
1972
        finally {
1973
            try {
1974
                pStmt.close();
1975
            }//try
1976
            catch (SQLException ee) {
1977
                logMetacat.error(
1978
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1979
                                + ee.getMessage());
1980
            }//catch
1981
            finally {
1982
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1983
            }//finally
1984
        }//finally
1985
        return rev;
1986
    }//getCurrentRevFromXMLDoumentsTable
1987

    
1988
    /**
1989
     * put a doc into a zip output stream
1990
     *
1991
     * @param docImpl, docmentImpl object which will be sent to zip output
1992
     *            stream
1993
     * @param zipOut, zip output stream which the docImpl will be put
1994
     * @param packageZipEntry, the zip entry name for whole package
1995
     */
1996
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1997
            ZipOutputStream zipOut, String packageZipEntry)
1998
            throws ClassNotFoundException, IOException, SQLException,
1999
            McdbException, Exception
2000
    {
2001
        byte[] byteString = null;
2002
        ZipEntry zEntry = null;
2003

    
2004
        byteString = docImpl.toString().getBytes();
2005
        //use docId as the zip entry's name
2006
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
2007
                + docImpl.getDocID());
2008
        zEntry.setSize(byteString.length);
2009
        zipOut.putNextEntry(zEntry);
2010
        zipOut.write(byteString, 0, byteString.length);
2011
        zipOut.closeEntry();
2012

    
2013
    }//addDocToZipOutputStream()
2014

    
2015
    /**
2016
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
2017
     * only inlcudes current version. If a DocumentImple object couldn't find
2018
     * for a docid, then the String of this docid was added to vetor rather
2019
     * than DocumentImple object.
2020
     *
2021
     * @param docIdList, a vetor hold a docid list for a data package. In
2022
     *            docid, there is not version number in it.
2023
     */
2024

    
2025
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2026
            throws McdbException, Exception
2027
    {
2028
        //Connection dbConn=null;
2029
        Vector documentImplList = new Vector();
2030
        int rev = 0;
2031

    
2032
        // Check the parameter
2033
        if (docIdList.isEmpty()) { return documentImplList; }//if
2034

    
2035
        //for every docid in vector
2036
        for (int i = 0; i < docIdList.size(); i++) {
2037
            try {
2038
                //get newest version for this docId
2039
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2040
                        .elementAt(i));
2041

    
2042
                // There is no record for this docId in xml_documents table
2043
                if (rev == -5) {
2044
                    // Rather than put DocumentImple object, put a String
2045
                    // Object(docid)
2046
                    // into the documentImplList
2047
                    documentImplList.add((String) docIdList.elementAt(i));
2048
                    // Skip other code
2049
                    continue;
2050
                }
2051

    
2052
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2053
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
2054

    
2055
                //create new documentImpl object
2056
                DocumentImpl documentImplObject = new DocumentImpl(
2057
                        docidPlusVersion);
2058
                //add them to vector
2059
                documentImplList.add(documentImplObject);
2060
            }//try
2061
            catch (Exception e) {
2062
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
2063
                        + e.getMessage());
2064
                // continue the for loop
2065
                continue;
2066
            }
2067
        }//for
2068
        return documentImplList;
2069
    }
2070

    
2071
    /**
2072
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2073
     * object couldn't find for a docid, then the String of this docid was
2074
     * added to vetor rather than DocumentImple object.
2075
     *
2076
     * @param docIdList, a vetor hold a docid list for a data package. In
2077
     *            docid, t here is version number in it.
2078
     */
2079
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2080
    {
2081
        //Connection dbConn=null;
2082
        Vector documentImplList = new Vector();
2083
        String siteCode = null;
2084
        String uniqueId = null;
2085
        int rev = 0;
2086

    
2087
        // Check the parameter
2088
        if (docIdList.isEmpty()) { return documentImplList; }//if
2089

    
2090
        //for every docid in vector
2091
        for (int i = 0; i < docIdList.size(); i++) {
2092

    
2093
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2094

    
2095
            try {
2096
                //create new documentImpl object
2097
                DocumentImpl documentImplObject = new DocumentImpl(
2098
                        docidPlusVersion);
2099
                //add them to vector
2100
                documentImplList.add(documentImplObject);
2101
            }//try
2102
            catch (McdbDocNotFoundException notFoundE) {
2103
                logMetacat.error(
2104
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2105
                                + notFoundE.getMessage());
2106
                // Rather than add a DocumentImple object into vetor, a String
2107
                // object
2108
                // - the doicd was added to the vector
2109
                documentImplList.add(docidPlusVersion);
2110
                // Continue the for loop
2111
                continue;
2112
            }//catch
2113
            catch (Exception e) {
2114
                logMetacat.error(
2115
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2116
                                + e.getMessage());
2117
                // Continue the for loop
2118
                continue;
2119
            }//catch
2120

    
2121
        }//for
2122
        return documentImplList;
2123
    }//getOldVersionAllDocumentImple
2124

    
2125
    /**
2126
     * put a data file into a zip output stream
2127
     *
2128
     * @param docImpl, docmentImpl object which will be sent to zip output
2129
     *            stream
2130
     * @param zipOut, the zip output stream which the docImpl will be put
2131
     * @param packageZipEntry, the zip entry name for whole package
2132
     */
2133
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2134
            ZipOutputStream zipOut, String packageZipEntry)
2135
            throws ClassNotFoundException, IOException, SQLException,
2136
            McdbException, Exception
2137
    {
2138
        byte[] byteString = null;
2139
        ZipEntry zEntry = null;
2140
        // this is data file; add file to zip
2141
        String filePath = MetaCatUtil.getOption("datafilepath");
2142
        if (!filePath.endsWith("/")) {
2143
            filePath += "/";
2144
        }
2145
        String fileName = filePath + docImpl.getDocID();
2146
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2147
        zipOut.putNextEntry(zEntry);
2148
        FileInputStream fin = null;
2149
        try {
2150
            fin = new FileInputStream(fileName);
2151
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2152
            int b = fin.read(buf);
2153
            while (b != -1) {
2154
                zipOut.write(buf, 0, b);
2155
                b = fin.read(buf);
2156
            }//while
2157
            zipOut.closeEntry();
2158
        }//try
2159
        catch (IOException ioe) {
2160
            logMetacat.error("There is an exception: "
2161
                    + ioe.getMessage());
2162
        }//catch
2163
    }//addDataFileToZipOutputStream()
2164

    
2165
    /**
2166
     * create a html summary for data package and put it into zip output stream
2167
     *
2168
     * @param docImplList, the documentImpl ojbects in data package
2169
     * @param zipOut, the zip output stream which the html should be put
2170
     * @param packageZipEntry, the zip entry name for whole package
2171
     */
2172
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2173
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2174
    {
2175
        StringBuffer htmlDoc = new StringBuffer();
2176
        ZipEntry zEntry = null;
2177
        byte[] byteString = null;
2178
        InputStream source;
2179
        DBTransform xmlToHtml;
2180

    
2181
        //create a DBTransform ojbect
2182
        xmlToHtml = new DBTransform();
2183
        //head of html
2184
        htmlDoc.append("<html><head></head><body>");
2185
        for (int i = 0; i < docImplList.size(); i++) {
2186
            // If this String object, this means it is missed data file
2187
            if ((((docImplList.elementAt(i)).getClass()).toString())
2188
                    .equals("class java.lang.String")) {
2189

    
2190
                htmlDoc.append("<a href=\"");
2191
                String dataFileid = (String) docImplList.elementAt(i);
2192
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2193
                htmlDoc.append("Data File: ");
2194
                htmlDoc.append(dataFileid).append("</a><br>");
2195
                htmlDoc.append("<br><hr><br>");
2196

    
2197
            }//if
2198
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2199
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2200
                                              // transform it.
2201
                //transform each file individually then concatenate all of the
2202
                //transformations together.
2203

    
2204
                //for metadata xml title
2205
                htmlDoc.append("<h2>");
2206
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2207
                        .getDocID());
2208
                //htmlDoc.append(".");
2209
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2210
                htmlDoc.append("</h2>");
2211
                //do the actual transform
2212
                StringWriter docString = new StringWriter();
2213
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2214
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2215
                        "-//W3C//HTML//EN", "html", docString);
2216
                htmlDoc.append(docString.toString());
2217
                htmlDoc.append("<br><br><hr><br><br>");
2218
            }//if
2219
            else { //this is a data file so we should link to it in the html
2220
                htmlDoc.append("<a href=\"");
2221
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2222
                        .getDocID();
2223
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2224
                htmlDoc.append("Data File: ");
2225
                htmlDoc.append(dataFileid).append("</a><br>");
2226
                htmlDoc.append("<br><hr><br>");
2227
            }//else
2228
        }//for
2229
        htmlDoc.append("</body></html>");
2230
        byteString = htmlDoc.toString().getBytes();
2231
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2232
        zEntry.setSize(byteString.length);
2233
        zipOut.putNextEntry(zEntry);
2234
        zipOut.write(byteString, 0, byteString.length);
2235
        zipOut.closeEntry();
2236
        //dbConn.close();
2237

    
2238
    }//addHtmlSummaryToZipOutputStream
2239

    
2240
    /**
2241
     * put a data packadge into a zip output stream
2242
     *
2243
     * @param docId, which the user want to put into zip output stream,it has version
2244
     * @param out, a servletoutput stream which the zip output stream will be
2245
     *            put
2246
     * @param user, the username of the user
2247
     * @param groups, the group of the user
2248
     */
2249
    public ZipOutputStream getZippedPackage(String docIdString,
2250
            ServletOutputStream out, String user, String[] groups,
2251
            String passWord) throws ClassNotFoundException, IOException,
2252
            SQLException, McdbException, NumberFormatException, Exception
2253
    {
2254
        ZipOutputStream zOut = null;
2255
        String elementDocid = null;
2256
        DocumentImpl docImpls = null;
2257
        //Connection dbConn = null;
2258
        Vector docIdList = new Vector();
2259
        Vector documentImplList = new Vector();
2260
        Vector htmlDocumentImplList = new Vector();
2261
        String packageId = null;
2262
        String rootName = "package";//the package zip entry name
2263

    
2264
        String docId = null;
2265
        int version = -5;
2266
        // Docid without revision
2267
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2268
        // revision number
2269
        version = MetaCatUtil.getVersionFromString(docIdString);
2270

    
2271
        //check if the reqused docId is a data package id
2272
        if (!isDataPackageId(docId)) {
2273

    
2274
            /*
2275
             * Exception e = new Exception("The request the doc id "
2276
             * +docIdString+ " is not a data package id");
2277
             */
2278

    
2279
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2280
            // zip
2281
            //up the single document and return the zip file.
2282
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2283

    
2284
                Exception e = new Exception("User " + user
2285
                        + " does not have permission"
2286
                        + " to export the data package " + docIdString);
2287
                throw e;
2288
            }
2289

    
2290
            docImpls = new DocumentImpl(docIdString);
2291
            //checking if the user has the permission to read the documents
2292
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2293
                    .getDocID())) {
2294
                zOut = new ZipOutputStream(out);
2295
                //if the docImpls is metadata
2296
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2297
                    //add metadata into zip output stream
2298
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2299
                }//if
2300
                else {
2301
                    //it is data file
2302
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2303
                    htmlDocumentImplList.add(docImpls);
2304
                }//else
2305
            }//if
2306

    
2307
            zOut.finish(); //terminate the zip file
2308
            return zOut;
2309
        }
2310
        // Check the permission of user
2311
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2312

    
2313
            Exception e = new Exception("User " + user
2314
                    + " does not have permission"
2315
                    + " to export the data package " + docIdString);
2316
            throw e;
2317
        } else //it is a packadge id
2318
        {
2319
            //store the package id
2320
            packageId = docId;
2321
            //get current version in database
2322
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2323
            //If it is for current version (-1 means user didn't specify
2324
            // revision)
2325
            if ((version == -1) || version == currentVersion) {
2326
                //get current version number
2327
                version = currentVersion;
2328
                //get package zip entry name
2329
                //it should be docId.revsion.package
2330
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2331
                        + version + MetaCatUtil.getOption("accNumSeparator")
2332
                        + "package";
2333
                //get the whole id list for data packadge
2334
                docIdList = getCurrentDocidListForDataPackage(packageId);
2335
                //get the whole documentImple object
2336
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2337

    
2338
            }//if
2339
            else if (version > currentVersion || version < -1) {
2340
                throw new Exception("The user specified docid: " + docId + "."
2341
                        + version + " doesn't exist");
2342
            }//else if
2343
            else //for an old version
2344
            {
2345

    
2346
                rootName = docIdString
2347
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2348
                //get the whole id list for data packadge
2349
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2350

    
2351
                //get the whole documentImple object
2352
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2353
            }//else
2354

    
2355
            // Make sure documentImplist is not empty
2356
            if (documentImplList.isEmpty()) { throw new Exception(
2357
                    "Couldn't find component for data package: " + packageId); }//if
2358

    
2359
            zOut = new ZipOutputStream(out);
2360
            //put every element into zip output stream
2361
            for (int i = 0; i < documentImplList.size(); i++) {
2362
                // if the object in the vetor is String, this means we couldn't
2363
                // find
2364
                // the document locally, we need find it remote
2365
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2366
                        .equals("class java.lang.String")) {
2367
                    // Get String object from vetor
2368
                    String documentId = (String) documentImplList.elementAt(i);
2369
                    logMetacat.info("docid: " + documentId);
2370
                    // Get doicd without revision
2371
                    String docidWithoutRevision = MetaCatUtil
2372
                            .getDocIdFromString(documentId);
2373
                    logMetacat.info("docidWithoutRevsion: "
2374
                            + docidWithoutRevision);
2375
                    // Get revision
2376
                    String revision = MetaCatUtil
2377
                            .getRevisionStringFromString(documentId);
2378
                    logMetacat.info("revsion from docIdentifier: "
2379
                            + revision);
2380
                    // Zip entry string
2381
                    String zipEntryPath = rootName + "/data/";
2382
                    // Create a RemoteDocument object
2383
                    RemoteDocument remoteDoc = new RemoteDocument(
2384
                            docidWithoutRevision, revision, user, passWord,
2385
                            zipEntryPath);
2386
                    // Here we only read data file from remote metacat
2387
                    String docType = remoteDoc.getDocType();
2388
                    if (docType != null) {
2389
                        if (docType.equals("BIN")) {
2390
                            // Put remote document to zip output
2391
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2392
                            // Add String object to htmlDocumentImplList
2393
                            String elementInHtmlList = remoteDoc
2394
                                    .getDocIdWithoutRevsion()
2395
                                    + MetaCatUtil.getOption("accNumSeparator")
2396
                                    + remoteDoc.getRevision();
2397
                            htmlDocumentImplList.add(elementInHtmlList);
2398
                        }//if
2399
                    }//if
2400

    
2401
                }//if
2402
                else {
2403
                    //create a docmentImpls object (represent xml doc) base on
2404
                    // the docId
2405
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2406
                    //checking if the user has the permission to read the
2407
                    // documents
2408
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2409
                            .getDocID())) {
2410
                        //if the docImpls is metadata
2411
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2412
                            //add metadata into zip output stream
2413
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2414
                            //add the documentImpl into the vetor which will
2415
                            // be used in html
2416
                            htmlDocumentImplList.add(docImpls);
2417

    
2418
                        }//if
2419
                        else {
2420
                            //it is data file
2421
                            addDataFileToZipOutputStream(docImpls, zOut,
2422
                                    rootName);
2423
                            htmlDocumentImplList.add(docImpls);
2424
                        }//else
2425
                    }//if
2426
                }//else
2427
            }//for
2428

    
2429
            //add html summary file
2430
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2431
                    rootName);
2432
            zOut.finish(); //terminate the zip file
2433
            //dbConn.close();
2434
            return zOut;
2435
        }//else
2436
    }//getZippedPackage()
2437

    
2438
    private class ReturnFieldValue
2439
    {
2440

    
2441
        private String docid = null; //return field value for this docid
2442

    
2443
        private String fieldValue = null;
2444

    
2445
        private String xmlFieldValue = null; //return field value in xml
2446
                                             // format
2447

    
2448
        public void setDocid(String myDocid)
2449
        {
2450
            docid = myDocid;
2451
        }
2452

    
2453
        public String getDocid()
2454
        {
2455
            return docid;
2456
        }
2457

    
2458
        public void setFieldValue(String myValue)
2459
        {
2460
            fieldValue = myValue;
2461
        }
2462

    
2463
        public String getFieldValue()
2464
        {
2465
            return fieldValue;
2466
        }
2467

    
2468
        public void setXMLFieldValue(String xml)
2469
        {
2470
            xmlFieldValue = xml;
2471
        }
2472

    
2473
        public String getXMLFieldValue()
2474
        {
2475
            return xmlFieldValue;
2476
        }
2477

    
2478
    }
2479
}
(21-21/66)