Project

General

Profile

1 155 jones
/**
2 203 jones
 *  '$RCSfile$'
3 2043 sgarg
 *    Purpose: A Class that searches a relational DB for elements and
4 203 jones
 *             attributes that have free text matches a query string,
5 2043 sgarg
 *             or structured query matches to a path specified node in the
6
 *             XML hierarchy.  It returns a result set consisting of the
7 203 jones
 *             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 155 jones
 *
12 203 jones
 *   '$Author$'
13
 *     '$Date$'
14
 * '$Revision$'
15 669 jones
 *
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 155 jones
 */
30
31 607 bojilova
package edu.ucsb.nceas.metacat;
32 155 jones
33 2074 jones
import java.io.BufferedWriter;
34
import java.io.File;
35
import java.io.FileInputStream;
36 3219 berkley
import java.io.FileOutputStream;
37 2074 jones
import java.io.FileReader;
38
import java.io.FileWriter;
39
import java.io.IOException;
40
import java.io.InputStream;
41 2087 tao
import java.io.PrintWriter;
42 2074 jones
import java.io.StringReader;
43
import java.io.StringWriter;
44 3219 berkley
import java.io.OutputStream;
45 2074 jones
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 1956 jones
import java.util.StringTokenizer;
51 401 berkley
import java.util.Vector;
52 2074 jones
import java.util.zip.ZipEntry;
53
import java.util.zip.ZipOutputStream;
54
55 940 tao
import javax.servlet.ServletOutputStream;
56 2087 tao
import javax.servlet.http.HttpServletResponse;
57 3211 berkley
import javax.servlet.http.HttpSession;
58 155 jones
59 2663 sgarg
import org.apache.log4j.Logger;
60 2087 tao
61 3219 berkley
import org.w3c.dom.*;
62
import javax.xml.parsers.DocumentBuilderFactory;
63
import org.xml.sax.InputSource;
64
import org.w3c.dom.ls.*;
65
66 2074 jones
import edu.ucsb.nceas.morpho.datapackage.Triple;
67
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
68
69 2912 harris
70 2043 sgarg
/**
71 2075 jones
 * 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 155 jones
 */
76 2075 jones
public class DBQuery
77
{
78 155 jones
79 2075 jones
    static final int ALL = 1;
80 2043 sgarg
81 2075 jones
    static final int WRITE = 2;
82 2043 sgarg
83 2075 jones
    static final int READ = 4;
84 155 jones
85 2075 jones
    //private Connection conn = null;
86
    private String parserName = null;
87 706 bojilova
88 2075 jones
    private MetaCatUtil util = new MetaCatUtil();
89 706 bojilova
90 2663 sgarg
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
91
92 2912 harris
    /** true if the metacat spatial option is installed **/
93
    private final boolean METACAT_SPATIAL = true;
94
95 3055 perry
    /** useful if you just want to grab a list of docids **/
96 3047 perry
    Vector docidOverride = new Vector();
97
98 2075 jones
    /**
99
     * the main routine used to test the DBQuery utility.
100
     * <p>
101
     * Usage: java DBQuery <xmlfile>
102 2087 tao
     *
103 2075 jones
     * @param xmlfile the filename of the xml file containing the query
104
     */
105
    static public void main(String[] args)
106
    {
107 706 bojilova
108 2075 jones
        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 706 bojilova
115 2075 jones
                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 706 bojilova
128 2075 jones
                // Time the request if asked for
129
                double startTime = System.currentTimeMillis();
130 2043 sgarg
131 2075 jones
                // Open a connection to the database
132
                MetaCatUtil util = new MetaCatUtil();
133
                //Connection dbconn = util.openDBConnection();
134 2043 sgarg
135 2075 jones
                double connTime = System.currentTimeMillis();
136 2043 sgarg
137 2075 jones
                // Execute the query
138 2752 jones
                DBQuery queryobj = new DBQuery();
139 2075 jones
                FileReader xml = new FileReader(new File(xmlfile));
140
                Hashtable nodelist = null;
141 2087 tao
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
142 2043 sgarg
143 2075 jones
                // 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 2043 sgarg
150 2075 jones
                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 706 bojilova
159 2075 jones
                    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 2043 sgarg
185 2075 jones
            } 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 2043 sgarg
193 2075 jones
    /**
194
     * construct an instance of the DBQuery class
195 2087 tao
     *
196 2075 jones
     * <p>
197
     * Generally, one would call the findDocuments() routine after creating an
198
     * instance to specify the search query
199
     * </p>
200 2087 tao
     *
201
202 2075 jones
     * @param parserName the fully qualified name of a Java class implementing
203
     *            the org.xml.sax.XMLReader interface
204
     */
205 2752 jones
    public DBQuery()
206 2075 jones
    {
207 2752 jones
        String parserName = MetaCatUtil.getOption("saxparser");
208
        this.parserName = parserName;
209 2075 jones
    }
210 2043 sgarg
211 3047 perry
    /**
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 2087 tao
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 2075 jones
    /**
255 2087 tao
     * 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 2075 jones
     */
263 2087 tao
    public void findDocuments(HttpServletResponse response,
264
                                         PrintWriter out, Hashtable params,
265
                                         String user, String[] groups,
266
                                         String sessionid, boolean useXMLIndex)
267 2075 jones
    {
268 3211 berkley
      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 2087 tao
      // get query and qformat
283
      String xmlquery = ((String[])params.get("query"))[0];
284 2168 tao
285 3211 berkley
      logMetacat.warn("SESSIONID: " + sessionid);
286 2663 sgarg
      logMetacat.warn("xmlquery: " + xmlquery);
287 2087 tao
      String qformat = ((String[])params.get("qformat"))[0];
288 2663 sgarg
      logMetacat.warn("qformat: " + qformat);
289 2168 tao
      // 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 2912 harris
           logMetacat.error("error generating QuerySpecification object"
303 2168 tao
                                    +" in DBQuery.findDocuments"
304 2663 sgarg
                                    + ee.getMessage());
305 2168 tao
         }
306
      }
307 2087 tao
308 2168 tao
309
310 2087 tao
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
311
      {
312
        //xml format
313
        response.setContentType("text/xml");
314 3211 berkley
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex,
315
          pagesize, pagestart, sessionid);
316 2087 tao
      }//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 2168 tao
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
323 3211 berkley
                                                groups, useXMLIndex, pagesize,
324
                                                pagestart, sessionid);
325 2658 sgarg
326 2087 tao
        //transfer the xml to html
327
        try
328
        {
329
330
         DBTransform trans = new DBTransform();
331
         response.setContentType("text/html");
332 2787 sgarg
333 3219 berkley
         // if the user is a moderator, then pass a param to the
334 2787 sgarg
         // xsl specifying the fact
335
         if(MetaCatUtil.isModerator(user, groups)){
336
        	 params.put("isModerator", new String[] {"true"});
337
         }
338
339 2087 tao
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
340
                                 "-//W3C//HTML//EN", qformat, out, params,
341
                                 sessionid);
342
343
        }
344
        catch(Exception e)
345
        {
346 2663 sgarg
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
347
                                +e.getMessage());
348 2087 tao
         }
349
350
      }//else
351
352 3219 berkley
  }
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 2075 jones
    }
366 3219 berkley
367
    return new StringBuffer(mrs.serializeToXML(pagestart, pagestart + pagesize));
368
  }
369 2043 sgarg
370 2087 tao
  /*
371
   * Transforms a hashtable of documents to an xml or html result and sent
372 2168 tao
   * the content to outputstream. Keep going untill hastable is empty. stop it.
373
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
374
   * to xmlquery String
375 2087 tao
   */
376 2168 tao
  public StringBuffer createResultDocument(String xmlquery,
377
                                            QuerySpecification qspec,
378
                                            PrintWriter out,
379 2087 tao
                                            String user, String[] groups,
380 3211 berkley
                                            boolean useXMLIndex, int pagesize,
381
                                            int pagestart, String sessionid)
382 2087 tao
  {
383
    DBConnection dbconn = null;
384
    int serialNumber = -1;
385
    StringBuffer resultset = new StringBuffer();
386 3219 berkley
387
    //try to get the cached version first
388
    Hashtable sessionHash = MetaCatServlet.getSessionHash();
389
    HttpSession sess = (HttpSession)sessionHash.get(sessionid);
390
391
    QuerySpecification cachedQuerySpec = (QuerySpecification)sess.getAttribute("query");
392
    if(cachedQuerySpec != null &&
393
       cachedQuerySpec.printSQL(false).equals(qspec.printSQL(false)))
394
    { //use the cached resultset if the query was the same as the last
395
      MetacatResultSet mrs = (MetacatResultSet)sess.getAttribute("results");
396
      logMetacat.info("Using cached query results");
397
      //if the query is the same and the session contains the query
398
      //results, return those instead of rerunning the query
399
      if(mrs != null)
400
      { //print and return the cached buffer
401
        StringBuffer pagedResultBuffer = getPagedResult(mrs, pagestart,
402
          pagesize);
403
        if(out != null)
404
        {
405
          out.println("<?xml version=\"1.0\"?>\n");
406
          out.println("<resultset>\n");
407
          out.println("  <query>" + xmlquery + "</query>\n");
408
          out.println(pagedResultBuffer.toString());
409
          out.println("\n</resultset>\n");
410
        }
411
        String returnString = "<?xml version=\"1.0\"?>\n";
412
        returnString += "<resultset>\n";
413
        returnString += "  <query>" + xmlquery + "</query>\n";
414
        returnString += pagedResultBuffer.toString();
415
        returnString += "\n</resultset>\n";
416
        return new StringBuffer(returnString);
417
      }
418
    }
419
420
    //no cached results...go on with a normal query
421
422 2087 tao
    resultset.append("<?xml version=\"1.0\"?>\n");
423
    resultset.append("<resultset>\n");
424
    resultset.append("  <query>" + xmlquery + "</query>");
425 3219 berkley
    //send out a new query
426 2087 tao
    if (out != null)
427 2075 jones
    {
428 2087 tao
      out.println(resultset.toString());
429 2075 jones
    }
430 2168 tao
    if (qspec != null)
431 2087 tao
    {
432 2168 tao
      try
433
      {
434 2043 sgarg
435 2168 tao
        //checkout the dbconnection
436
        dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
437
        serialNumber = dbconn.getCheckOutSerialNumber();
438 2087 tao
439 2168 tao
        //print out the search result
440
        // search the doc list
441
        resultset = findResultDoclist(qspec, resultset, out, user, groups,
442 3211 berkley
                                      dbconn, useXMLIndex, pagesize, pagestart,
443
                                      sessionid);
444 2087 tao
445 2168 tao
      } //try
446
      catch (IOException ioe)
447
      {
448 2663 sgarg
        logMetacat.error("IO error in DBQuery.findDocuments:");
449
        logMetacat.error(ioe.getMessage());
450 2043 sgarg
451 2168 tao
      }
452
      catch (SQLException e)
453
      {
454 2663 sgarg
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
455
                                 + e.getMessage());
456 2168 tao
      }
457
      catch (Exception ee)
458
      {
459 2663 sgarg
        logMetacat.error("Exception in DBQuery.findDocuments: "
460
                                 + ee.getMessage());
461 3219 berkley
        ee.printStackTrace();
462 2168 tao
      }
463
      finally
464
      {
465
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
466
      } //finally
467
    }//if
468 2087 tao
    String closeRestultset = "</resultset>";
469
    resultset.append(closeRestultset);
470
    if (out != null)
471
    {
472
      out.println(closeRestultset);
473
    }
474 2168 tao
475 3219 berkley
    //create a DOM to cache
476
    try
477
    {
478
479
      //cache the query result and the query
480
      logMetacat.info("Caching query and resultset");
481
      sess.setAttribute("query", qspec);
482
      MetacatResultSet mrs = processAndCacheResults(resultset.toString(), sess);
483
      sess.setAttribute("results", mrs);
484
      StringBuffer pagedResultBuffer = getPagedResult(mrs, pagestart, pagesize);
485
      String returnString = "<?xml version=\"1.0\"?>\n";
486
      returnString += "<resultset>\n";
487
      returnString += "  <query>" + xmlquery + "</query>\n";
488
      returnString += pagedResultBuffer.toString();
489
      returnString += "\n</resultset>\n";
490
      return new StringBuffer(returnString);
491
    }
492
    catch(Exception e)
493
    {
494
      logMetacat.error("################Could not parse resultset: " + e.getMessage());
495
    }
496
497 2087 tao
    return resultset;
498
  }//createResultDocuments
499 2043 sgarg
500 3219 berkley
  /**
501
   * parse the dom of the resultset into a MetacatResultSet object so it can
502
   * be cached in a reasonable way
503
   */
504
  private MetacatResultSet processAndCacheResults(String resultset, HttpSession sess)
505
    throws Exception
506
  {
507
    StringReader sreader = new StringReader(resultset.toString());
508
    InputSource inputsource = new InputSource(sreader);
509
    logMetacat.warn("processing DOM");
510
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputsource);
511
    //got the dom, now process it into an MRS
512
    MetacatResultSet mrs = new MetacatResultSet(doc);
513
    return mrs;
514
  }
515 743 jones
516 2087 tao
    /*
517
     * Find the doc list which match the query
518
     */
519
    private StringBuffer findResultDoclist(QuerySpecification qspec,
520
                                      StringBuffer resultsetBuffer,
521
                                      PrintWriter out,
522
                                      String user, String[]groups,
523 3211 berkley
                                      DBConnection dbconn, boolean useXMLIndex,
524
                                      int pagesize, int pagestart, String sessionid)
525 2087 tao
                                      throws Exception
526
    {
527 3219 berkley
      String query = null;
528
      int count = 0;
529
      int index = 0;
530
      Hashtable docListResult = new Hashtable();
531
      PreparedStatement pstmt = null;
532
      String docid = null;
533
      String docname = null;
534
      String doctype = null;
535
      String createDate = null;
536
      String updateDate = null;
537
      StringBuffer document = null;
538
      int rev = 0;
539
      double startTime = 0;
540
      int offset = 1;
541 2912 harris
542 3219 berkley
      ResultSet rs = null;
543
544
      offset = 1;
545 2091 tao
      // this is a hack for offset
546
      if (out == null)
547
      {
548
        // for html page, we put everything into one page
549 2421 sgarg
        offset =
550
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
551 2091 tao
      }
552
      else
553
      {
554
          offset =
555 2421 sgarg
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
556 2091 tao
      }
557 2421 sgarg
558 3047 perry
      /*
559
       * Check the docidOverride Vector
560
       * if defined, we bypass the qspec.printSQL() method
561
       * and contruct a simpler query based on a
562
       * list of docids rather than a bunch of subselects
563
       */
564
      if ( this.docidOverride.size() == 0 ) {
565
          query = qspec.printSQL(useXMLIndex);
566
      } else {
567 3104 perry
          logMetacat.info("*** docid override " + this.docidOverride.size());
568 3047 perry
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
569
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
570
          for (int i = 0; i < docidOverride.size(); i++) {
571
              queryBuffer.append("'");
572
              queryBuffer.append( (String)docidOverride.elementAt(i) );
573
              queryBuffer.append("',");
574
          }
575 3104 perry
          // empty string hack
576 3047 perry
          queryBuffer.append( "'') " );
577
          query = queryBuffer.toString();
578
      }
579
580 2087 tao
      String ownerQuery = getOwnerQuery(user);
581 3047 perry
      logMetacat.info("\n\n\n query: " + query);
582
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
583 2087 tao
      // if query is not the owner query, we need to check the permission
584
      // otherwise we don't need (owner has all permission by default)
585
      if (!query.equals(ownerQuery))
586
      {
587
        // set user name and group
588
        qspec.setUserName(user);
589
        qspec.setGroup(groups);
590
        // Get access query
591
        String accessQuery = qspec.getAccessQuery();
592 2366 sgarg
        if(!query.endsWith("WHERE")){
593
            query = query + accessQuery;
594
        } else {
595
            query = query + accessQuery.substring(4, accessQuery.length());
596
        }
597 3047 perry
        logMetacat.warn("\n\n\n final query: " + query);
598 2087 tao
      }
599 2043 sgarg
600 3219 berkley
      startTime = System.currentTimeMillis() / 1000;
601 2087 tao
      pstmt = dbconn.prepareStatement(query);
602 3219 berkley
      rs = pstmt.executeQuery();
603
      //now we need to process the resultset based on pagesize and pagestart
604
      //if they are not 0
605 2087 tao
      double queryExecuteTime = System.currentTimeMillis() / 1000;
606 3219 berkley
      logMetacat.warn("Time to execute query: "
607 2663 sgarg
                    + (queryExecuteTime - startTime));
608 2087 tao
      boolean tableHasRows = rs.next();
609
      while (tableHasRows)
610
      {
611
        docid = rs.getString(1).trim();
612
        docname = rs.getString(2);
613
        doctype = rs.getString(3);
614
        createDate = rs.getString(4);
615
        updateDate = rs.getString(5);
616
        rev = rs.getInt(6);
617 2043 sgarg
618 2087 tao
        // if there are returndocs to match, backtracking can be performed
619
        // otherwise, just return the document that was hit
620
        Vector returndocVec = qspec.getReturnDocList();
621 2091 tao
         if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
622 2087 tao
                        && !qspec.isPercentageSearch())
623 3219 berkley
         {
624 2663 sgarg
           logMetacat.warn("Back tracing now...");
625 2087 tao
           String sep = MetaCatUtil.getOption("accNumSeparator");
626
           StringBuffer btBuf = new StringBuffer();
627
           btBuf.append("select docid from xml_relation where ");
628 743 jones
629 2087 tao
           //build the doctype list for the backtracking sql statement
630
           btBuf.append("packagetype in (");
631
           for (int i = 0; i < returndocVec.size(); i++)
632
           {
633
             btBuf.append("'").append((String) returndocVec.get(i)).append("'");
634
             if (i != (returndocVec.size() - 1))
635
             {
636
                btBuf.append(", ");
637
              }
638
            }
639
            btBuf.append(") ");
640
            btBuf.append("and (subject like '");
641
            btBuf.append(docid).append("'");
642
            btBuf.append("or object like '");
643
            btBuf.append(docid).append("')");
644 743 jones
645 2087 tao
            PreparedStatement npstmt = dbconn.prepareStatement(btBuf.toString());
646
            //should incease usage count
647
            dbconn.increaseUsageCount(1);
648
            npstmt.execute();
649
            ResultSet btrs = npstmt.getResultSet();
650
            boolean hasBtRows = btrs.next();
651
            while (hasBtRows)
652
            {
653
               //there was a backtrackable document found
654
               DocumentImpl xmldoc = null;
655
               String packageDocid = btrs.getString(1);
656 2663 sgarg
               logMetacat.info("Getting document for docid: "
657
                                         + packageDocid);
658 2087 tao
                try
659
                {
660
                    //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not
661
                    // needed here
662
                    // xmldoc = new DocumentImpl(dbconn, packageDocid);
663
                    //  thus use the following to get the doc info only
664
                    //  xmldoc = new DocumentImpl(dbconn);
665 2641 tao
                    String accNumber = packageDocid + MetaCatUtil.getOption("accNumSeparator") +
666
                    DBUtil.getLatestRevisionInDocumentTable(packageDocid);
667
                    xmldoc = new DocumentImpl(accNumber, false);
668 2087 tao
                    if (xmldoc == null)
669
                    {
670 2663 sgarg
                       logMetacat.info("Document was null for: "
671
                                                + packageDocid);
672 2075 jones
                    }
673 2087 tao
                }
674
                catch (Exception e)
675
                {
676
                    System.out.println("Error getting document in "
677
                                       + "DBQuery.findDocuments: "
678
                                       + e.getMessage());
679
                }
680 2043 sgarg
681 2087 tao
                String docid_org = xmldoc.getDocID();
682
                if (docid_org == null)
683
                {
684 2663 sgarg
                   logMetacat.info("Docid_org was null.");
685 2091 tao
                   //continue;
686 2087 tao
                }
687
                docid = docid_org.trim();
688
                docname = xmldoc.getDocname();
689
                doctype = xmldoc.getDoctype();
690
                createDate = xmldoc.getCreateDate();
691
                updateDate = xmldoc.getUpdateDate();
692
                rev = xmldoc.getRev();
693
                document = new StringBuffer();
694 2043 sgarg
695 2087 tao
                String completeDocid = docid
696 2075 jones
                                + MetaCatUtil.getOption("accNumSeparator");
697 2087 tao
                completeDocid += rev;
698
                document.append("<docid>").append(completeDocid);
699
                document.append("</docid>");
700
                if (docname != null)
701
                {
702
                  document.append("<docname>" + docname + "</docname>");
703
                }
704
                if (doctype != null)
705
                {
706
                  document.append("<doctype>" + doctype + "</doctype>");
707
                }
708
                if (createDate != null)
709
                {
710
                 document.append("<createdate>" + createDate + "</createdate>");
711
                }
712
                if (updateDate != null)
713
                {
714
                  document.append("<updatedate>" + updateDate+ "</updatedate>");
715
                }
716
                // Store the document id and the root node id
717
                docListResult.put(docid, (String) document.toString());
718
                count++;
719 2043 sgarg
720 2091 tao
721 2087 tao
                // Get the next package document linked to our hit
722
                hasBtRows = btrs.next();
723
              }//while
724
              npstmt.close();
725
              btrs.close();
726
        }
727 2106 jones
        else if (returndocVec.size() == 0 || returndocVec.contains(doctype))
728 2087 tao
        {
729 2043 sgarg
730 2087 tao
           document = new StringBuffer();
731 2043 sgarg
732 2087 tao
           String completeDocid = docid
733 2075 jones
                            + MetaCatUtil.getOption("accNumSeparator");
734 2087 tao
           completeDocid += rev;
735
           document.append("<docid>").append(completeDocid).append("</docid>");
736
           if (docname != null)
737
           {
738
               document.append("<docname>" + docname + "</docname>");
739 3219 berkley
           }
740
           if (doctype != null)
741
           {
742
              document.append("<doctype>" + doctype + "</doctype>");
743
           }
744
           if (createDate != null)
745
           {
746
               document.append("<createdate>" + createDate + "</createdate>");
747
           }
748
           if (updateDate != null)
749
           {
750
             document.append("<updatedate>" + updateDate + "</updatedate>");
751
           }
752
           // Store the document id and the root node id
753
           docListResult.put(docid, (String) document.toString());
754
           count++;
755 2043 sgarg
756 2087 tao
        }//else
757
        // when doclist reached the offset number, send out doc list and empty
758
        // the hash table
759
        if (count == offset)
760
        {
761
          //reset count
762
          count = 0;
763
          handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
764
                              user, groups,dbconn, useXMLIndex);
765
          // reset docListResult
766
          docListResult = new Hashtable();
767 2043 sgarg
768 2087 tao
        }
769
       // Advance to the next record in the cursor
770
       tableHasRows = rs.next();
771
     }//while
772
     rs.close();
773
     pstmt.close();
774
     //if docListResult is not empty, it need to be sent.
775
     if (!docListResult.isEmpty())
776
     {
777
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
778
                              user, groups,dbconn, useXMLIndex);
779
     }
780
     double docListTime = System.currentTimeMillis() / 1000;
781 2663 sgarg
     logMetacat.warn("prepare docid list time: "
782
                    + (docListTime - queryExecuteTime));
783 2091 tao
784 2087 tao
     return resultsetBuffer;
785
    }//findReturnDoclist
786 2043 sgarg
787
788 2087 tao
    /*
789
     * Send completed search hashtable(part of reulst)to output stream
790
     * and buffer into a buffer stream
791
     */
792
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
793
                                           StringBuffer resultset,
794
                                           PrintWriter out, Hashtable partOfDoclist,
795
                                           String user, String[]groups,
796
                                       DBConnection dbconn, boolean useXMLIndex)
797
                                       throws Exception
798
   {
799 2421 sgarg
800 2424 sgarg
     // check if there is a record in xml_returnfield
801
     // and get the returnfield_id and usage count
802
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
803
     boolean enterRecords = false;
804
805
     // get value of xml_returnfield_count
806
     int count = (new Integer(MetaCatUtil
807
                            .getOption("xml_returnfield_count")))
808
                            .intValue();
809 2430 sgarg
810 2446 sgarg
     // set enterRecords to true if usage_count is more than the offset
811 2430 sgarg
     // specified in metacat.properties
812 2424 sgarg
     if(usage_count > count){
813
         enterRecords = true;
814
     }
815
816 2421 sgarg
     if(returnfield_id < 0){
817 2663 sgarg
         logMetacat.warn("Error in getting returnfield id from"
818
                                  + "xml_returnfield table");
819 2486 sgarg
	enterRecords = false;
820 2421 sgarg
     }
821
822
     // get the hashtable containing the docids that already in the
823
     // xml_queryresult table
824 2663 sgarg
     logMetacat.info("size of partOfDoclist before"
825 2421 sgarg
                             + " docidsInQueryresultTable(): "
826 2663 sgarg
                             + partOfDoclist.size());
827 2421 sgarg
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
828
                                                        partOfDoclist, dbconn);
829
830
     // remove the keys in queryresultDocList from partOfDoclist
831
     Enumeration _keys = queryresultDocList.keys();
832
     while (_keys.hasMoreElements()){
833
         partOfDoclist.remove(_keys.nextElement());
834
     }
835 2425 sgarg
836
     // backup the keys-elements in partOfDoclist to check later
837
     // if the doc entry is indexed yet
838
     Hashtable partOfDoclistBackup = new Hashtable();
839
     _keys = partOfDoclist.keys();
840
     while (_keys.hasMoreElements()){
841
	 Object key = _keys.nextElement();
842
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
843
     }
844
845 2663 sgarg
     logMetacat.info("size of partOfDoclist after"
846 2421 sgarg
                             + " docidsInQueryresultTable(): "
847 2663 sgarg
                             + partOfDoclist.size());
848 2421 sgarg
849
     //add return fields for the documents in partOfDoclist
850
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
851 2087 tao
                                        dbconn, useXMLIndex );
852 2421 sgarg
     //add relationship part part docid list for the documents in partOfDocList
853 2087 tao
     partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
854 2421 sgarg
855
856
     Enumeration keys = partOfDoclist.keys();
857 2087 tao
     String key = null;
858
     String element = null;
859 2421 sgarg
     String query = null;
860
     int offset = (new Integer(MetaCatUtil
861
                               .getOption("queryresult_string_length")))
862
                               .intValue();
863 2087 tao
     while (keys.hasMoreElements())
864
     {
865 2421 sgarg
         key = (String) keys.nextElement();
866
         element = (String)partOfDoclist.get(key);
867
868 2446 sgarg
	 // check if the enterRecords is true, elements is not null, element's
869
         // length is less than the limit of table column and if the document
870 2425 sgarg
         // has been indexed already
871 2446 sgarg
         if(enterRecords && element != null
872 2425 sgarg
		&& element.length() < offset
873
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
874 2421 sgarg
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
875 2446 sgarg
                 + "queryresult_string) VALUES (?, ?, ?)";
876
877 2421 sgarg
             PreparedStatement pstmt = null;
878
             pstmt = dbconn.prepareStatement(query);
879 2446 sgarg
             pstmt.setInt(1, returnfield_id);
880
             pstmt.setString(2, key);
881
             pstmt.setString(3, element);
882
883 2421 sgarg
             dbconn.increaseUsageCount(1);
884
             pstmt.execute();
885
             pstmt.close();
886
         }
887
888
         // A string with element
889
         String xmlElement = "  <document>" + element + "</document>";
890
891
         //send single element to output
892
         if (out != null)
893
         {
894 2087 tao
             out.println(xmlElement);
895 2421 sgarg
         }
896
         resultset.append(xmlElement);
897
     }//while
898
899
900
     keys = queryresultDocList.keys();
901
     while (keys.hasMoreElements())
902
     {
903
         key = (String) keys.nextElement();
904
         element = (String)queryresultDocList.get(key);
905
         // A string with element
906
         String xmlElement = "  <document>" + element + "</document>";
907
         //send single element to output
908
         if (out != null)
909
         {
910
             out.println(xmlElement);
911
         }
912
         resultset.append(xmlElement);
913
     }//while
914
915
     return resultset;
916
 }
917
918
   /**
919
    * Get the docids already in xml_queryresult table and corresponding
920
    * queryresultstring as a hashtable
921
    */
922
   private Hashtable docidsInQueryresultTable(int returnfield_id,
923
                                              Hashtable partOfDoclist,
924
                                              DBConnection dbconn){
925
926
         Hashtable returnValue = new Hashtable();
927
         PreparedStatement pstmt = null;
928
         ResultSet rs = null;
929
930
         // get partOfDoclist as string for the query
931
         Enumeration keylist = partOfDoclist.keys();
932
         StringBuffer doclist = new StringBuffer();
933
         while (keylist.hasMoreElements())
934
         {
935
             doclist.append("'");
936
             doclist.append((String) keylist.nextElement());
937
             doclist.append("',");
938
         }//while
939
940
941
         if (doclist.length() > 0)
942
         {
943
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
944
945
             // the query to find out docids from xml_queryresult
946
             String query = "select docid, queryresult_string from "
947
                          + "xml_queryresult where returnfield_id = " +
948
                          returnfield_id +" and docid in ("+ doclist + ")";
949 2663 sgarg
             logMetacat.info("Query to get docids from xml_queryresult:"
950
                                      + query);
951 2421 sgarg
952
             try {
953
                 // prepare and execute the query
954
                 pstmt = dbconn.prepareStatement(query);
955
                 dbconn.increaseUsageCount(1);
956
                 pstmt.execute();
957
                 rs = pstmt.getResultSet();
958
                 boolean tableHasRows = rs.next();
959
                 while (tableHasRows) {
960
                     // store the returned results in the returnValue hashtable
961
                     String key = rs.getString(1);
962
                     String element = rs.getString(2);
963
964
                     if(element != null){
965
                         returnValue.put(key, element);
966
                     } else {
967 2663 sgarg
                         logMetacat.info("Null elment found ("
968
                         + "DBQuery.docidsInQueryresultTable)");
969 2421 sgarg
                     }
970
                     tableHasRows = rs.next();
971
                 }
972
                 rs.close();
973
                 pstmt.close();
974
             } catch (Exception e){
975 2663 sgarg
                 logMetacat.error("Error getting docids from "
976 2421 sgarg
                                          + "queryresult in "
977
                                          + "DBQuery.docidsInQueryresultTable: "
978 2663 sgarg
                                          + e.getMessage());
979 2421 sgarg
              }
980
         }
981
         return returnValue;
982
     }
983
984
985
   /**
986
    * Method to get id from xml_returnfield table
987
    * for a given query specification
988
    */
989 2424 sgarg
   private int returnfield_id;
990 2421 sgarg
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
991
                                           DBConnection dbconn){
992
       int id = -1;
993 2424 sgarg
       int count = 1;
994 2421 sgarg
       PreparedStatement pstmt = null;
995
       ResultSet rs = null;
996
       String returnfield = qspec.getSortedReturnFieldString();
997
998
       // query for finding the id from xml_returnfield
999 2446 sgarg
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1000
            + "WHERE returnfield_string LIKE ?";
1001 2663 sgarg
       logMetacat.info("ReturnField Query:" + query);
1002 2421 sgarg
1003
       try {
1004
           // prepare and run the query
1005
           pstmt = dbconn.prepareStatement(query);
1006 2446 sgarg
           pstmt.setString(1,returnfield);
1007 2421 sgarg
           dbconn.increaseUsageCount(1);
1008
           pstmt.execute();
1009
           rs = pstmt.getResultSet();
1010
           boolean tableHasRows = rs.next();
1011
1012
           // if record found then increase the usage count
1013
           // else insert a new record and get the id of the new record
1014
           if(tableHasRows){
1015
               // get the id
1016
               id = rs.getInt(1);
1017 2424 sgarg
               count = rs.getInt(2) + 1;
1018 2421 sgarg
               rs.close();
1019
               pstmt.close();
1020
1021
               // increase the usage count
1022
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1023
                   + "' WHERE returnfield_id ='"+ id +"'";
1024 2663 sgarg
               logMetacat.info("ReturnField Table Update:"+ query);
1025 2421 sgarg
1026
               pstmt = dbconn.prepareStatement(query);
1027
               dbconn.increaseUsageCount(1);
1028
               pstmt.execute();
1029
               pstmt.close();
1030
1031
           } else {
1032
               rs.close();
1033
               pstmt.close();
1034
1035
               // insert a new record
1036
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1037 2446 sgarg
                   + "VALUES (?, '1')";
1038 2663 sgarg
               logMetacat.info("ReturnField Table Insert:"+ query);
1039 2421 sgarg
               pstmt = dbconn.prepareStatement(query);
1040 2446 sgarg
               pstmt.setString(1, returnfield);
1041 2421 sgarg
               dbconn.increaseUsageCount(1);
1042
               pstmt.execute();
1043
               pstmt.close();
1044
1045
               // get the id of the new record
1046 2446 sgarg
               query = "SELECT returnfield_id FROM xml_returnfield "
1047
                   + "WHERE returnfield_string LIKE ?";
1048 2663 sgarg
               logMetacat.info("ReturnField query after Insert:" + query);
1049 2421 sgarg
               pstmt = dbconn.prepareStatement(query);
1050 2446 sgarg
               pstmt.setString(1, returnfield);
1051
1052 2421 sgarg
               dbconn.increaseUsageCount(1);
1053
               pstmt.execute();
1054
               rs = pstmt.getResultSet();
1055
               if(rs.next()){
1056
                   id = rs.getInt(1);
1057
               } else {
1058
                   id = -1;
1059
               }
1060
               rs.close();
1061
               pstmt.close();
1062 2087 tao
           }
1063 2091 tao
1064 2421 sgarg
       } catch (Exception e){
1065 2663 sgarg
           logMetacat.error("Error getting id from xml_returnfield in "
1066 2421 sgarg
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1067 2663 sgarg
                                     + e.getMessage());
1068 2421 sgarg
           id = -1;
1069
       }
1070 2424 sgarg
1071
       returnfield_id = id;
1072
       return count;
1073 2087 tao
   }
1074 2043 sgarg
1075
1076 2087 tao
    /*
1077
     * A method to add return field to return doclist hash table
1078
     */
1079 2421 sgarg
    private Hashtable addReturnfield(Hashtable docListResult,
1080 2087 tao
                                      QuerySpecification qspec,
1081
                                      String user, String[]groups,
1082
                                      DBConnection dbconn, boolean useXMLIndex )
1083
                                      throws Exception
1084
    {
1085
      PreparedStatement pstmt = null;
1086
      ResultSet rs = null;
1087
      String docid = null;
1088
      String fieldname = null;
1089
      String fielddata = null;
1090
      String relation = null;
1091
1092
      if (qspec.containsExtendedSQL())
1093
      {
1094
        qspec.setUserName(user);
1095
        qspec.setGroup(groups);
1096
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1097
        Vector results = new Vector();
1098
        Enumeration keylist = docListResult.keys();
1099
        StringBuffer doclist = new StringBuffer();
1100
        Vector parentidList = new Vector();
1101
        Hashtable returnFieldValue = new Hashtable();
1102
        while (keylist.hasMoreElements())
1103
        {
1104
          doclist.append("'");
1105
          doclist.append((String) keylist.nextElement());
1106
          doclist.append("',");
1107
        }
1108
        if (doclist.length() > 0)
1109
        {
1110
          Hashtable controlPairs = new Hashtable();
1111
          double extendedQueryStart = System.currentTimeMillis() / 1000;
1112
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1113
          // check if user has permission to see the return field data
1114
          String accessControlSQL =
1115
                 qspec.printAccessControlSQLForReturnField(doclist.toString());
1116
          pstmt = dbconn.prepareStatement(accessControlSQL);
1117
          //increase dbconnection usage count
1118
          dbconn.increaseUsageCount(1);
1119
          pstmt.execute();
1120
          rs = pstmt.getResultSet();
1121
          boolean tableHasRows = rs.next();
1122
          while (tableHasRows)
1123
          {
1124
            long startNodeId = rs.getLong(1);
1125
            long endNodeId = rs.getLong(2);
1126
            controlPairs.put(new Long(startNodeId), new Long(endNodeId));
1127
            tableHasRows = rs.next();
1128
          }
1129
1130
           double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
1131 2663 sgarg
           logMetacat.info( "Time for execute access extended query: "
1132
                          + (extendedAccessQueryEnd - extendedQueryStart));
1133 2087 tao
1134
           String extendedQuery =
1135
               qspec.printExtendedSQL(doclist.toString(), controlPairs, useXMLIndex);
1136 2663 sgarg
           logMetacat.warn("Extended query: " + extendedQuery);
1137 2376 sgarg
1138 2474 sgarg
           if(extendedQuery != null){
1139
               pstmt = dbconn.prepareStatement(extendedQuery);
1140
               //increase dbconnection usage count
1141
               dbconn.increaseUsageCount(1);
1142
               pstmt.execute();
1143
               rs = pstmt.getResultSet();
1144
               double extendedQueryEnd = System.currentTimeMillis() / 1000;
1145 2663 sgarg
               logMetacat.info(
1146 2474 sgarg
                   "Time for execute extended query: "
1147 2663 sgarg
                   + (extendedQueryEnd - extendedQueryStart));
1148 2474 sgarg
               tableHasRows = rs.next();
1149
               while (tableHasRows) {
1150
                   ReturnFieldValue returnValue = new ReturnFieldValue();
1151
                   docid = rs.getString(1).trim();
1152
                   fieldname = rs.getString(2);
1153
                   fielddata = rs.getString(3);
1154
                   fielddata = MetaCatUtil.normalize(fielddata);
1155
                   String parentId = rs.getString(4);
1156
                   StringBuffer value = new StringBuffer();
1157 2043 sgarg
1158 2474 sgarg
                   // if xml_index is used, there would be just one record per nodeid
1159
                   // as xml_index just keeps one entry for each path
1160
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1161
                       // don't need to merger nodedata
1162
                       value.append("<param name=\"");
1163
                       value.append(fieldname);
1164
                       value.append("\">");
1165
                       value.append(fielddata);
1166
                       value.append("</param>");
1167
                       //set returnvalue
1168
                       returnValue.setDocid(docid);
1169
                       returnValue.setFieldValue(fielddata);
1170
                       returnValue.setXMLFieldValue(value.toString());
1171
                       // Store it in hastable
1172
                       putInArray(parentidList, parentId, returnValue);
1173
                   }
1174
                   else {
1175
                       // need to merge nodedata if they have same parent id and
1176
                       // node type is text
1177
                       fielddata = (String) ( (ReturnFieldValue)
1178
                                             getArrayValue(
1179
                           parentidList, parentId)).getFieldValue()
1180
                           + fielddata;
1181
                       value.append("<param name=\"");
1182
                       value.append(fieldname);
1183
                       value.append("\">");
1184
                       value.append(fielddata);
1185
                       value.append("</param>");
1186
                       returnValue.setDocid(docid);
1187
                       returnValue.setFieldValue(fielddata);
1188
                       returnValue.setXMLFieldValue(value.toString());
1189
                       // remove the old return value from paretnidList
1190
                       parentidList.remove(parentId);
1191
                       // store the new return value in parentidlit
1192
                       putInArray(parentidList, parentId, returnValue);
1193
                   }
1194
                   tableHasRows = rs.next();
1195
               } //while
1196
               rs.close();
1197
               pstmt.close();
1198 2043 sgarg
1199 2474 sgarg
               // put the merger node data info into doclistReult
1200
               Enumeration xmlFieldValue = (getElements(parentidList)).
1201
                   elements();
1202
               while (xmlFieldValue.hasMoreElements()) {
1203
                   ReturnFieldValue object =
1204
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1205
                   docid = object.getDocid();
1206
                   if (docListResult.containsKey(docid)) {
1207
                       String removedelement = (String) docListResult.
1208
                           remove(docid);
1209
                       docListResult.
1210
                           put(docid,
1211
                               removedelement + object.getXMLFieldValue());
1212
                   }
1213
                   else {
1214
                       docListResult.put(docid, object.getXMLFieldValue());
1215
                   }
1216
               } //while
1217
               double docListResultEnd = System.currentTimeMillis() / 1000;
1218 2663 sgarg
               logMetacat.warn(
1219 2474 sgarg
                   "Time for prepare doclistresult after"
1220
                   + " execute extended query: "
1221 2663 sgarg
                   + (docListResultEnd - extendedQueryEnd));
1222 2474 sgarg
           }
1223
1224
           // get attribures return
1225
           docListResult = getAttributeValueForReturn(qspec,
1226
                           docListResult, doclist.toString(), useXMLIndex);
1227 2087 tao
       }//if doclist lenght is great than zero
1228 2043 sgarg
1229 2087 tao
     }//if has extended query
1230 2043 sgarg
1231 2087 tao
      return docListResult;
1232
    }//addReturnfield
1233 2043 sgarg
1234 2087 tao
    /*
1235
    * A method to add relationship to return doclist hash table
1236
    */
1237
   private Hashtable addRelationship(Hashtable docListResult,
1238
                                     QuerySpecification qspec,
1239
                                     DBConnection dbconn, boolean useXMLIndex )
1240
                                     throws Exception
1241
  {
1242
    PreparedStatement pstmt = null;
1243
    ResultSet rs = null;
1244
    StringBuffer document = null;
1245
    double startRelation = System.currentTimeMillis() / 1000;
1246
    Enumeration docidkeys = docListResult.keys();
1247
    while (docidkeys.hasMoreElements())
1248
    {
1249
      //String connstring =
1250
      // "metacat://"+util.getOption("server")+"?docid=";
1251
      String connstring = "%docid=";
1252
      String docidkey = (String) docidkeys.nextElement();
1253
      pstmt = dbconn.prepareStatement(QuerySpecification
1254
                      .printRelationSQL(docidkey));
1255
      pstmt.execute();
1256
      rs = pstmt.getResultSet();
1257
      boolean tableHasRows = rs.next();
1258
      while (tableHasRows)
1259
      {
1260
        String sub = rs.getString(1);
1261
        String rel = rs.getString(2);
1262
        String obj = rs.getString(3);
1263
        String subDT = rs.getString(4);
1264
        String objDT = rs.getString(5);
1265 2043 sgarg
1266 2087 tao
        document = new StringBuffer();
1267
        document.append("<triple>");
1268
        document.append("<subject>").append(MetaCatUtil.normalize(sub));
1269
        document.append("</subject>");
1270
        if (subDT != null)
1271
        {
1272
          document.append("<subjectdoctype>").append(subDT);
1273
          document.append("</subjectdoctype>");
1274
        }
1275
        document.append("<relationship>").append(MetaCatUtil.normalize(rel));
1276
        document.append("</relationship>");
1277
        document.append("<object>").append(MetaCatUtil.normalize(obj));
1278
        document.append("</object>");
1279
        if (objDT != null)
1280
        {
1281
          document.append("<objectdoctype>").append(objDT);
1282
          document.append("</objectdoctype>");
1283
        }
1284
        document.append("</triple>");
1285 2043 sgarg
1286 2087 tao
        String removedelement = (String) docListResult.remove(docidkey);
1287
        docListResult.put(docidkey, removedelement+ document.toString());
1288
        tableHasRows = rs.next();
1289
      }//while
1290
      rs.close();
1291
      pstmt.close();
1292
    }//while
1293
    double endRelation = System.currentTimeMillis() / 1000;
1294 2663 sgarg
    logMetacat.info("Time for adding relation to docListResult: "
1295
                             + (endRelation - startRelation));
1296 2043 sgarg
1297 2087 tao
    return docListResult;
1298
  }//addRelation
1299
1300
  /**
1301
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1302
   * string as a param instead of a hashtable.
1303
   *
1304
   * @param xmlquery a string representing a query.
1305
   */
1306
   private  String transformQuery(String xmlquery)
1307
   {
1308
     xmlquery = xmlquery.trim();
1309
     int index = xmlquery.indexOf("?>");
1310
     if (index != -1)
1311
     {
1312
       return xmlquery.substring(index + 2, xmlquery.length());
1313
     }
1314
     else
1315
     {
1316
       return xmlquery;
1317
     }
1318
   }
1319
1320
1321 2075 jones
    /*
1322
     * A method to search if Vector contains a particular key string
1323
     */
1324
    private boolean containsKey(Vector parentidList, String parentId)
1325
    {
1326 2043 sgarg
1327 2075 jones
        Vector tempVector = null;
1328 2043 sgarg
1329 2075 jones
        for (int count = 0; count < parentidList.size(); count++) {
1330
            tempVector = (Vector) parentidList.get(count);
1331 2360 sgarg
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1332 2075 jones
        }
1333
        return false;
1334 2043 sgarg
    }
1335
1336 2075 jones
    /*
1337
     * A method to put key and value in Vector
1338
     */
1339
    private void putInArray(Vector parentidList, String key,
1340
            ReturnFieldValue value)
1341
    {
1342 2043 sgarg
1343 2075 jones
        Vector tempVector = null;
1344 2043 sgarg
1345 2075 jones
        for (int count = 0; count < parentidList.size(); count++) {
1346
            tempVector = (Vector) parentidList.get(count);
1347 2043 sgarg
1348 2075 jones
            if (key.compareTo((String) tempVector.get(0)) == 0) {
1349
                tempVector.remove(1);
1350
                tempVector.add(1, value);
1351
                return;
1352
            }
1353
        }
1354 2043 sgarg
1355 2075 jones
        tempVector = new Vector();
1356
        tempVector.add(0, key);
1357
        tempVector.add(1, value);
1358
        parentidList.add(tempVector);
1359
        return;
1360 2043 sgarg
    }
1361
1362 2075 jones
    /*
1363
     * A method to get value in Vector given a key
1364
     */
1365
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1366 1353 tao
    {
1367 2043 sgarg
1368 2075 jones
        Vector tempVector = null;
1369 2043 sgarg
1370 2075 jones
        for (int count = 0; count < parentidList.size(); count++) {
1371
            tempVector = (Vector) parentidList.get(count);
1372 2043 sgarg
1373 2075 jones
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1374
                    .get(1); }
1375
        }
1376
        return null;
1377 2045 tao
    }
1378 436 berkley
1379 2075 jones
    /*
1380
     * A method to get enumeration of all values in Vector
1381
     */
1382
    private Vector getElements(Vector parentidList)
1383 342 berkley
    {
1384 2446 sgarg
        Vector enumVector = new Vector();
1385 2075 jones
        Vector tempVector = null;
1386 2043 sgarg
1387 2075 jones
        for (int count = 0; count < parentidList.size(); count++) {
1388
            tempVector = (Vector) parentidList.get(count);
1389 744 jones
1390 2446 sgarg
            enumVector.add(tempVector.get(1));
1391 744 jones
        }
1392 2446 sgarg
        return enumVector;
1393 372 berkley
    }
1394 2043 sgarg
1395 2075 jones
    /*
1396
     * A method to return search result after running a query which return
1397
     * field have attribue
1398
     */
1399
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
1400
            Hashtable docInformationList, String docList, boolean useXMLIndex)
1401 743 jones
    {
1402 2075 jones
        StringBuffer XML = null;
1403
        String sql = null;
1404
        DBConnection dbconn = null;
1405
        PreparedStatement pstmt = null;
1406
        ResultSet rs = null;
1407
        int serialNumber = -1;
1408
        boolean tableHasRows = false;
1409 2043 sgarg
1410 2075 jones
        //check the parameter
1411
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
1412 2043 sgarg
1413 2075 jones
        // if has attribute as return field
1414 2473 cjones
        if (squery.containsAttributeReturnField()) {
1415 2075 jones
            sql = squery.printAttributeQuery(docList, useXMLIndex);
1416
            try {
1417
                dbconn = DBConnectionPool
1418
                        .getDBConnection("DBQuery.getAttributeValue");
1419
                serialNumber = dbconn.getCheckOutSerialNumber();
1420
                pstmt = dbconn.prepareStatement(sql);
1421
                pstmt.execute();
1422
                rs = pstmt.getResultSet();
1423
                tableHasRows = rs.next();
1424
                while (tableHasRows) {
1425
                    String docid = rs.getString(1).trim();
1426
                    String fieldname = rs.getString(2);
1427
                    String fielddata = rs.getString(3);
1428
                    String attirbuteName = rs.getString(4);
1429
                    XML = new StringBuffer();
1430 2043 sgarg
1431 2075 jones
                    XML.append("<param name=\"");
1432
                    XML.append(fieldname);
1433 2428 cjones
                    XML.append("/");
1434 2075 jones
                    XML.append(QuerySpecification.ATTRIBUTESYMBOL);
1435
                    XML.append(attirbuteName);
1436
                    XML.append("\">");
1437
                    XML.append(fielddata);
1438
                    XML.append("</param>");
1439
                    tableHasRows = rs.next();
1440 2043 sgarg
1441 2075 jones
                    if (docInformationList.containsKey(docid)) {
1442
                        String removedelement = (String) docInformationList
1443
                                .remove(docid);
1444
                        docInformationList.put(docid, removedelement
1445
                                + XML.toString());
1446
                    } else {
1447
                        docInformationList.put(docid, XML.toString());
1448
                    }
1449
                }//while
1450
                rs.close();
1451
                pstmt.close();
1452
            } catch (Exception se) {
1453 2663 sgarg
                logMetacat.error(
1454 2075 jones
                        "Error in DBQuery.getAttributeValue1: "
1455 2663 sgarg
                                + se.getMessage());
1456 2075 jones
            } finally {
1457
                try {
1458
                    pstmt.close();
1459
                }//try
1460
                catch (SQLException sqlE) {
1461 2663 sgarg
                    logMetacat.error(
1462 2075 jones
                            "Error in DBQuery.getAttributeValue2: "
1463 2663 sgarg
                                    + sqlE.getMessage());
1464 2075 jones
                }//catch
1465
                finally {
1466
                    DBConnectionPool.returnDBConnection(dbconn, serialNumber);
1467
                }//finally
1468
            }//finally
1469
        }//if
1470
        return docInformationList;
1471 2043 sgarg
1472 372 berkley
    }
1473 2043 sgarg
1474 2075 jones
    /*
1475
     * A method to create a query to get owner's docid list
1476
     */
1477
    private String getOwnerQuery(String owner)
1478 372 berkley
    {
1479 2075 jones
        if (owner != null) {
1480
            owner = owner.toLowerCase();
1481
        }
1482
        StringBuffer self = new StringBuffer();
1483 2043 sgarg
1484 2075 jones
        self.append("SELECT docid,docname,doctype,");
1485
        self.append("date_created, date_updated, rev ");
1486
        self.append("FROM xml_documents WHERE docid IN (");
1487
        self.append("(");
1488
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1489
        self.append("nodedata LIKE '%%%' ");
1490
        self.append(") \n");
1491
        self.append(") ");
1492
        self.append(" AND (");
1493
        self.append(" lower(user_owner) = '" + owner + "'");
1494
        self.append(") ");
1495
        return self.toString();
1496 342 berkley
    }
1497 2043 sgarg
1498 2075 jones
    /**
1499
     * format a structured query as an XML document that conforms to the
1500
     * pathquery.dtd and is appropriate for submission to the DBQuery
1501
     * structured query engine
1502 2087 tao
     *
1503 2075 jones
     * @param params The list of parameters that should be included in the
1504
     *            query
1505
     */
1506
    public static String createSQuery(Hashtable params)
1507 342 berkley
    {
1508 2075 jones
        StringBuffer query = new StringBuffer();
1509
        Enumeration elements;
1510
        Enumeration keys;
1511
        String filterDoctype = null;
1512
        String casesensitive = null;
1513
        String searchmode = null;
1514
        Object nextkey;
1515
        Object nextelement;
1516
        //add the xml headers
1517
        query.append("<?xml version=\"1.0\"?>\n");
1518 2091 tao
        query.append("<pathquery version=\"1.2\">\n");
1519 372 berkley
1520 2091 tao
1521
1522 2075 jones
        if (params.containsKey("meta_file_id")) {
1523
            query.append("<meta_file_id>");
1524
            query.append(((String[]) params.get("meta_file_id"))[0]);
1525
            query.append("</meta_file_id>");
1526 372 berkley
        }
1527 2043 sgarg
1528 2075 jones
        if (params.containsKey("returndoctype")) {
1529
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1530
            for (int i = 0; i < returnDoctypes.length; i++) {
1531
                String doctype = (String) returnDoctypes[i];
1532 181 jones
1533 2075 jones
                if (!doctype.equals("any") && !doctype.equals("ANY")
1534
                        && !doctype.equals("")) {
1535
                    query.append("<returndoctype>").append(doctype);
1536
                    query.append("</returndoctype>");
1537
                }
1538
            }
1539
        }
1540 181 jones
1541 2075 jones
        if (params.containsKey("filterdoctype")) {
1542
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1543
            for (int i = 0; i < filterDoctypes.length; i++) {
1544
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1545
                query.append("</filterdoctype>");
1546
            }
1547
        }
1548 181 jones
1549 2075 jones
        if (params.containsKey("returnfield")) {
1550
            String[] returnfield = ((String[]) params.get("returnfield"));
1551
            for (int i = 0; i < returnfield.length; i++) {
1552
                query.append("<returnfield>").append(returnfield[i]);
1553
                query.append("</returnfield>");
1554
            }
1555
        }
1556 2043 sgarg
1557 2075 jones
        if (params.containsKey("owner")) {
1558
            String[] owner = ((String[]) params.get("owner"));
1559
            for (int i = 0; i < owner.length; i++) {
1560
                query.append("<owner>").append(owner[i]);
1561
                query.append("</owner>");
1562
            }
1563
        }
1564 181 jones
1565 2075 jones
        if (params.containsKey("site")) {
1566
            String[] site = ((String[]) params.get("site"));
1567
            for (int i = 0; i < site.length; i++) {
1568
                query.append("<site>").append(site[i]);
1569
                query.append("</site>");
1570
            }
1571
        }
1572 2043 sgarg
1573 2075 jones
        //allows the dynamic switching of boolean operators
1574
        if (params.containsKey("operator")) {
1575
            query.append("<querygroup operator=\""
1576
                    + ((String[]) params.get("operator"))[0] + "\">");
1577
        } else { //the default operator is UNION
1578
            query.append("<querygroup operator=\"UNION\">");
1579
        }
1580 940 tao
1581 2075 jones
        if (params.containsKey("casesensitive")) {
1582
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1583
        } else {
1584
            casesensitive = "false";
1585
        }
1586 2043 sgarg
1587 2075 jones
        if (params.containsKey("searchmode")) {
1588
            searchmode = ((String[]) params.get("searchmode"))[0];
1589
        } else {
1590
            searchmode = "contains";
1591 940 tao
        }
1592
1593 2075 jones
        //anyfield is a special case because it does a
1594
        //free text search. It does not have a <pathexpr>
1595
        //tag. This allows for a free text search within the structured
1596
        //query. This is useful if the INTERSECT operator is used.
1597
        if (params.containsKey("anyfield")) {
1598
            String[] anyfield = ((String[]) params.get("anyfield"));
1599
            //allow for more than one value for anyfield
1600
            for (int i = 0; i < anyfield.length; i++) {
1601
                if (!anyfield[i].equals("")) {
1602
                    query.append("<queryterm casesensitive=\"" + casesensitive
1603
                            + "\" " + "searchmode=\"" + searchmode
1604
                            + "\"><value>" + anyfield[i]
1605
                            + "</value></queryterm>");
1606
                }
1607
            }
1608 940 tao
        }
1609 2043 sgarg
1610 2075 jones
        //this while loop finds the rest of the parameters
1611
        //and attempts to query for the field specified
1612
        //by the parameter.
1613
        elements = params.elements();
1614
        keys = params.keys();
1615
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1616
            nextkey = keys.nextElement();
1617
            nextelement = elements.nextElement();
1618 2043 sgarg
1619 2075 jones
            //make sure we aren't querying for any of these
1620
            //parameters since the are already in the query
1621
            //in one form or another.
1622
            Vector ignoredParams = new Vector();
1623
            ignoredParams.add("returndoctype");
1624
            ignoredParams.add("filterdoctype");
1625
            ignoredParams.add("action");
1626
            ignoredParams.add("qformat");
1627
            ignoredParams.add("anyfield");
1628
            ignoredParams.add("returnfield");
1629
            ignoredParams.add("owner");
1630
            ignoredParams.add("site");
1631
            ignoredParams.add("operator");
1632 2091 tao
            ignoredParams.add("sessionid");
1633 3211 berkley
            ignoredParams.add("pagesize");
1634
            ignoredParams.add("pagestart");
1635 2043 sgarg
1636 2075 jones
            // Also ignore parameters listed in the properties file
1637
            // so that they can be passed through to stylesheets
1638
            String paramsToIgnore = MetaCatUtil
1639
                    .getOption("query.ignored.params");
1640
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1641
            while (st.hasMoreTokens()) {
1642
                ignoredParams.add(st.nextToken());
1643
            }
1644
            if (!ignoredParams.contains(nextkey.toString())) {
1645
                //allow for more than value per field name
1646
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1647
                    if (!((String[]) nextelement)[i].equals("")) {
1648
                        query.append("<queryterm casesensitive=\""
1649
                                + casesensitive + "\" " + "searchmode=\""
1650 2087 tao
                                + searchmode + "\">" + "<value>" +
1651 2075 jones
                                //add the query value
1652
                                ((String[]) nextelement)[i]
1653 2087 tao
                                + "</value><pathexpr>" +
1654 2075 jones
                                //add the path to query by
1655
                                nextkey.toString() + "</pathexpr></queryterm>");
1656
                    }
1657
                }
1658
            }
1659
        }
1660
        query.append("</querygroup></pathquery>");
1661
        //append on the end of the xml and return the result as a string
1662
        return query.toString();
1663
    }
1664 2043 sgarg
1665 2075 jones
    /**
1666
     * format a simple free-text value query as an XML document that conforms
1667
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1668
     * structured query engine
1669 2087 tao
     *
1670 2075 jones
     * @param value the text string to search for in the xml catalog
1671
     * @param doctype the type of documents to include in the result set -- use
1672
     *            "any" or "ANY" for unfiltered result sets
1673
     */
1674
    public static String createQuery(String value, String doctype)
1675 1292 tao
    {
1676 2075 jones
        StringBuffer xmlquery = new StringBuffer();
1677
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1678
        xmlquery.append("<pathquery version=\"1.0\">");
1679 2043 sgarg
1680 2075 jones
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1681
            xmlquery.append("<returndoctype>");
1682
            xmlquery.append(doctype).append("</returndoctype>");
1683
        }
1684 2043 sgarg
1685 2075 jones
        xmlquery.append("<querygroup operator=\"UNION\">");
1686
        //chad added - 8/14
1687
        //the if statement allows a query to gracefully handle a null
1688
        //query. Without this if a nullpointerException is thrown.
1689
        if (!value.equals("")) {
1690
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1691
            xmlquery.append("searchmode=\"contains\">");
1692
            xmlquery.append("<value>").append(value).append("</value>");
1693
            xmlquery.append("</queryterm>");
1694 1217 tao
        }
1695 2075 jones
        xmlquery.append("</querygroup>");
1696
        xmlquery.append("</pathquery>");
1697 2043 sgarg
1698 2075 jones
        return (xmlquery.toString());
1699
    }
1700 2043 sgarg
1701 2075 jones
    /**
1702
     * format a simple free-text value query as an XML document that conforms
1703
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1704
     * structured query engine
1705 2087 tao
     *
1706 2075 jones
     * @param value the text string to search for in the xml catalog
1707
     */
1708
    public static String createQuery(String value)
1709 940 tao
    {
1710 2075 jones
        return createQuery(value, "any");
1711 940 tao
    }
1712 2043 sgarg
1713 2075 jones
    /**
1714
     * Check for "READ" permission on @docid for @user and/or @group from DB
1715
     * connection
1716
     */
1717
    private boolean hasPermission(String user, String[] groups, String docid)
1718
            throws SQLException, Exception
1719 940 tao
    {
1720 2075 jones
        // Check for READ permission on @docid for @user and/or @groups
1721
        PermissionController controller = new PermissionController(docid);
1722
        return controller.hasPermission(user, groups,
1723
                AccessControlInterface.READSTRING);
1724
    }
1725 2043 sgarg
1726 2075 jones
    /**
1727
     * Get all docIds list for a data packadge
1728 2087 tao
     *
1729 2075 jones
     * @param dataPackageDocid, the string in docId field of xml_relation table
1730
     */
1731
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1732 940 tao
    {
1733 2075 jones
        DBConnection dbConn = null;
1734
        int serialNumber = -1;
1735
        Vector docIdList = new Vector();//return value
1736
        PreparedStatement pStmt = null;
1737
        ResultSet rs = null;
1738
        String docIdInSubjectField = null;
1739
        String docIdInObjectField = null;
1740 2043 sgarg
1741 2075 jones
        // Check the parameter
1742
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1743 940 tao
1744 2075 jones
        //the query stirng
1745
        String query = "SELECT subject, object from xml_relation where docId = ?";
1746
        try {
1747
            dbConn = DBConnectionPool
1748
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1749
            serialNumber = dbConn.getCheckOutSerialNumber();
1750
            pStmt = dbConn.prepareStatement(query);
1751
            //bind the value to query
1752
            pStmt.setString(1, dataPackageDocid);
1753 2043 sgarg
1754 2075 jones
            //excute the query
1755
            pStmt.execute();
1756
            //get the result set
1757
            rs = pStmt.getResultSet();
1758
            //process the result
1759
            while (rs.next()) {
1760
                //In order to get the whole docIds in a data packadge,
1761
                //we need to put the docIds of subject and object field in
1762
                // xml_relation
1763
                //into the return vector
1764
                docIdInSubjectField = rs.getString(1);//the result docId in
1765
                                                      // subject field
1766
                docIdInObjectField = rs.getString(2);//the result docId in
1767
                                                     // object field
1768 940 tao
1769 2075 jones
                //don't put the duplicate docId into the vector
1770
                if (!docIdList.contains(docIdInSubjectField)) {
1771
                    docIdList.add(docIdInSubjectField);
1772
                }
1773 2043 sgarg
1774 2075 jones
                //don't put the duplicate docId into the vector
1775
                if (!docIdList.contains(docIdInObjectField)) {
1776
                    docIdList.add(docIdInObjectField);
1777
                }
1778
            }//while
1779
            //close the pStmt
1780
            pStmt.close();
1781
        }//try
1782
        catch (SQLException e) {
1783 2663 sgarg
            logMetacat.error("Error in getDocidListForDataPackage: "
1784
                    + e.getMessage());
1785 2075 jones
        }//catch
1786
        finally {
1787
            try {
1788
                pStmt.close();
1789
            }//try
1790
            catch (SQLException ee) {
1791 2663 sgarg
                logMetacat.error(
1792 2075 jones
                        "Error in getDocidListForDataPackage: "
1793 2663 sgarg
                                + ee.getMessage());
1794 2075 jones
            }//catch
1795
            finally {
1796
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1797
            }//fianlly
1798
        }//finally
1799
        return docIdList;
1800
    }//getCurrentDocidListForDataPackadge()
1801 2043 sgarg
1802 2075 jones
    /**
1803
     * Get all docIds list for a data packadge
1804 2087 tao
     *
1805 2075 jones
     * @param dataPackageDocid, the string in docId field of xml_relation table
1806
     */
1807 2641 tao
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1808 940 tao
    {
1809 2043 sgarg
1810 2075 jones
        Vector docIdList = new Vector();//return value
1811
        Vector tripleList = null;
1812
        String xml = null;
1813 2043 sgarg
1814 2075 jones
        // Check the parameter
1815 2641 tao
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1816 2043 sgarg
1817 2075 jones
        try {
1818
            //initial a documentImpl object
1819 2641 tao
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1820 2075 jones
            //transfer to documentImpl object to string
1821
            xml = packageDocument.toString();
1822 2043 sgarg
1823 2075 jones
            //create a tripcollection object
1824
            TripleCollection tripleForPackage = new TripleCollection(
1825
                    new StringReader(xml));
1826
            //get the vetor of triples
1827
            tripleList = tripleForPackage.getCollection();
1828 2043 sgarg
1829 2075 jones
            for (int i = 0; i < tripleList.size(); i++) {
1830
                //put subject docid into docIdlist without duplicate
1831
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1832
                        .getSubject())) {
1833
                    //put subject docid into docIdlist
1834
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1835
                }
1836
                //put object docid into docIdlist without duplicate
1837
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1838
                        .getObject())) {
1839
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1840
                }
1841
            }//for
1842
        }//try
1843
        catch (Exception e) {
1844 2663 sgarg
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1845
                    + e.getMessage());
1846 2075 jones
        }//catch
1847 2043 sgarg
1848 2075 jones
        // return result
1849
        return docIdList;
1850
    }//getDocidListForPackageInXMLRevisions()
1851 2043 sgarg
1852 2075 jones
    /**
1853
     * Check if the docId is a data packadge id. If the id is a data packadage
1854
     * id, it should be store in the docId fields in xml_relation table. So we
1855
     * can use a query to get the entries which the docId equals the given
1856
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1857
     * it is.
1858 2087 tao
     *
1859 2075 jones
     * @param docId, the id need to be checked
1860
     */
1861
    private boolean isDataPackageId(String docId)
1862 940 tao
    {
1863 2075 jones
        boolean result = false;
1864
        PreparedStatement pStmt = null;
1865
        ResultSet rs = null;
1866
        String query = "SELECT docId from xml_relation where docId = ?";
1867
        DBConnection dbConn = null;
1868
        int serialNumber = -1;
1869
        try {
1870
            dbConn = DBConnectionPool
1871
                    .getDBConnection("DBQuery.isDataPackageId");
1872
            serialNumber = dbConn.getCheckOutSerialNumber();
1873
            pStmt = dbConn.prepareStatement(query);
1874
            //bind the value to query
1875
            pStmt.setString(1, docId);
1876
            //execute the query
1877
            pStmt.execute();
1878
            rs = pStmt.getResultSet();
1879
            //process the result
1880
            if (rs.next()) //There are some records for the id in docId fields
1881
            {
1882
                result = true;//It is a data packadge id
1883
            }
1884
            pStmt.close();
1885
        }//try
1886
        catch (SQLException e) {
1887 2663 sgarg
            logMetacat.error("Error in isDataPackageId: "
1888
                    + e.getMessage());
1889 2075 jones
        } finally {
1890
            try {
1891
                pStmt.close();
1892
            }//try
1893
            catch (SQLException ee) {
1894 2663 sgarg
                logMetacat.error("Error in isDataPackageId: "
1895
                        + ee.getMessage());
1896 2075 jones
            }//catch
1897
            finally {
1898
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1899
            }//finally
1900
        }//finally
1901
        return result;
1902
    }//isDataPackageId()
1903 2043 sgarg
1904 2075 jones
    /**
1905
     * Check if the user has the permission to export data package
1906 2087 tao
     *
1907 2075 jones
     * @param conn, the connection
1908
     * @param docId, the id need to be checked
1909
     * @param user, the name of user
1910
     * @param groups, the user's group
1911
     */
1912
    private boolean hasPermissionToExportPackage(String docId, String user,
1913
            String[] groups) throws Exception
1914 940 tao
    {
1915 2075 jones
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1916
        return DocumentImpl.hasReadPermission(user, groups, docId);
1917
    }
1918 2043 sgarg
1919 2075 jones
    /**
1920
     * Get the current Rev for a docid in xml_documents table
1921 2087 tao
     *
1922 2075 jones
     * @param docId, the id need to get version numb If the return value is -5,
1923
     *            means no value in rev field for this docid
1924
     */
1925
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1926
            throws SQLException
1927
    {
1928
        int rev = -5;
1929
        PreparedStatement pStmt = null;
1930
        ResultSet rs = null;
1931
        String query = "SELECT rev from xml_documents where docId = ?";
1932
        DBConnection dbConn = null;
1933
        int serialNumber = -1;
1934
        try {
1935
            dbConn = DBConnectionPool
1936
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1937
            serialNumber = dbConn.getCheckOutSerialNumber();
1938
            pStmt = dbConn.prepareStatement(query);
1939
            //bind the value to query
1940
            pStmt.setString(1, docId);
1941
            //execute the query
1942
            pStmt.execute();
1943
            rs = pStmt.getResultSet();
1944
            //process the result
1945
            if (rs.next()) //There are some records for rev
1946
            {
1947
                rev = rs.getInt(1);
1948
                ;//It is the version for given docid
1949
            } else {
1950
                rev = -5;
1951
            }
1952 2043 sgarg
1953 1292 tao
        }//try
1954 2075 jones
        catch (SQLException e) {
1955 2663 sgarg
            logMetacat.error(
1956 2075 jones
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1957 2663 sgarg
                            + e.getMessage());
1958 2075 jones
            throw e;
1959 1292 tao
        }//catch
1960 2075 jones
        finally {
1961
            try {
1962
                pStmt.close();
1963
            }//try
1964
            catch (SQLException ee) {
1965 2663 sgarg
                logMetacat.error(
1966 2075 jones
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1967 2663 sgarg
                                + ee.getMessage());
1968 2075 jones
            }//catch
1969
            finally {
1970
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1971
            }//finally
1972
        }//finally
1973
        return rev;
1974
    }//getCurrentRevFromXMLDoumentsTable
1975 2043 sgarg
1976 2075 jones
    /**
1977
     * put a doc into a zip output stream
1978 2087 tao
     *
1979 2075 jones
     * @param docImpl, docmentImpl object which will be sent to zip output
1980
     *            stream
1981
     * @param zipOut, zip output stream which the docImpl will be put
1982
     * @param packageZipEntry, the zip entry name for whole package
1983
     */
1984
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1985
            ZipOutputStream zipOut, String packageZipEntry)
1986
            throws ClassNotFoundException, IOException, SQLException,
1987
            McdbException, Exception
1988
    {
1989
        byte[] byteString = null;
1990
        ZipEntry zEntry = null;
1991 2043 sgarg
1992 2075 jones
        byteString = docImpl.toString().getBytes();
1993
        //use docId as the zip entry's name
1994
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1995
                + docImpl.getDocID());
1996
        zEntry.setSize(byteString.length);
1997
        zipOut.putNextEntry(zEntry);
1998
        zipOut.write(byteString, 0, byteString.length);
1999
        zipOut.closeEntry();
2000 2043 sgarg
2001 2075 jones
    }//addDocToZipOutputStream()
2002 940 tao
2003 2075 jones
    /**
2004
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
2005
     * only inlcudes current version. If a DocumentImple object couldn't find
2006
     * for a docid, then the String of this docid was added to vetor rather
2007
     * than DocumentImple object.
2008 2087 tao
     *
2009 2075 jones
     * @param docIdList, a vetor hold a docid list for a data package. In
2010
     *            docid, there is not version number in it.
2011
     */
2012 2043 sgarg
2013 2075 jones
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
2014
            throws McdbException, Exception
2015 940 tao
    {
2016 2075 jones
        //Connection dbConn=null;
2017
        Vector documentImplList = new Vector();
2018
        int rev = 0;
2019 2043 sgarg
2020 2075 jones
        // Check the parameter
2021
        if (docIdList.isEmpty()) { return documentImplList; }//if
2022 2043 sgarg
2023 2075 jones
        //for every docid in vector
2024
        for (int i = 0; i < docIdList.size(); i++) {
2025
            try {
2026
                //get newest version for this docId
2027
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
2028
                        .elementAt(i));
2029 940 tao
2030 2075 jones
                // There is no record for this docId in xml_documents table
2031
                if (rev == -5) {
2032
                    // Rather than put DocumentImple object, put a String
2033
                    // Object(docid)
2034
                    // into the documentImplList
2035
                    documentImplList.add((String) docIdList.elementAt(i));
2036
                    // Skip other code
2037
                    continue;
2038
                }
2039 2043 sgarg
2040 2075 jones
                String docidPlusVersion = ((String) docIdList.elementAt(i))
2041
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
2042 2043 sgarg
2043 2075 jones
                //create new documentImpl object
2044
                DocumentImpl documentImplObject = new DocumentImpl(
2045
                        docidPlusVersion);
2046
                //add them to vector
2047
                documentImplList.add(documentImplObject);
2048
            }//try
2049
            catch (Exception e) {
2050 2663 sgarg
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
2051
                        + e.getMessage());
2052 2075 jones
                // continue the for loop
2053
                continue;
2054
            }
2055
        }//for
2056
        return documentImplList;
2057
    }
2058 2043 sgarg
2059 2075 jones
    /**
2060
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2061
     * object couldn't find for a docid, then the String of this docid was
2062
     * added to vetor rather than DocumentImple object.
2063 2087 tao
     *
2064 2075 jones
     * @param docIdList, a vetor hold a docid list for a data package. In
2065
     *            docid, t here is version number in it.
2066
     */
2067
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2068
    {
2069
        //Connection dbConn=null;
2070
        Vector documentImplList = new Vector();
2071
        String siteCode = null;
2072
        String uniqueId = null;
2073
        int rev = 0;
2074 2043 sgarg
2075 2075 jones
        // Check the parameter
2076
        if (docIdList.isEmpty()) { return documentImplList; }//if
2077 2043 sgarg
2078 2075 jones
        //for every docid in vector
2079
        for (int i = 0; i < docIdList.size(); i++) {
2080 2043 sgarg
2081 2075 jones
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2082
2083
            try {
2084
                //create new documentImpl object
2085
                DocumentImpl documentImplObject = new DocumentImpl(
2086
                        docidPlusVersion);
2087
                //add them to vector
2088
                documentImplList.add(documentImplObject);
2089
            }//try
2090
            catch (McdbDocNotFoundException notFoundE) {
2091 2663 sgarg
                logMetacat.error(
2092 2075 jones
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2093 2663 sgarg
                                + notFoundE.getMessage());
2094 2075 jones
                // Rather than add a DocumentImple object into vetor, a String
2095
                // object
2096
                // - the doicd was added to the vector
2097
                documentImplList.add(docidPlusVersion);
2098
                // Continue the for loop
2099
                continue;
2100
            }//catch
2101
            catch (Exception e) {
2102 2663 sgarg
                logMetacat.error(
2103 2075 jones
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2104 2663 sgarg
                                + e.getMessage());
2105 2075 jones
                // Continue the for loop
2106
                continue;
2107
            }//catch
2108
2109
        }//for
2110
        return documentImplList;
2111
    }//getOldVersionAllDocumentImple
2112
2113
    /**
2114
     * put a data file into a zip output stream
2115 2087 tao
     *
2116 2075 jones
     * @param docImpl, docmentImpl object which will be sent to zip output
2117
     *            stream
2118
     * @param zipOut, the zip output stream which the docImpl will be put
2119
     * @param packageZipEntry, the zip entry name for whole package
2120
     */
2121
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2122
            ZipOutputStream zipOut, String packageZipEntry)
2123
            throws ClassNotFoundException, IOException, SQLException,
2124
            McdbException, Exception
2125 940 tao
    {
2126 2075 jones
        byte[] byteString = null;
2127
        ZipEntry zEntry = null;
2128
        // this is data file; add file to zip
2129
        String filePath = MetaCatUtil.getOption("datafilepath");
2130
        if (!filePath.endsWith("/")) {
2131
            filePath += "/";
2132
        }
2133
        String fileName = filePath + docImpl.getDocID();
2134
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2135
        zipOut.putNextEntry(zEntry);
2136
        FileInputStream fin = null;
2137
        try {
2138
            fin = new FileInputStream(fileName);
2139
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2140
            int b = fin.read(buf);
2141
            while (b != -1) {
2142
                zipOut.write(buf, 0, b);
2143
                b = fin.read(buf);
2144
            }//while
2145
            zipOut.closeEntry();
2146
        }//try
2147
        catch (IOException ioe) {
2148 2663 sgarg
            logMetacat.error("There is an exception: "
2149
                    + ioe.getMessage());
2150 2075 jones
        }//catch
2151
    }//addDataFileToZipOutputStream()
2152 2043 sgarg
2153 2075 jones
    /**
2154
     * create a html summary for data package and put it into zip output stream
2155 2087 tao
     *
2156 2075 jones
     * @param docImplList, the documentImpl ojbects in data package
2157
     * @param zipOut, the zip output stream which the html should be put
2158
     * @param packageZipEntry, the zip entry name for whole package
2159
     */
2160
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2161
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2162
    {
2163
        StringBuffer htmlDoc = new StringBuffer();
2164
        ZipEntry zEntry = null;
2165
        byte[] byteString = null;
2166
        InputStream source;
2167
        DBTransform xmlToHtml;
2168 2043 sgarg
2169 2075 jones
        //create a DBTransform ojbect
2170
        xmlToHtml = new DBTransform();
2171
        //head of html
2172
        htmlDoc.append("<html><head></head><body>");
2173
        for (int i = 0; i < docImplList.size(); i++) {
2174
            // If this String object, this means it is missed data file
2175
            if ((((docImplList.elementAt(i)).getClass()).toString())
2176
                    .equals("class java.lang.String")) {
2177 2043 sgarg
2178 2075 jones
                htmlDoc.append("<a href=\"");
2179
                String dataFileid = (String) docImplList.elementAt(i);
2180
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2181
                htmlDoc.append("Data File: ");
2182
                htmlDoc.append(dataFileid).append("</a><br>");
2183
                htmlDoc.append("<br><hr><br>");
2184 1356 tao
2185 2075 jones
            }//if
2186
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2187
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2188
                                              // transform it.
2189
                //transform each file individually then concatenate all of the
2190
                //transformations together.
2191 1356 tao
2192 2075 jones
                //for metadata xml title
2193
                htmlDoc.append("<h2>");
2194
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2195
                        .getDocID());
2196
                //htmlDoc.append(".");
2197
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2198
                htmlDoc.append("</h2>");
2199
                //do the actual transform
2200
                StringWriter docString = new StringWriter();
2201
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2202
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2203
                        "-//W3C//HTML//EN", "html", docString);
2204
                htmlDoc.append(docString.toString());
2205
                htmlDoc.append("<br><br><hr><br><br>");
2206
            }//if
2207
            else { //this is a data file so we should link to it in the html
2208
                htmlDoc.append("<a href=\"");
2209
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2210
                        .getDocID();
2211
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2212
                htmlDoc.append("Data File: ");
2213
                htmlDoc.append(dataFileid).append("</a><br>");
2214
                htmlDoc.append("<br><hr><br>");
2215
            }//else
2216
        }//for
2217
        htmlDoc.append("</body></html>");
2218
        byteString = htmlDoc.toString().getBytes();
2219
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2220
        zEntry.setSize(byteString.length);
2221
        zipOut.putNextEntry(zEntry);
2222
        zipOut.write(byteString, 0, byteString.length);
2223
        zipOut.closeEntry();
2224
        //dbConn.close();
2225 1356 tao
2226 2075 jones
    }//addHtmlSummaryToZipOutputStream
2227 1356 tao
2228 2075 jones
    /**
2229
     * put a data packadge into a zip output stream
2230 2087 tao
     *
2231 2641 tao
     * @param docId, which the user want to put into zip output stream,it has version
2232 2075 jones
     * @param out, a servletoutput stream which the zip output stream will be
2233
     *            put
2234
     * @param user, the username of the user
2235
     * @param groups, the group of the user
2236
     */
2237
    public ZipOutputStream getZippedPackage(String docIdString,
2238
            ServletOutputStream out, String user, String[] groups,
2239
            String passWord) throws ClassNotFoundException, IOException,
2240
            SQLException, McdbException, NumberFormatException, Exception
2241 945 tao
    {
2242 2075 jones
        ZipOutputStream zOut = null;
2243
        String elementDocid = null;
2244
        DocumentImpl docImpls = null;
2245
        //Connection dbConn = null;
2246
        Vector docIdList = new Vector();
2247
        Vector documentImplList = new Vector();
2248
        Vector htmlDocumentImplList = new Vector();
2249
        String packageId = null;
2250
        String rootName = "package";//the package zip entry name
2251 2043 sgarg
2252 2075 jones
        String docId = null;
2253
        int version = -5;
2254
        // Docid without revision
2255
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2256
        // revision number
2257
        version = MetaCatUtil.getVersionFromString(docIdString);
2258 2043 sgarg
2259 2075 jones
        //check if the reqused docId is a data package id
2260
        if (!isDataPackageId(docId)) {
2261 2043 sgarg
2262 2075 jones
            /*
2263
             * Exception e = new Exception("The request the doc id "
2264
             * +docIdString+ " is not a data package id");
2265
             */
2266 940 tao
2267 2075 jones
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2268
            // zip
2269
            //up the single document and return the zip file.
2270
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2271 2043 sgarg
2272 2075 jones
                Exception e = new Exception("User " + user
2273
                        + " does not have permission"
2274
                        + " to export the data package " + docIdString);
2275
                throw e;
2276
            }
2277 2043 sgarg
2278 2641 tao
            docImpls = new DocumentImpl(docIdString);
2279 2075 jones
            //checking if the user has the permission to read the documents
2280
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2281
                    .getDocID())) {
2282
                zOut = new ZipOutputStream(out);
2283
                //if the docImpls is metadata
2284
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2285
                    //add metadata into zip output stream
2286
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2287
                }//if
2288
                else {
2289
                    //it is data file
2290
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2291
                    htmlDocumentImplList.add(docImpls);
2292
                }//else
2293 1292 tao
            }//if
2294 2043 sgarg
2295 2075 jones
            zOut.finish(); //terminate the zip file
2296
            return zOut;
2297
        }
2298
        // Check the permission of user
2299
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2300
2301
            Exception e = new Exception("User " + user
2302
                    + " does not have permission"
2303
                    + " to export the data package " + docIdString);
2304
            throw e;
2305
        } else //it is a packadge id
2306 1292 tao
        {
2307 2075 jones
            //store the package id
2308
            packageId = docId;
2309
            //get current version in database
2310
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2311
            //If it is for current version (-1 means user didn't specify
2312
            // revision)
2313
            if ((version == -1) || version == currentVersion) {
2314
                //get current version number
2315
                version = currentVersion;
2316
                //get package zip entry name
2317
                //it should be docId.revsion.package
2318
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2319
                        + version + MetaCatUtil.getOption("accNumSeparator")
2320
                        + "package";
2321
                //get the whole id list for data packadge
2322
                docIdList = getCurrentDocidListForDataPackage(packageId);
2323
                //get the whole documentImple object
2324
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2325 2043 sgarg
2326 1292 tao
            }//if
2327 2075 jones
            else if (version > currentVersion || version < -1) {
2328
                throw new Exception("The user specified docid: " + docId + "."
2329
                        + version + " doesn't exist");
2330
            }//else if
2331
            else //for an old version
2332 1292 tao
            {
2333 2075 jones
2334
                rootName = docIdString
2335
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2336
                //get the whole id list for data packadge
2337
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2338
2339
                //get the whole documentImple object
2340
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2341 1292 tao
            }//else
2342 940 tao
2343 2075 jones
            // Make sure documentImplist is not empty
2344
            if (documentImplList.isEmpty()) { throw new Exception(
2345
                    "Couldn't find component for data package: " + packageId); }//if
2346 2043 sgarg
2347 2075 jones
            zOut = new ZipOutputStream(out);
2348
            //put every element into zip output stream
2349
            for (int i = 0; i < documentImplList.size(); i++) {
2350
                // if the object in the vetor is String, this means we couldn't
2351
                // find
2352
                // the document locally, we need find it remote
2353
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2354
                        .equals("class java.lang.String")) {
2355
                    // Get String object from vetor
2356
                    String documentId = (String) documentImplList.elementAt(i);
2357 2663 sgarg
                    logMetacat.info("docid: " + documentId);
2358 2075 jones
                    // Get doicd without revision
2359
                    String docidWithoutRevision = MetaCatUtil
2360
                            .getDocIdFromString(documentId);
2361 2663 sgarg
                    logMetacat.info("docidWithoutRevsion: "
2362
                            + docidWithoutRevision);
2363 2075 jones
                    // Get revision
2364
                    String revision = MetaCatUtil
2365
                            .getRevisionStringFromString(documentId);
2366 2663 sgarg
                    logMetacat.info("revsion from docIdentifier: "
2367
                            + revision);
2368 2075 jones
                    // Zip entry string
2369
                    String zipEntryPath = rootName + "/data/";
2370
                    // Create a RemoteDocument object
2371
                    RemoteDocument remoteDoc = new RemoteDocument(
2372
                            docidWithoutRevision, revision, user, passWord,
2373
                            zipEntryPath);
2374
                    // Here we only read data file from remote metacat
2375
                    String docType = remoteDoc.getDocType();
2376
                    if (docType != null) {
2377
                        if (docType.equals("BIN")) {
2378
                            // Put remote document to zip output
2379
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2380
                            // Add String object to htmlDocumentImplList
2381
                            String elementInHtmlList = remoteDoc
2382
                                    .getDocIdWithoutRevsion()
2383
                                    + MetaCatUtil.getOption("accNumSeparator")
2384
                                    + remoteDoc.getRevision();
2385
                            htmlDocumentImplList.add(elementInHtmlList);
2386
                        }//if
2387
                    }//if
2388 1361 tao
2389 2075 jones
                }//if
2390
                else {
2391
                    //create a docmentImpls object (represent xml doc) base on
2392
                    // the docId
2393
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2394
                    //checking if the user has the permission to read the
2395
                    // documents
2396
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2397
                            .getDocID())) {
2398
                        //if the docImpls is metadata
2399
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2400
                            //add metadata into zip output stream
2401
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2402
                            //add the documentImpl into the vetor which will
2403
                            // be used in html
2404
                            htmlDocumentImplList.add(docImpls);
2405 2043 sgarg
2406 2075 jones
                        }//if
2407
                        else {
2408
                            //it is data file
2409
                            addDataFileToZipOutputStream(docImpls, zOut,
2410
                                    rootName);
2411
                            htmlDocumentImplList.add(docImpls);
2412
                        }//else
2413
                    }//if
2414
                }//else
2415
            }//for
2416 2043 sgarg
2417 2075 jones
            //add html summary file
2418
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2419
                    rootName);
2420
            zOut.finish(); //terminate the zip file
2421
            //dbConn.close();
2422
            return zOut;
2423
        }//else
2424
    }//getZippedPackage()
2425 2043 sgarg
2426 2075 jones
    private class ReturnFieldValue
2427 1361 tao
    {
2428 2043 sgarg
2429 2075 jones
        private String docid = null; //return field value for this docid
2430 2043 sgarg
2431 2075 jones
        private String fieldValue = null;
2432 2043 sgarg
2433 2075 jones
        private String xmlFieldValue = null; //return field value in xml
2434
                                             // format
2435
2436
        public void setDocid(String myDocid)
2437
        {
2438
            docid = myDocid;
2439
        }
2440
2441
        public String getDocid()
2442
        {
2443
            return docid;
2444
        }
2445
2446
        public void setFieldValue(String myValue)
2447
        {
2448
            fieldValue = myValue;
2449
        }
2450
2451
        public String getFieldValue()
2452
        {
2453
            return fieldValue;
2454
        }
2455
2456
        public void setXMLFieldValue(String xml)
2457
        {
2458
            xmlFieldValue = xml;
2459
        }
2460
2461
        public String getXMLFieldValue()
2462
        {
2463
            return xmlFieldValue;
2464
        }
2465
2466 1361 tao
    }
2467 155 jones
}