Project

General

Profile

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

    
31
package edu.ucsb.nceas.metacat;
32

    
33
import java.io.*;
34
import java.util.zip.*;
35
import java.sql.PreparedStatement;
36
import java.sql.ResultSet;
37
import java.sql.SQLException;
38
import java.util.*;
39

    
40
import javax.servlet.ServletOutputStream;
41
import javax.servlet.http.HttpServletResponse;
42
import javax.servlet.http.HttpSession;
43

    
44
import org.apache.log4j.Logger;
45

    
46
import org.w3c.dom.*;
47
import javax.xml.parsers.DocumentBuilderFactory;
48
import org.xml.sax.InputSource;
49
import org.w3c.dom.ls.*;
50

    
51
import edu.ucsb.nceas.morpho.datapackage.Triple;
52
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
53

    
54

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

    
64
    static final int ALL = 1;
65

    
66
    static final int WRITE = 2;
67

    
68
    static final int READ = 4;
69

    
70
    //private Connection conn = null;
71
    private String parserName = null;
72

    
73
    private MetaCatUtil util = new MetaCatUtil();
74

    
75
    private Logger logMetacat = Logger.getLogger(DBQuery.class);
76

    
77
    /** true if the metacat spatial option is installed **/
78
    private final boolean METACAT_SPATIAL = true;
79

    
80
    /** useful if you just want to grab a list of docids. Since the docids can be very long,
81
         it is a vector of vector  **/
82
    Vector docidOverride = new Vector();
83
    
84
    // a hash table serves as query reuslt cache. Key of hashtable
85
    // is a query string and value is result xml string
86
    private static Hashtable queryResultCache = new Hashtable();
87
    
88
    // Capacity of the query result cache
89
    private static final int QUERYRESULTCACHESIZE = Integer.parseInt(MetaCatUtil.getOption("queryresult_cache_size"));
90

    
91
    // Size of page for non paged query
92
    private static final int NONPAGESIZE = 99999999;
93
    /**
94
     * the main routine used to test the DBQuery utility.
95
     * <p>
96
     * Usage: java DBQuery <xmlfile>
97
     *
98
     * @param xmlfile the filename of the xml file containing the query
99
     */
100
    static public void main(String[] args)
101
    {
102

    
103
        if (args.length < 1) {
104
            System.err.println("Wrong number of arguments!!!");
105
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
106
            return;
107
        } else {
108
            try {
109

    
110
                int i = 0;
111
                boolean showRuntime = false;
112
                boolean useXMLIndex = false;
113
                if (args[i].equals("-t")) {
114
                    showRuntime = true;
115
                    i++;
116
                }
117
                if (args[i].equals("-index")) {
118
                    useXMLIndex = true;
119
                    i++;
120
                }
121
                String xmlfile = args[i];
122

    
123
                // Time the request if asked for
124
                double startTime = System.currentTimeMillis();
125

    
126
                // Open a connection to the database
127
                MetaCatUtil util = new MetaCatUtil();
128
                //Connection dbconn = util.openDBConnection();
129

    
130
                double connTime = System.currentTimeMillis();
131

    
132
                // Execute the query
133
                DBQuery queryobj = new DBQuery();
134
                FileReader xml = new FileReader(new File(xmlfile));
135
                Hashtable nodelist = null;
136
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
137

    
138
                // Print the reulting document listing
139
                StringBuffer result = new StringBuffer();
140
                String document = null;
141
                String docid = null;
142
                result.append("<?xml version=\"1.0\"?>\n");
143
                result.append("<resultset>\n");
144

    
145
                if (!showRuntime) {
146
                    Enumeration doclist = nodelist.keys();
147
                    while (doclist.hasMoreElements()) {
148
                        docid = (String) doclist.nextElement();
149
                        document = (String) nodelist.get(docid);
150
                        result.append("  <document>\n    " + document
151
                                + "\n  </document>\n");
152
                    }
153

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

    
180
            } catch (Exception e) {
181
                System.err.println("Error in DBQuery.main");
182
                System.err.println(e.getMessage());
183
                e.printStackTrace(System.err);
184
            }
185
        }
186
    }
187

    
188
    /**
189
     * construct an instance of the DBQuery class
190
     *
191
     * <p>
192
     * Generally, one would call the findDocuments() routine after creating an
193
     * instance to specify the search query
194
     * </p>
195
     *
196

    
197
     * @param parserName the fully qualified name of a Java class implementing
198
     *            the org.xml.sax.XMLReader interface
199
     */
200
    public DBQuery()
201
    {
202
        String parserName = MetaCatUtil.getOption("saxparser");
203
        this.parserName = parserName;
204
    }
205

    
206
    /**
207
     * 
208
     * Construct an instance of DBQuery Class
209
     * BUT accept a docid Vector that will supersede
210
     * the query.printSQL() method
211
     *
212
     * If a docid Vector is passed in,
213
     * the docids will be used to create a simple IN query 
214
     * without the multiple subselects of the printSQL() method
215
     *
216
     * Using this constructor, we just check for 
217
     * a docidOverride Vector in the findResultDoclist() method
218
     *
219
     * @param docids List of docids to display in the resultset
220
     */
221
    public DBQuery(Vector docids)
222
    {
223
    	// since the query will be too long to be handled, so we divided the 
224
    	// docids vector into couple vectors.
225
    	int size = (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
226
    	logMetacat.info("The size of select doicds is "+docids.size());
227
    	logMetacat.info("The application result size in metacat.properties is "+size);
228
    	Vector subset = new Vector();
229
    	if (docids != null && docids.size() > size)
230
    	{
231
    		int index = 0;
232
    		for (int i=0; i< docids.size(); i++)
233
    		{
234
    			
235
    			if (index < size)
236
    			{  	
237
    				subset.add(docids.elementAt(i));
238
    				index ++;
239
    			}
240
    			else
241
    			{
242
    				docidOverride.add(subset);
243
    				subset = new Vector();
244
    				subset.add(docids.elementAt(i));
245
    			    index = 1;
246
    			}
247
    		}
248
    		if (!subset.isEmpty())
249
    		{
250
    			docidOverride.add(subset);
251
    		}
252
    		
253
    	}
254
    	else
255
    	{
256
    		this.docidOverride.add(docids);
257
    	}
258
        
259
        String parserName = MetaCatUtil.getOption("saxparser");
260
        this.parserName = parserName;
261
    }
262

    
263
  /**
264
   * Method put the search result set into out printerwriter
265
   * @param resoponse the return response
266
   * @param out the output printer
267
   * @param params the paratermer hashtable
268
   * @param user the user name (it maybe different to the one in param)
269
   * @param groups the group array
270
   * @param sessionid  the sessionid
271
   */
272
  public void findDocuments(HttpServletResponse response,
273
                                       PrintWriter out, Hashtable params,
274
                                       String user, String[] groups,
275
                                       String sessionid)
276
  {
277
    boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
278
               .booleanValue();
279
    findDocuments(response, out, params, user, groups, sessionid, useXMLIndex);
280

    
281
  }
282

    
283

    
284
    /**
285
     * Method put the search result set into out printerwriter
286
     * @param resoponse the return response
287
     * @param out the output printer
288
     * @param params the paratermer hashtable
289
     * @param user the user name (it maybe different to the one in param)
290
     * @param groups the group array
291
     * @param sessionid  the sessionid
292
     */
293
    public void findDocuments(HttpServletResponse response,
294
                                         PrintWriter out, Hashtable params,
295
                                         String user, String[] groups,
296
                                         String sessionid, boolean useXMLIndex)
297
    {
298
      int pagesize = 0;
299
      int pagestart = 0;
300
      
301
      if(params.containsKey("pagesize") && params.containsKey("pagestart"))
302
      {
303
        String pagesizeStr = ((String[])params.get("pagesize"))[0];
304
        String pagestartStr = ((String[])params.get("pagestart"))[0];
305
        if(pagesizeStr != null && pagestartStr != null)
306
        {
307
          pagesize = (new Integer(pagesizeStr)).intValue();
308
          pagestart = (new Integer(pagestartStr)).intValue();
309
        }
310
      }
311
      
312
      String xmlquery = null;
313
      String qformat = null;
314
      // get query and qformat
315
      try {
316
    	xmlquery = ((String[])params.get("query"))[0];
317

    
318
        logMetacat.info("SESSIONID: " + sessionid);
319
        logMetacat.info("xmlquery: " + xmlquery);
320
        qformat = ((String[])params.get("qformat"))[0];
321
        logMetacat.info("qformat: " + qformat);
322
      }
323
      catch (Exception ee)
324
      {
325
        logMetacat.error("Couldn't retrieve xmlquery or qformat value from "
326
                  +"params hashtable in DBQuery.findDocuments: "
327
                  + ee.getMessage()); 
328
      }
329
      // Get the XML query and covert it into a SQL statment
330
      QuerySpecification qspec = null;
331
      if ( xmlquery != null)
332
      {
333
         xmlquery = transformQuery(xmlquery);
334
         try
335
         {
336
           qspec = new QuerySpecification(xmlquery,
337
                                          parserName,
338
                                          MetaCatUtil.getOption("accNumSeparator"));
339
         }
340
         catch (Exception ee)
341
         {
342
           logMetacat.error("error generating QuerySpecification object"
343
                                    +" in DBQuery.findDocuments"
344
                                    + ee.getMessage());
345
         }
346
      }
347

    
348

    
349

    
350
      if (qformat != null && qformat.equals(MetaCatServlet.XMLFORMAT))
351
      {
352
        //xml format
353
        response.setContentType("text/xml");
354
        createResultDocument(xmlquery, qspec, out, user, groups, useXMLIndex, 
355
          pagesize, pagestart, sessionid);
356
      }//if
357
      else
358
      {
359
        //knb format, in this case we will get whole result and sent it out
360
        response.setContentType("text/html");
361
        PrintWriter nonout = null;
362
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
363
                                                groups, useXMLIndex, pagesize, 
364
                                                pagestart, sessionid);
365
        
366
        //transfer the xml to html
367
        try
368
        {
369
         double startHTMLTransform = System.currentTimeMillis()/1000;
370
         DBTransform trans = new DBTransform();
371
         response.setContentType("text/html");
372

    
373
         // if the user is a moderator, then pass a param to the 
374
         // xsl specifying the fact
375
         if(MetaCatUtil.isModerator(user, groups)){
376
        	 params.put("isModerator", new String[] {"true"});
377
         }
378

    
379
         trans.transformXMLDocument(xml.toString(), "-//NCEAS//resultset//EN",
380
                                 "-//W3C//HTML//EN", qformat, out, params,
381
                                 sessionid);
382
         double endHTMLTransform = System.currentTimeMillis()/1000;
383
          logMetacat.warn("The time to transfrom resultset from xml to html format is "
384
                  		                             +(endHTMLTransform -startHTMLTransform));
385
          MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Transfrom xml to html  "
386
                             +(endHTMLTransform -startHTMLTransform));
387
          MetaCatUtil.writeDebugToDelimiteredFile(" "+(endHTMLTransform -startHTMLTransform), false);
388
        }
389
        catch(Exception e)
390
        {
391
         logMetacat.error("Error in MetaCatServlet.transformResultset:"
392
                                +e.getMessage());
393
         }
394

    
395
      }//else
396

    
397
  }
398
  
399
  /**
400
   * Transforms a hashtable of documents to an xml or html result and sent
401
   * the content to outputstream. Keep going untill hastable is empty. stop it.
402
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
403
   * to xmlquery String
404
   * @param xmlquery
405
   * @param qspec
406
   * @param out
407
   * @param user
408
   * @param groups
409
   * @param useXMLIndex
410
   * @param sessionid
411
   * @return
412
   */
413
    public StringBuffer createResultDocument(String xmlquery,
414
                                              QuerySpecification qspec,
415
                                              PrintWriter out,
416
                                              String user, String[] groups,
417
                                              boolean useXMLIndex)
418
    {
419
    	return createResultDocument(xmlquery,qspec,out, user,groups, useXMLIndex, 0, 0,"");
420
    }
421

    
422
  /*
423
   * Transforms a hashtable of documents to an xml or html result and sent
424
   * the content to outputstream. Keep going untill hastable is empty. stop it.
425
   * add the QuerySpecification as parameter is for ecogrid. But it is duplicate
426
   * to xmlquery String
427
   */
428
  public StringBuffer createResultDocument(String xmlquery,
429
                                            QuerySpecification qspec,
430
                                            PrintWriter out,
431
                                            String user, String[] groups,
432
                                            boolean useXMLIndex, int pagesize,
433
                                            int pagestart, String sessionid)
434
  {
435
    DBConnection dbconn = null;
436
    int serialNumber = -1;
437
    StringBuffer resultset = new StringBuffer();
438

    
439
    //try to get the cached version first    
440
    Hashtable sessionHash = MetaCatServlet.getSessionHash();
441
    HttpSession sess = (HttpSession)sessionHash.get(sessionid);
442

    
443
    
444
    resultset.append("<?xml version=\"1.0\"?>\n");
445
    resultset.append("<resultset>\n");
446
    resultset.append("  <pagestart>" + pagestart + "</pagestart>\n");
447
    resultset.append("  <pagesize>" + pagesize + "</pagesize>\n");
448
    resultset.append("  <nextpage>" + (pagestart + 1) + "</nextpage>\n");
449
    resultset.append("  <previouspage>" + (pagestart - 1) + "</previouspage>\n");
450

    
451
    resultset.append("  <query>" + xmlquery + "</query>");
452
    //send out a new query
453
    if (out != null)
454
    {
455
      out.println(resultset.toString());
456
    }
457
    if (qspec != null)
458
    {
459
      try
460
      {
461

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

    
466
        //print out the search result
467
        // search the doc list
468
        Vector givenDocids = new Vector();
469
        StringBuffer resultContent = new StringBuffer();
470
        if (docidOverride == null || docidOverride.size() == 0)
471
        {
472
        	logMetacat.info("Not in map query");
473
        	resultContent = findResultDoclist(qspec, out, user, groups,
474
                    dbconn, useXMLIndex, pagesize, pagestart, 
475
                    sessionid, givenDocids);
476
        }
477
        else
478
        {
479
        	logMetacat.info("In map query");
480
        	// since docid can be too long to be handled. We divide it into several parts
481
        	for (int i= 0; i<docidOverride.size(); i++)
482
        	{
483
        	   logMetacat.info("in loop===== "+i);
484
        		givenDocids = (Vector)docidOverride.elementAt(i);
485
        		StringBuffer subset = findResultDoclist(qspec, out, user, groups,
486
                        dbconn, useXMLIndex, pagesize, pagestart, 
487
                        sessionid, givenDocids);
488
        		resultContent.append(subset);
489
        	}
490
        }
491
           
492
        resultset.append(resultContent);
493
      } //try
494
      catch (IOException ioe)
495
      {
496
        logMetacat.error("IO error in DBQuery.findDocuments:");
497
        logMetacat.error(ioe.getMessage());
498

    
499
      }
500
      catch (SQLException e)
501
      {
502
        logMetacat.error("SQL Error in DBQuery.findDocuments: "
503
                                 + e.getMessage());
504
      }
505
      catch (Exception ee)
506
      {
507
        logMetacat.error("Exception in DBQuery.findDocuments: "
508
                                 + ee.getMessage());
509
        ee.printStackTrace();
510
      }
511
      finally
512
      {
513
        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
514
      } //finally
515
    }//if
516
    String closeRestultset = "</resultset>";
517
    resultset.append(closeRestultset);
518
    if (out != null)
519
    {
520
      out.println(closeRestultset);
521
    }
522

    
523
    //default to returning the whole resultset
524
    return resultset;
525
  }//createResultDocuments
526

    
527
    /*
528
     * Find the doc list which match the query
529
     */
530
    private StringBuffer findResultDoclist(QuerySpecification qspec,
531
                                      PrintWriter out,
532
                                      String user, String[]groups,
533
                                      DBConnection dbconn, boolean useXMLIndex,
534
                                      int pagesize, int pagestart, String sessionid, Vector givenDocids)
535
                                      throws Exception
536
    {
537
      StringBuffer resultsetBuffer = new StringBuffer();
538
      String query = null;
539
      int count = 0;
540
      int index = 0;
541
      ResultDocumentSet docListResult = new ResultDocumentSet();
542
      PreparedStatement pstmt = null;
543
      String docid = null;
544
      String docname = null;
545
      String doctype = null;
546
      String createDate = null;
547
      String updateDate = null;
548
      StringBuffer document = null;
549
      boolean lastpage = false;
550
      int rev = 0;
551
      double startTime = 0;
552
      int offset = 1;
553
      double startSelectionTime = System.currentTimeMillis()/1000;
554
      ResultSet rs = null;
555
           
556
   
557
      // this is a hack for offset. in postgresql 7, if the returned docid list is too long,
558
      //the extend query which base on the docid will be too long to be run. So we 
559
      // have to cut them into different parts. Page query don't need it somehow.
560
      if (out == null)
561
      {
562
        // for html page, we put everything into one page
563
        offset =
564
            (new Integer(MetaCatUtil.getOption("web_resultsetsize"))).intValue();
565
      }
566
      else
567
      {
568
          offset =
569
              (new Integer(MetaCatUtil.getOption("app_resultsetsize"))).intValue();
570
      }
571

    
572
      /*
573
       * Check the docidOverride Vector
574
       * if defined, we bypass the qspec.printSQL() method
575
       * and contruct a simpler query based on a 
576
       * list of docids rather than a bunch of subselects
577
       */
578
      if ( givenDocids == null || givenDocids.size() == 0 ) {
579
          query = qspec.printSQL(useXMLIndex);
580
      } else {
581
          logMetacat.info("*** docid override " + givenDocids.size());
582
          StringBuffer queryBuffer = new StringBuffer( "SELECT docid,docname,doctype,date_created, date_updated, rev " );
583
          queryBuffer.append( " FROM xml_documents WHERE docid IN (" );
584
          for (int i = 0; i < givenDocids.size(); i++) {  
585
              queryBuffer.append("'");
586
              queryBuffer.append( (String)givenDocids.elementAt(i) );
587
              queryBuffer.append("',");
588
          }
589
          // empty string hack 
590
          queryBuffer.append( "'') " );
591
          query = queryBuffer.toString();
592
      } 
593
      String ownerQuery = getOwnerQuery(user);
594
      logMetacat.info("\n\n\n query: " + query);
595
      logMetacat.info("\n\n\n owner query: "+ownerQuery);
596
      // if query is not the owner query, we need to check the permission
597
      // otherwise we don't need (owner has all permission by default)
598
      if (!query.equals(ownerQuery))
599
      {
600
        // set user name and group
601
        qspec.setUserName(user);
602
        qspec.setGroup(groups);
603
        // Get access query
604
        String accessQuery = qspec.getAccessQuery();
605
        if(!query.endsWith("WHERE")){
606
            query = query + accessQuery;
607
        } else {
608
            query = query + accessQuery.substring(4, accessQuery.length());
609
        }
610
        
611
      }
612
      logMetacat.warn("============ final selection query: " + query);
613
      String selectionAndExtendedQuery = null;
614
      // we only get cache for public
615
      if (user != null && user.equalsIgnoreCase("public") 
616
     		 && pagesize == 0 && MetaCatUtil.getOption("query_cache_on").equals("true"))
617
      {
618
    	  selectionAndExtendedQuery = query +qspec.getReturnDocList()+qspec.getReturnFieldList();
619
   	      String cachedResult = getResultXMLFromCache(selectionAndExtendedQuery);
620
   	      logMetacat.debug("The key of query cache is "+selectionAndExtendedQuery);
621
   	      //System.out.println("==========the string from cache is "+cachedResult);
622
   	      if (cachedResult != null)
623
   	      {
624
   	    	logMetacat.info("resutl from cache !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
625
   	    	 if (out != null)
626
   	         {
627
   	             out.println(cachedResult);
628
   	         }
629
   	    	 resultsetBuffer.append(cachedResult);
630
   	    	 return resultsetBuffer;
631
   	      }
632
      }
633
      
634
      startTime = System.currentTimeMillis() / 1000;
635
      pstmt = dbconn.prepareStatement(query);
636
      rs = pstmt.executeQuery();
637

    
638
      double queryExecuteTime = System.currentTimeMillis() / 1000;
639
      logMetacat.warn("Time to execute select docid query is "
640
                    + (queryExecuteTime - startTime));
641
      MetaCatUtil.writeDebugToFile("\n\n\n\n\n\nExecute selection query  "
642
              + (queryExecuteTime - startTime));
643
      MetaCatUtil.writeDebugToDelimiteredFile(""+(queryExecuteTime - startTime), false);
644

    
645
      boolean tableHasRows = rs.next();
646
      
647
      if(pagesize == 0)
648
      { //this makes sure we get all results if there is no paging
649
        pagesize = NONPAGESIZE;
650
        pagestart = NONPAGESIZE;
651
      } 
652
      
653
      int currentIndex = 0;
654
      while (tableHasRows)
655
      {
656
        logMetacat.info("############getting result: " + currentIndex);
657
        docid = rs.getString(1).trim();
658
        logMetacat.info("############processing: " + docid);
659
        docname = rs.getString(2);
660
        doctype = rs.getString(3);
661
        logMetacat.info("############processing: " + doctype);
662
        createDate = rs.getString(4);
663
        updateDate = rs.getString(5);
664
        rev = rs.getInt(6);
665
        
666
         Vector returndocVec = qspec.getReturnDocList();
667
       if (returndocVec.size() == 0 || returndocVec.contains(doctype))
668
        {
669
          logMetacat.info("NOT Back tracing now...");
670
           document = new StringBuffer();
671

    
672
           String completeDocid = docid
673
                            + MetaCatUtil.getOption("accNumSeparator");
674
           completeDocid += rev;
675
           document.append("<docid>").append(completeDocid).append("</docid>");
676
           if (docname != null)
677
           {
678
               document.append("<docname>" + docname + "</docname>");
679
           }
680
           if (doctype != null)
681
           {
682
              document.append("<doctype>" + doctype + "</doctype>");
683
           }
684
           if (createDate != null)
685
           {
686
               document.append("<createdate>" + createDate + "</createdate>");
687
           }
688
           if (updateDate != null)
689
           {
690
             document.append("<updatedate>" + updateDate + "</updatedate>");
691
           }
692
           // Store the document id and the root node id
693
           
694
           docListResult.addResultDocument(
695
             new ResultDocument(docid, (String) document.toString()));
696
           logMetacat.info("$$$$$$$real result: " + docid);
697
           currentIndex++;
698
           count++;
699
        }//else
700
        
701
        // when doclist reached the offset number, send out doc list and empty
702
        // the hash table
703
        if (count == offset && pagesize == NONPAGESIZE)
704
        { //if pagesize is not 0, do this later.
705
          //reset count
706
          //logMetacat.warn("############doing subset cache");
707
          count = 0;
708
          handleSubsetResult(qspec, resultsetBuffer, out, docListResult,
709
                              user, groups,dbconn, useXMLIndex);
710
          //reset docListResult
711
          docListResult = new ResultDocumentSet();
712
        }
713
       
714
       logMetacat.info("currentIndex: " + currentIndex);
715
       logMetacat.info("page comparator: " + (pagesize * pagestart) + pagesize);
716
       if(currentIndex >= ((pagesize * pagestart) + pagesize))
717
       {
718
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
719
         for(int i=pagesize*pagestart; i<docListResult.size(); i++)
720
         {
721
           pagedResultsHash.put(docListResult.get(i));
722
         }
723
         
724
         docListResult = pagedResultsHash;
725
         break;
726
       }
727
       // Advance to the next record in the cursor
728
       tableHasRows = rs.next();
729
       if(!tableHasRows)
730
       {
731
         ResultDocumentSet pagedResultsHash = new ResultDocumentSet();
732
         //get the last page of information then break
733
         if(pagesize != NONPAGESIZE)
734
         {
735
           for(int i=pagesize*pagestart; i<docListResult.size(); i++)
736
           {
737
             pagedResultsHash.put(docListResult.get(i));
738
           }
739
           docListResult = pagedResultsHash;
740
         }
741
         
742
         lastpage = true;
743
         break;
744
       }
745
     }//while
746
     
747
     rs.close();
748
     pstmt.close();
749
     double docListTime = System.currentTimeMillis() / 1000;
750
     logMetacat.warn("======Total time to get docid list is: "
751
                          + (docListTime - startSelectionTime ));
752
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------Total selection: "
753
             + (docListTime - startSelectionTime ));
754
     MetaCatUtil.writeDebugToDelimiteredFile(" "+ (docListTime - startSelectionTime ), false);
755
     //if docListResult is not empty, it need to be sent.
756
     if (docListResult.size() != 0)
757
     {
758
      
759
       handleSubsetResult(qspec,resultsetBuffer, out, docListResult,
760
                              user, groups,dbconn, useXMLIndex);
761
     }
762

    
763
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
764
     if (out != null)
765
     {
766
         out.println("\n<lastpage>" + lastpage + "</lastpage>\n");
767
     }
768
     
769
     // now we only cached none-paged query and user is public
770
     if (user != null && user.equalsIgnoreCase("public") 
771
    		 && pagesize == NONPAGESIZE && MetaCatUtil.getOption("query_cache_on").equals("true"))
772
     {
773
       //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
774
  	   storeQueryResultIntoCache(selectionAndExtendedQuery, resultsetBuffer.toString());
775
     }
776
          
777
     return resultsetBuffer;
778
    }//findReturnDoclist
779

    
780

    
781
    /*
782
     * Send completed search hashtable(part of reulst)to output stream
783
     * and buffer into a buffer stream
784
     */
785
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
786
                                           StringBuffer resultset,
787
                                           PrintWriter out, ResultDocumentSet partOfDoclist,
788
                                           String user, String[]groups,
789
                                       DBConnection dbconn, boolean useXMLIndex)
790
                                       throws Exception
791
   {
792
     double startReturnField = System.currentTimeMillis()/1000;
793
     // check if there is a record in xml_returnfield
794
     // and get the returnfield_id and usage count
795
     int usage_count = getXmlReturnfieldsTableId(qspec, dbconn);
796
     boolean enterRecords = false;
797

    
798
     // get value of xml_returnfield_count
799
     int count = (new Integer(MetaCatUtil
800
                            .getOption("xml_returnfield_count")))
801
                            .intValue();
802

    
803
     // set enterRecords to true if usage_count is more than the offset
804
     // specified in metacat.properties
805
     if(usage_count > count){
806
         enterRecords = true;
807
     }
808

    
809
     if(returnfield_id < 0){
810
         logMetacat.warn("Error in getting returnfield id from"
811
                                  + "xml_returnfield table");
812
         enterRecords = false;
813
     }
814

    
815
     // get the hashtable containing the docids that already in the
816
     // xml_queryresult table
817
     logMetacat.info("size of partOfDoclist before"
818
                             + " docidsInQueryresultTable(): "
819
                             + partOfDoclist.size());
820
     double startGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
821
     Hashtable queryresultDocList = docidsInQueryresultTable(returnfield_id,
822
                                                        partOfDoclist, dbconn);
823

    
824
     // remove the keys in queryresultDocList from partOfDoclist
825
     Enumeration _keys = queryresultDocList.keys();
826
     while (_keys.hasMoreElements()){
827
         partOfDoclist.remove((String)_keys.nextElement());
828
     }
829
     double endGetReturnValueFromQueryresultable = System.currentTimeMillis()/1000;
830
     logMetacat.warn("Time to get return fields from xml_queryresult table is (Part1 in return fields) " +
831
          		               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
832
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from xml_queryresult(Part1 in return fields) " +
833
               (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable));
834
     MetaCatUtil.writeDebugToDelimiteredFile(" " +
835
             (endGetReturnValueFromQueryresultable-startGetReturnValueFromQueryresultable),false);
836
     // backup the keys-elements in partOfDoclist to check later
837
     // if the doc entry is indexed yet
838
     Hashtable partOfDoclistBackup = new Hashtable();
839
     Iterator itt = partOfDoclist.getDocids();
840
     while (itt.hasNext()){
841
       Object key = itt.next();
842
         partOfDoclistBackup.put(key, partOfDoclist.get(key));
843
     }
844

    
845
     logMetacat.info("size of partOfDoclist after"
846
                             + " docidsInQueryresultTable(): "
847
                             + partOfDoclist.size());
848

    
849
     //add return fields for the documents in partOfDoclist
850
     partOfDoclist = addReturnfield(partOfDoclist, qspec, user, groups,
851
                                        dbconn, useXMLIndex);
852
     double endExtendedQuery = System.currentTimeMillis()/1000;
853
     logMetacat.warn("Get fields from index and node table (Part2 in return fields) "
854
        		                                          + (endExtendedQuery - endGetReturnValueFromQueryresultable));
855
     MetaCatUtil.writeDebugToFile("-----------------------------------------Get fields from extened query(Part2 in return fields) "
856
             + (endExtendedQuery - endGetReturnValueFromQueryresultable));
857
     MetaCatUtil.writeDebugToDelimiteredFile(" "
858
             + (endExtendedQuery - endGetReturnValueFromQueryresultable), false);
859
     //add relationship part part docid list for the documents in partOfDocList
860
     //partOfDoclist = addRelationship(partOfDoclist, qspec, dbconn, useXMLIndex);
861

    
862
     double startStoreReturnField = System.currentTimeMillis()/1000;
863
     Iterator keys = partOfDoclist.getDocids();
864
     String key = null;
865
     String element = null;
866
     String query = null;
867
     int offset = (new Integer(MetaCatUtil
868
                               .getOption("queryresult_string_length")))
869
                               .intValue();
870
     while (keys.hasNext())
871
     {
872
         key = (String) keys.next();
873
         element = (String)partOfDoclist.get(key);
874
         
875
	 // check if the enterRecords is true, elements is not null, element's
876
         // length is less than the limit of table column and if the document
877
         // has been indexed already
878
         if(enterRecords && element != null
879
		&& element.length() < offset
880
		&& element.compareTo((String) partOfDoclistBackup.get(key)) != 0){
881
             query = "INSERT INTO xml_queryresult (returnfield_id, docid, "
882
                 + "queryresult_string) VALUES (?, ?, ?)";
883

    
884
             PreparedStatement pstmt = null;
885
             pstmt = dbconn.prepareStatement(query);
886
             pstmt.setInt(1, returnfield_id);
887
             pstmt.setString(2, key);
888
             pstmt.setString(3, element);
889
            
890
             dbconn.increaseUsageCount(1);
891
             try
892
             {
893
            	 pstmt.execute();
894
             }
895
             catch(Exception e)
896
             {
897
            	 logMetacat.warn("couldn't insert the element to xml_queryresult table "+e.getLocalizedMessage());
898
             }
899
             finally
900
             {
901
                pstmt.close();
902
             }
903
         }
904
        
905
         // A string with element
906
         String xmlElement = "  <document>" + element + "</document>";
907

    
908
         //send single element to output
909
         if (out != null)
910
         {
911
             out.println(xmlElement);
912
         }
913
         resultset.append(xmlElement);
914
     }//while
915
     
916
     double endStoreReturnField = System.currentTimeMillis()/1000;
917
     logMetacat.warn("Time to store new return fields into xml_queryresult table (Part4 in return fields) "
918
                   + (endStoreReturnField -startStoreReturnField));
919
     MetaCatUtil.writeDebugToFile("-----------------------------------------Insert new record to xml_queryresult(Part4 in return fields) "
920
             + (endStoreReturnField -startStoreReturnField));
921
     MetaCatUtil.writeDebugToDelimiteredFile(" "
922
             + (endStoreReturnField -startStoreReturnField), false);
923
     
924
     Enumeration keysE = queryresultDocList.keys();
925
     while (keysE.hasMoreElements())
926
     {
927
         key = (String) keysE.nextElement();
928
         element = (String)queryresultDocList.get(key);
929
         // A string with element
930
         String xmlElement = "  <document>" + element + "</document>";
931
         //send single element to output
932
         if (out != null)
933
         {
934
             out.println(xmlElement);
935
         }
936
         resultset.append(xmlElement);
937
     }//while
938
     double returnFieldTime = System.currentTimeMillis() / 1000;
939
     logMetacat.warn("======Total time to get return fields is: "
940
                           + (returnFieldTime - startReturnField));
941
     MetaCatUtil.writeDebugToFile("---------------------------------------------------------------------------------------------------------------"+
942
    		 "Total to get return fields  "
943
                                   + (returnFieldTime - startReturnField));
944
     MetaCatUtil.writeDebugToDelimiteredFile(" "+ (returnFieldTime - startReturnField), false);
945
     return resultset;
946
 }
947

    
948
   /**
949
    * Get the docids already in xml_queryresult table and corresponding
950
    * queryresultstring as a hashtable
951
    */
952
   private Hashtable docidsInQueryresultTable(int returnfield_id,
953
                                              ResultDocumentSet partOfDoclist,
954
                                              DBConnection dbconn){
955

    
956
         Hashtable returnValue = new Hashtable();
957
         PreparedStatement pstmt = null;
958
         ResultSet rs = null;
959

    
960
         // get partOfDoclist as string for the query
961
         Iterator keylist = partOfDoclist.getDocids();
962
         StringBuffer doclist = new StringBuffer();
963
         while (keylist.hasNext())
964
         {
965
             doclist.append("'");
966
             doclist.append((String) keylist.next());
967
             doclist.append("',");
968
         }//while
969

    
970

    
971
         if (doclist.length() > 0)
972
         {
973
             doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
974

    
975
             // the query to find out docids from xml_queryresult
976
             String query = "select docid, queryresult_string from "
977
                          + "xml_queryresult where returnfield_id = " +
978
                          returnfield_id +" and docid in ("+ doclist + ")";
979
             logMetacat.info("Query to get docids from xml_queryresult:"
980
                                      + query);
981

    
982
             try {
983
                 // prepare and execute the query
984
                 pstmt = dbconn.prepareStatement(query);
985
                 dbconn.increaseUsageCount(1);
986
                 pstmt.execute();
987
                 rs = pstmt.getResultSet();
988
                 boolean tableHasRows = rs.next();
989
                 while (tableHasRows) {
990
                     // store the returned results in the returnValue hashtable
991
                     String key = rs.getString(1);
992
                     String element = rs.getString(2);
993

    
994
                     if(element != null){
995
                         returnValue.put(key, element);
996
                     } else {
997
                         logMetacat.info("Null elment found ("
998
                         + "DBQuery.docidsInQueryresultTable)");
999
                     }
1000
                     tableHasRows = rs.next();
1001
                 }
1002
                 rs.close();
1003
                 pstmt.close();
1004
             } catch (Exception e){
1005
                 logMetacat.error("Error getting docids from "
1006
                                          + "queryresult in "
1007
                                          + "DBQuery.docidsInQueryresultTable: "
1008
                                          + e.getMessage());
1009
              }
1010
         }
1011
         return returnValue;
1012
     }
1013

    
1014

    
1015
   /**
1016
    * Method to get id from xml_returnfield table
1017
    * for a given query specification
1018
    */
1019
   private int returnfield_id;
1020
   private int getXmlReturnfieldsTableId(QuerySpecification qspec,
1021
                                           DBConnection dbconn){
1022
       int id = -1;
1023
       int count = 1;
1024
       PreparedStatement pstmt = null;
1025
       ResultSet rs = null;
1026
       String returnfield = qspec.getSortedReturnFieldString();
1027

    
1028
       // query for finding the id from xml_returnfield
1029
       String query = "SELECT returnfield_id, usage_count FROM xml_returnfield "
1030
            + "WHERE returnfield_string LIKE ?";
1031
       logMetacat.info("ReturnField Query:" + query);
1032

    
1033
       try {
1034
           // prepare and run the query
1035
           pstmt = dbconn.prepareStatement(query);
1036
           pstmt.setString(1,returnfield);
1037
           dbconn.increaseUsageCount(1);
1038
           pstmt.execute();
1039
           rs = pstmt.getResultSet();
1040
           boolean tableHasRows = rs.next();
1041

    
1042
           // if record found then increase the usage count
1043
           // else insert a new record and get the id of the new record
1044
           if(tableHasRows){
1045
               // get the id
1046
               id = rs.getInt(1);
1047
               count = rs.getInt(2) + 1;
1048
               rs.close();
1049
               pstmt.close();
1050

    
1051
               // increase the usage count
1052
               query = "UPDATE xml_returnfield SET usage_count ='" + count
1053
                   + "' WHERE returnfield_id ='"+ id +"'";
1054
               logMetacat.info("ReturnField Table Update:"+ query);
1055

    
1056
               pstmt = dbconn.prepareStatement(query);
1057
               dbconn.increaseUsageCount(1);
1058
               pstmt.execute();
1059
               pstmt.close();
1060

    
1061
           } else {
1062
               rs.close();
1063
               pstmt.close();
1064

    
1065
               // insert a new record
1066
               query = "INSERT INTO xml_returnfield (returnfield_string, usage_count)"
1067
                   + "VALUES (?, '1')";
1068
               logMetacat.info("ReturnField Table Insert:"+ query);
1069
               pstmt = dbconn.prepareStatement(query);
1070
               pstmt.setString(1, returnfield);
1071
               dbconn.increaseUsageCount(1);
1072
               pstmt.execute();
1073
               pstmt.close();
1074

    
1075
               // get the id of the new record
1076
               query = "SELECT returnfield_id FROM xml_returnfield "
1077
                   + "WHERE returnfield_string LIKE ?";
1078
               logMetacat.info("ReturnField query after Insert:" + query);
1079
               pstmt = dbconn.prepareStatement(query);
1080
               pstmt.setString(1, returnfield);
1081

    
1082
               dbconn.increaseUsageCount(1);
1083
               pstmt.execute();
1084
               rs = pstmt.getResultSet();
1085
               if(rs.next()){
1086
                   id = rs.getInt(1);
1087
               } else {
1088
                   id = -1;
1089
               }
1090
               rs.close();
1091
               pstmt.close();
1092
           }
1093

    
1094
       } catch (Exception e){
1095
           logMetacat.error("Error getting id from xml_returnfield in "
1096
                                     + "DBQuery.getXmlReturnfieldsTableId: "
1097
                                     + e.getMessage());
1098
           id = -1;
1099
       }
1100

    
1101
       returnfield_id = id;
1102
       return count;
1103
   }
1104

    
1105

    
1106
    /*
1107
     * A method to add return field to return doclist hash table
1108
     */
1109
    private ResultDocumentSet addReturnfield(ResultDocumentSet docListResult,
1110
                                      QuerySpecification qspec,
1111
                                      String user, String[]groups,
1112
                                      DBConnection dbconn, boolean useXMLIndex )
1113
                                      throws Exception
1114
    {
1115
      PreparedStatement pstmt = null;
1116
      ResultSet rs = null;
1117
      String docid = null;
1118
      String fieldname = null;
1119
      String fieldtype = null;
1120
      String fielddata = null;
1121
      String relation = null;
1122

    
1123
      if (qspec.containsExtendedSQL())
1124
      {
1125
        qspec.setUserName(user);
1126
        qspec.setGroup(groups);
1127
        Vector extendedFields = new Vector(qspec.getReturnFieldList());
1128
        Vector results = new Vector();
1129
        Iterator keylist = docListResult.getDocids();
1130
        StringBuffer doclist = new StringBuffer();
1131
        Vector parentidList = new Vector();
1132
        Hashtable returnFieldValue = new Hashtable();
1133
        while (keylist.hasNext())
1134
        {
1135
          doclist.append("'");
1136
          doclist.append((String) keylist.next());
1137
          doclist.append("',");
1138
        }
1139
        if (doclist.length() > 0)
1140
        {
1141
          Hashtable controlPairs = new Hashtable();
1142
          doclist.deleteCharAt(doclist.length() - 1); //remove the last comma
1143
          boolean tableHasRows = false;
1144
        
1145

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

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

    
1176
                   //handle case when usexmlindex is true differently
1177
                   //at one point merging the nodedata (for large text elements) was 
1178
                   //deemed unnecessary - but now it is needed.  but not for attribute nodes
1179
                   if (useXMLIndex || !containsKey(parentidList, parentId)) {
1180
                	   //merge node data only for non-ATTRIBUTEs
1181
                	   if (fieldtype != null && !fieldtype.equals("ATTRIBUTE")) {
1182
	                	   //try merging the data
1183
	                	   ReturnFieldValue existingRFV =
1184
	                		   getArrayValue(parentidList, parentId);
1185
	                	   if (existingRFV != null) {
1186
	                		   fielddata = existingRFV.getFieldValue() + fielddata;
1187
	                	   }
1188
                	   }
1189
                       value.append("<param name=\"");
1190
                       value.append(fieldname);
1191
                       value.append("\">");
1192
                       value.append(fielddata);
1193
                       value.append("</param>");
1194
                       //set returnvalue
1195
                       returnValue.setDocid(docid);
1196
                       returnValue.setFieldValue(fielddata);
1197
                       returnValue.setFieldType(fieldtype);
1198
                       returnValue.setXMLFieldValue(value.toString());
1199
                       // Store it in hastable
1200
                       putInArray(parentidList, parentId, returnValue);
1201
                   }
1202
                   else {
1203
                       // need to merge nodedata if they have same parent id and
1204
                       // node type is text
1205
                       fielddata = (String) ( (ReturnFieldValue)
1206
                                             getArrayValue(
1207
                           parentidList, parentId)).getFieldValue()
1208
                           + fielddata;
1209
                       value.append("<param name=\"");
1210
                       value.append(fieldname);
1211
                       value.append("\">");
1212
                       value.append(fielddata);
1213
                       value.append("</param>");
1214
                       returnValue.setDocid(docid);
1215
                       returnValue.setFieldValue(fielddata);
1216
                       returnValue.setFieldType(fieldtype);
1217
                       returnValue.setXMLFieldValue(value.toString());
1218
                       // remove the old return value from paretnidList
1219
                       parentidList.remove(parentId);
1220
                       // store the new return value in parentidlit
1221
                       putInArray(parentidList, parentId, returnValue);
1222
                   }
1223
                   tableHasRows = rs.next();
1224
               } //while
1225
               rs.close();
1226
               pstmt.close();
1227

    
1228
               // put the merger node data info into doclistReult
1229
               Enumeration xmlFieldValue = (getElements(parentidList)).
1230
                   elements();
1231
               while (xmlFieldValue.hasMoreElements()) {
1232
                   ReturnFieldValue object =
1233
                       (ReturnFieldValue) xmlFieldValue.nextElement();
1234
                   docid = object.getDocid();
1235
                   if (docListResult.containsDocid(docid)) {
1236
                       String removedelement = (String) docListResult.
1237
                           remove(docid);
1238
                       docListResult.
1239
                           addResultDocument(new ResultDocument(docid,
1240
                               removedelement + object.getXMLFieldValue()));
1241
                   }
1242
                   else {
1243
                       docListResult.addResultDocument(
1244
                         new ResultDocument(docid, object.getXMLFieldValue()));
1245
                   }
1246
               } //while
1247
               double docListResultEnd = System.currentTimeMillis() / 1000;
1248
               logMetacat.warn(
1249
                   "Time to prepare ResultDocumentSet after"
1250
                   + " execute extended query: "
1251
                   + (docListResultEnd - extendedQueryEnd));
1252
           }
1253

    
1254
         
1255
           
1256
           
1257
       }//if doclist lenght is great than zero
1258

    
1259
     }//if has extended query
1260

    
1261
      return docListResult;
1262
    }//addReturnfield
1263

    
1264
  
1265
  /**
1266
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
1267
   * string as a param instead of a hashtable.
1268
   *
1269
   * @param xmlquery a string representing a query.
1270
   */
1271
   private  String transformQuery(String xmlquery)
1272
   {
1273
     xmlquery = xmlquery.trim();
1274
     int index = xmlquery.indexOf("?>");
1275
     if (index != -1)
1276
     {
1277
       return xmlquery.substring(index + 2, xmlquery.length());
1278
     }
1279
     else
1280
     {
1281
       return xmlquery;
1282
     }
1283
   }
1284
   
1285
   /*
1286
    * Method to store query string and result xml string into query result
1287
    * cache. If the size alreay reache the limitation, the cache will be
1288
    * cleared first, then store them.
1289
    */
1290
   private void storeQueryResultIntoCache(String query, String resultXML)
1291
   {
1292
	   synchronized (queryResultCache)
1293
	   {
1294
		   if (queryResultCache.size() >= QUERYRESULTCACHESIZE)
1295
		   {
1296
			   queryResultCache.clear();
1297
		   }
1298
		   queryResultCache.put(query, resultXML);
1299
		   
1300
	   }
1301
   }
1302
   
1303
   /*
1304
    * Method to get result xml string from query result cache. 
1305
    * Note: the returned string can be null.
1306
    */
1307
   private String getResultXMLFromCache(String query)
1308
   {
1309
	   String resultSet = null;
1310
	   synchronized (queryResultCache)
1311
	   {
1312
          try
1313
          {
1314
        	 logMetacat.info("Get query from cache ===");
1315
		     resultSet = (String)queryResultCache.get(query);
1316
		   
1317
          }
1318
          catch (Exception e)
1319
          {
1320
        	  resultSet = null;
1321
          }
1322
		   
1323
	   }
1324
	   return resultSet;
1325
   }
1326
   
1327
   /**
1328
    * Method to clear the query result cache.
1329
    */
1330
   public static void clearQueryResultCache()
1331
   {
1332
	   synchronized (queryResultCache)
1333
	   {
1334
		   queryResultCache.clear();
1335
	   }
1336
   }
1337

    
1338

    
1339
    /*
1340
     * A method to search if Vector contains a particular key string
1341
     */
1342
    private boolean containsKey(Vector parentidList, String parentId)
1343
    {
1344

    
1345
        Vector tempVector = null;
1346

    
1347
        for (int count = 0; count < parentidList.size(); count++) {
1348
            tempVector = (Vector) parentidList.get(count);
1349
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return true; }
1350
        }
1351
        return false;
1352
    }
1353
    
1354
    /*
1355
     * A method to put key and value in Vector
1356
     */
1357
    private void putInArray(Vector parentidList, String key,
1358
            ReturnFieldValue value)
1359
    {
1360

    
1361
        Vector tempVector = null;
1362
        //only filter if the field type is NOT an attribute (say, for text)
1363
        String fieldType = value.getFieldType();
1364
        if (fieldType != null && !fieldType.equals("ATTRIBUTE")) {
1365
        
1366
	        for (int count = 0; count < parentidList.size(); count++) {
1367
	            tempVector = (Vector) parentidList.get(count);
1368
	
1369
	            if (key.compareTo((String) tempVector.get(0)) == 0) {
1370
	                tempVector.remove(1);
1371
	                tempVector.add(1, value);
1372
	                return;
1373
	            }
1374
	        }
1375
        }
1376

    
1377
        tempVector = new Vector();
1378
        tempVector.add(0, key);
1379
        tempVector.add(1, value);
1380
        parentidList.add(tempVector);
1381
        return;
1382
    }
1383

    
1384
    /*
1385
     * A method to get value in Vector given a key
1386
     */
1387
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
1388
    {
1389

    
1390
        Vector tempVector = null;
1391

    
1392
        for (int count = 0; count < parentidList.size(); count++) {
1393
            tempVector = (Vector) parentidList.get(count);
1394

    
1395
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
1396
                    .get(1); }
1397
        }
1398
        return null;
1399
    }
1400

    
1401
    /*
1402
     * A method to get enumeration of all values in Vector
1403
     */
1404
    private Vector getElements(Vector parentidList)
1405
    {
1406
        Vector enumVector = new Vector();
1407
        Vector tempVector = null;
1408

    
1409
        for (int count = 0; count < parentidList.size(); count++) {
1410
            tempVector = (Vector) parentidList.get(count);
1411

    
1412
            enumVector.add(tempVector.get(1));
1413
        }
1414
        return enumVector;
1415
    }
1416

    
1417
  
1418

    
1419
    /*
1420
     * A method to create a query to get owner's docid list
1421
     */
1422
    private String getOwnerQuery(String owner)
1423
    {
1424
        if (owner != null) {
1425
            owner = owner.toLowerCase();
1426
        }
1427
        StringBuffer self = new StringBuffer();
1428

    
1429
        self.append("SELECT docid,docname,doctype,");
1430
        self.append("date_created, date_updated, rev ");
1431
        self.append("FROM xml_documents WHERE docid IN (");
1432
        self.append("(");
1433
        self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
1434
        self.append("nodedata LIKE '%%%' ");
1435
        self.append(") \n");
1436
        self.append(") ");
1437
        self.append(" AND (");
1438
        self.append(" lower(user_owner) = '" + owner + "'");
1439
        self.append(") ");
1440
        return self.toString();
1441
    }
1442

    
1443
    /**
1444
     * format a structured query as an XML document that conforms to the
1445
     * pathquery.dtd and is appropriate for submission to the DBQuery
1446
     * structured query engine
1447
     *
1448
     * @param params The list of parameters that should be included in the
1449
     *            query
1450
     */
1451
    public static String createSQuery(Hashtable params)
1452
    {
1453
        StringBuffer query = new StringBuffer();
1454
        Enumeration elements;
1455
        Enumeration keys;
1456
        String filterDoctype = null;
1457
        String casesensitive = null;
1458
        String searchmode = null;
1459
        Object nextkey;
1460
        Object nextelement;
1461
        //add the xml headers
1462
        query.append("<?xml version=\"1.0\"?>\n");
1463
        query.append("<pathquery version=\"1.2\">\n");
1464

    
1465

    
1466

    
1467
        if (params.containsKey("meta_file_id")) {
1468
            query.append("<meta_file_id>");
1469
            query.append(((String[]) params.get("meta_file_id"))[0]);
1470
            query.append("</meta_file_id>");
1471
        }
1472

    
1473
        if (params.containsKey("returndoctype")) {
1474
            String[] returnDoctypes = ((String[]) params.get("returndoctype"));
1475
            for (int i = 0; i < returnDoctypes.length; i++) {
1476
                String doctype = (String) returnDoctypes[i];
1477

    
1478
                if (!doctype.equals("any") && !doctype.equals("ANY")
1479
                        && !doctype.equals("")) {
1480
                    query.append("<returndoctype>").append(doctype);
1481
                    query.append("</returndoctype>");
1482
                }
1483
            }
1484
        }
1485

    
1486
        if (params.containsKey("filterdoctype")) {
1487
            String[] filterDoctypes = ((String[]) params.get("filterdoctype"));
1488
            for (int i = 0; i < filterDoctypes.length; i++) {
1489
                query.append("<filterdoctype>").append(filterDoctypes[i]);
1490
                query.append("</filterdoctype>");
1491
            }
1492
        }
1493

    
1494
        if (params.containsKey("returnfield")) {
1495
            String[] returnfield = ((String[]) params.get("returnfield"));
1496
            for (int i = 0; i < returnfield.length; i++) {
1497
                query.append("<returnfield>").append(returnfield[i]);
1498
                query.append("</returnfield>");
1499
            }
1500
        }
1501

    
1502
        if (params.containsKey("owner")) {
1503
            String[] owner = ((String[]) params.get("owner"));
1504
            for (int i = 0; i < owner.length; i++) {
1505
                query.append("<owner>").append(owner[i]);
1506
                query.append("</owner>");
1507
            }
1508
        }
1509

    
1510
        if (params.containsKey("site")) {
1511
            String[] site = ((String[]) params.get("site"));
1512
            for (int i = 0; i < site.length; i++) {
1513
                query.append("<site>").append(site[i]);
1514
                query.append("</site>");
1515
            }
1516
        }
1517

    
1518
        //allows the dynamic switching of boolean operators
1519
        if (params.containsKey("operator")) {
1520
            query.append("<querygroup operator=\""
1521
                    + ((String[]) params.get("operator"))[0] + "\">");
1522
        } else { //the default operator is UNION
1523
            query.append("<querygroup operator=\"UNION\">");
1524
        }
1525

    
1526
        if (params.containsKey("casesensitive")) {
1527
            casesensitive = ((String[]) params.get("casesensitive"))[0];
1528
        } else {
1529
            casesensitive = "false";
1530
        }
1531

    
1532
        if (params.containsKey("searchmode")) {
1533
            searchmode = ((String[]) params.get("searchmode"))[0];
1534
        } else {
1535
            searchmode = "contains";
1536
        }
1537

    
1538
        //anyfield is a special case because it does a
1539
        //free text search. It does not have a <pathexpr>
1540
        //tag. This allows for a free text search within the structured
1541
        //query. This is useful if the INTERSECT operator is used.
1542
        if (params.containsKey("anyfield")) {
1543
            String[] anyfield = ((String[]) params.get("anyfield"));
1544
            //allow for more than one value for anyfield
1545
            for (int i = 0; i < anyfield.length; i++) {
1546
                if (!anyfield[i].equals("")) {
1547
                    query.append("<queryterm casesensitive=\"" + casesensitive
1548
                            + "\" " + "searchmode=\"" + searchmode
1549
                            + "\"><value>" + anyfield[i]
1550
                            + "</value></queryterm>");
1551
                }
1552
            }
1553
        }
1554

    
1555
        //this while loop finds the rest of the parameters
1556
        //and attempts to query for the field specified
1557
        //by the parameter.
1558
        elements = params.elements();
1559
        keys = params.keys();
1560
        while (keys.hasMoreElements() && elements.hasMoreElements()) {
1561
            nextkey = keys.nextElement();
1562
            nextelement = elements.nextElement();
1563

    
1564
            //make sure we aren't querying for any of these
1565
            //parameters since the are already in the query
1566
            //in one form or another.
1567
            Vector ignoredParams = new Vector();
1568
            ignoredParams.add("returndoctype");
1569
            ignoredParams.add("filterdoctype");
1570
            ignoredParams.add("action");
1571
            ignoredParams.add("qformat");
1572
            ignoredParams.add("anyfield");
1573
            ignoredParams.add("returnfield");
1574
            ignoredParams.add("owner");
1575
            ignoredParams.add("site");
1576
            ignoredParams.add("operator");
1577
            ignoredParams.add("sessionid");
1578
            ignoredParams.add("pagesize");
1579
            ignoredParams.add("pagestart");
1580

    
1581
            // Also ignore parameters listed in the properties file
1582
            // so that they can be passed through to stylesheets
1583
            String paramsToIgnore = MetaCatUtil
1584
                    .getOption("query.ignored.params");
1585
            StringTokenizer st = new StringTokenizer(paramsToIgnore, ",");
1586
            while (st.hasMoreTokens()) {
1587
                ignoredParams.add(st.nextToken());
1588
            }
1589
            if (!ignoredParams.contains(nextkey.toString())) {
1590
                //allow for more than value per field name
1591
                for (int i = 0; i < ((String[]) nextelement).length; i++) {
1592
                    if (!((String[]) nextelement)[i].equals("")) {
1593
                        query.append("<queryterm casesensitive=\""
1594
                                + casesensitive + "\" " + "searchmode=\""
1595
                                + searchmode + "\">" + "<value>" +
1596
                                //add the query value
1597
                                ((String[]) nextelement)[i]
1598
                                + "</value><pathexpr>" +
1599
                                //add the path to query by
1600
                                nextkey.toString() + "</pathexpr></queryterm>");
1601
                    }
1602
                }
1603
            }
1604
        }
1605
        query.append("</querygroup></pathquery>");
1606
        //append on the end of the xml and return the result as a string
1607
        return query.toString();
1608
    }
1609

    
1610
    /**
1611
     * format a simple free-text value query as an XML document that conforms
1612
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1613
     * structured query engine
1614
     *
1615
     * @param value the text string to search for in the xml catalog
1616
     * @param doctype the type of documents to include in the result set -- use
1617
     *            "any" or "ANY" for unfiltered result sets
1618
     */
1619
    public static String createQuery(String value, String doctype)
1620
    {
1621
        StringBuffer xmlquery = new StringBuffer();
1622
        xmlquery.append("<?xml version=\"1.0\"?>\n");
1623
        xmlquery.append("<pathquery version=\"1.0\">");
1624

    
1625
        if (!doctype.equals("any") && !doctype.equals("ANY")) {
1626
            xmlquery.append("<returndoctype>");
1627
            xmlquery.append(doctype).append("</returndoctype>");
1628
        }
1629

    
1630
        xmlquery.append("<querygroup operator=\"UNION\">");
1631
        //chad added - 8/14
1632
        //the if statement allows a query to gracefully handle a null
1633
        //query. Without this if a nullpointerException is thrown.
1634
        if (!value.equals("")) {
1635
            xmlquery.append("<queryterm casesensitive=\"false\" ");
1636
            xmlquery.append("searchmode=\"contains\">");
1637
            xmlquery.append("<value>").append(value).append("</value>");
1638
            xmlquery.append("</queryterm>");
1639
        }
1640
        xmlquery.append("</querygroup>");
1641
        xmlquery.append("</pathquery>");
1642

    
1643
        return (xmlquery.toString());
1644
    }
1645

    
1646
    /**
1647
     * format a simple free-text value query as an XML document that conforms
1648
     * to the pathquery.dtd and is appropriate for submission to the DBQuery
1649
     * structured query engine
1650
     *
1651
     * @param value the text string to search for in the xml catalog
1652
     */
1653
    public static String createQuery(String value)
1654
    {
1655
        return createQuery(value, "any");
1656
    }
1657

    
1658
    /**
1659
     * Check for "READ" permission on @docid for @user and/or @group from DB
1660
     * connection
1661
     */
1662
    private boolean hasPermission(String user, String[] groups, String docid)
1663
            throws SQLException, Exception
1664
    {
1665
        // Check for READ permission on @docid for @user and/or @groups
1666
        PermissionController controller = new PermissionController(docid);
1667
        return controller.hasPermission(user, groups,
1668
                AccessControlInterface.READSTRING);
1669
    }
1670

    
1671
    /**
1672
     * Get all docIds list for a data packadge
1673
     *
1674
     * @param dataPackageDocid, the string in docId field of xml_relation table
1675
     */
1676
    private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
1677
    {
1678
        DBConnection dbConn = null;
1679
        int serialNumber = -1;
1680
        Vector docIdList = new Vector();//return value
1681
        PreparedStatement pStmt = null;
1682
        ResultSet rs = null;
1683
        String docIdInSubjectField = null;
1684
        String docIdInObjectField = null;
1685

    
1686
        // Check the parameter
1687
        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
1688

    
1689
        //the query stirng
1690
        String query = "SELECT subject, object from xml_relation where docId = ?";
1691
        try {
1692
            dbConn = DBConnectionPool
1693
                    .getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
1694
            serialNumber = dbConn.getCheckOutSerialNumber();
1695
            pStmt = dbConn.prepareStatement(query);
1696
            //bind the value to query
1697
            pStmt.setString(1, dataPackageDocid);
1698

    
1699
            //excute the query
1700
            pStmt.execute();
1701
            //get the result set
1702
            rs = pStmt.getResultSet();
1703
            //process the result
1704
            while (rs.next()) {
1705
                //In order to get the whole docIds in a data packadge,
1706
                //we need to put the docIds of subject and object field in
1707
                // xml_relation
1708
                //into the return vector
1709
                docIdInSubjectField = rs.getString(1);//the result docId in
1710
                                                      // subject field
1711
                docIdInObjectField = rs.getString(2);//the result docId in
1712
                                                     // object field
1713

    
1714
                //don't put the duplicate docId into the vector
1715
                if (!docIdList.contains(docIdInSubjectField)) {
1716
                    docIdList.add(docIdInSubjectField);
1717
                }
1718

    
1719
                //don't put the duplicate docId into the vector
1720
                if (!docIdList.contains(docIdInObjectField)) {
1721
                    docIdList.add(docIdInObjectField);
1722
                }
1723
            }//while
1724
            //close the pStmt
1725
            pStmt.close();
1726
        }//try
1727
        catch (SQLException e) {
1728
            logMetacat.error("Error in getDocidListForDataPackage: "
1729
                    + e.getMessage());
1730
        }//catch
1731
        finally {
1732
            try {
1733
                pStmt.close();
1734
            }//try
1735
            catch (SQLException ee) {
1736
                logMetacat.error(
1737
                        "Error in getDocidListForDataPackage: "
1738
                                + ee.getMessage());
1739
            }//catch
1740
            finally {
1741
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1742
            }//fianlly
1743
        }//finally
1744
        return docIdList;
1745
    }//getCurrentDocidListForDataPackadge()
1746

    
1747
    /**
1748
     * Get all docIds list for a data packadge
1749
     *
1750
     * @param dataPackageDocid, the string in docId field of xml_relation table
1751
     */
1752
    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
1753
    {
1754

    
1755
        Vector docIdList = new Vector();//return value
1756
        Vector tripleList = null;
1757
        String xml = null;
1758

    
1759
        // Check the parameter
1760
        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
1761

    
1762
        try {
1763
            //initial a documentImpl object
1764
            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
1765
            //transfer to documentImpl object to string
1766
            xml = packageDocument.toString();
1767

    
1768
            //create a tripcollection object
1769
            TripleCollection tripleForPackage = new TripleCollection(
1770
                    new StringReader(xml));
1771
            //get the vetor of triples
1772
            tripleList = tripleForPackage.getCollection();
1773

    
1774
            for (int i = 0; i < tripleList.size(); i++) {
1775
                //put subject docid into docIdlist without duplicate
1776
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1777
                        .getSubject())) {
1778
                    //put subject docid into docIdlist
1779
                    docIdList.add(((Triple) tripleList.get(i)).getSubject());
1780
                }
1781
                //put object docid into docIdlist without duplicate
1782
                if (!docIdList.contains(((Triple) tripleList.elementAt(i))
1783
                        .getObject())) {
1784
                    docIdList.add(((Triple) (tripleList.get(i))).getObject());
1785
                }
1786
            }//for
1787
        }//try
1788
        catch (Exception e) {
1789
            logMetacat.error("Error in getOldVersionAllDocumentImpl: "
1790
                    + e.getMessage());
1791
        }//catch
1792

    
1793
        // return result
1794
        return docIdList;
1795
    }//getDocidListForPackageInXMLRevisions()
1796

    
1797
    /**
1798
     * Check if the docId is a data packadge id. If the id is a data packadage
1799
     * id, it should be store in the docId fields in xml_relation table. So we
1800
     * can use a query to get the entries which the docId equals the given
1801
     * value. If the result is null. The docId is not a packadge id. Otherwise,
1802
     * it is.
1803
     *
1804
     * @param docId, the id need to be checked
1805
     */
1806
    private boolean isDataPackageId(String docId)
1807
    {
1808
        boolean result = false;
1809
        PreparedStatement pStmt = null;
1810
        ResultSet rs = null;
1811
        String query = "SELECT docId from xml_relation where docId = ?";
1812
        DBConnection dbConn = null;
1813
        int serialNumber = -1;
1814
        try {
1815
            dbConn = DBConnectionPool
1816
                    .getDBConnection("DBQuery.isDataPackageId");
1817
            serialNumber = dbConn.getCheckOutSerialNumber();
1818
            pStmt = dbConn.prepareStatement(query);
1819
            //bind the value to query
1820
            pStmt.setString(1, docId);
1821
            //execute the query
1822
            pStmt.execute();
1823
            rs = pStmt.getResultSet();
1824
            //process the result
1825
            if (rs.next()) //There are some records for the id in docId fields
1826
            {
1827
                result = true;//It is a data packadge id
1828
            }
1829
            pStmt.close();
1830
        }//try
1831
        catch (SQLException e) {
1832
            logMetacat.error("Error in isDataPackageId: "
1833
                    + e.getMessage());
1834
        } finally {
1835
            try {
1836
                pStmt.close();
1837
            }//try
1838
            catch (SQLException ee) {
1839
                logMetacat.error("Error in isDataPackageId: "
1840
                        + ee.getMessage());
1841
            }//catch
1842
            finally {
1843
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1844
            }//finally
1845
        }//finally
1846
        return result;
1847
    }//isDataPackageId()
1848

    
1849
    /**
1850
     * Check if the user has the permission to export data package
1851
     *
1852
     * @param conn, the connection
1853
     * @param docId, the id need to be checked
1854
     * @param user, the name of user
1855
     * @param groups, the user's group
1856
     */
1857
    private boolean hasPermissionToExportPackage(String docId, String user,
1858
            String[] groups) throws Exception
1859
    {
1860
        //DocumentImpl doc=new DocumentImpl(conn,docId);
1861
        return DocumentImpl.hasReadPermission(user, groups, docId);
1862
    }
1863

    
1864
    /**
1865
     * Get the current Rev for a docid in xml_documents table
1866
     *
1867
     * @param docId, the id need to get version numb If the return value is -5,
1868
     *            means no value in rev field for this docid
1869
     */
1870
    private int getCurrentRevFromXMLDoumentsTable(String docId)
1871
            throws SQLException
1872
    {
1873
        int rev = -5;
1874
        PreparedStatement pStmt = null;
1875
        ResultSet rs = null;
1876
        String query = "SELECT rev from xml_documents where docId = ?";
1877
        DBConnection dbConn = null;
1878
        int serialNumber = -1;
1879
        try {
1880
            dbConn = DBConnectionPool
1881
                    .getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
1882
            serialNumber = dbConn.getCheckOutSerialNumber();
1883
            pStmt = dbConn.prepareStatement(query);
1884
            //bind the value to query
1885
            pStmt.setString(1, docId);
1886
            //execute the query
1887
            pStmt.execute();
1888
            rs = pStmt.getResultSet();
1889
            //process the result
1890
            if (rs.next()) //There are some records for rev
1891
            {
1892
                rev = rs.getInt(1);
1893
                ;//It is the version for given docid
1894
            } else {
1895
                rev = -5;
1896
            }
1897

    
1898
        }//try
1899
        catch (SQLException e) {
1900
            logMetacat.error(
1901
                    "Error in getCurrentRevFromXMLDoumentsTable: "
1902
                            + e.getMessage());
1903
            throw e;
1904
        }//catch
1905
        finally {
1906
            try {
1907
                pStmt.close();
1908
            }//try
1909
            catch (SQLException ee) {
1910
                logMetacat.error(
1911
                        "Error in getCurrentRevFromXMLDoumentsTable: "
1912
                                + ee.getMessage());
1913
            }//catch
1914
            finally {
1915
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1916
            }//finally
1917
        }//finally
1918
        return rev;
1919
    }//getCurrentRevFromXMLDoumentsTable
1920

    
1921
    /**
1922
     * put a doc into a zip output stream
1923
     *
1924
     * @param docImpl, docmentImpl object which will be sent to zip output
1925
     *            stream
1926
     * @param zipOut, zip output stream which the docImpl will be put
1927
     * @param packageZipEntry, the zip entry name for whole package
1928
     */
1929
    private void addDocToZipOutputStream(DocumentImpl docImpl,
1930
            ZipOutputStream zipOut, String packageZipEntry)
1931
            throws ClassNotFoundException, IOException, SQLException,
1932
            McdbException, Exception
1933
    {
1934
        byte[] byteString = null;
1935
        ZipEntry zEntry = null;
1936

    
1937
        byteString = docImpl.toString().getBytes();
1938
        //use docId as the zip entry's name
1939
        zEntry = new ZipEntry(packageZipEntry + "/metadata/"
1940
                + docImpl.getDocID());
1941
        zEntry.setSize(byteString.length);
1942
        zipOut.putNextEntry(zEntry);
1943
        zipOut.write(byteString, 0, byteString.length);
1944
        zipOut.closeEntry();
1945

    
1946
    }//addDocToZipOutputStream()
1947

    
1948
    /**
1949
     * Transfer a docid vetor to a documentImpl vector. The documentImpl vetor
1950
     * only inlcudes current version. If a DocumentImple object couldn't find
1951
     * for a docid, then the String of this docid was added to vetor rather
1952
     * than DocumentImple object.
1953
     *
1954
     * @param docIdList, a vetor hold a docid list for a data package. In
1955
     *            docid, there is not version number in it.
1956
     */
1957

    
1958
    private Vector getCurrentAllDocumentImpl(Vector docIdList)
1959
            throws McdbException, Exception
1960
    {
1961
        //Connection dbConn=null;
1962
        Vector documentImplList = new Vector();
1963
        int rev = 0;
1964

    
1965
        // Check the parameter
1966
        if (docIdList.isEmpty()) { return documentImplList; }//if
1967

    
1968
        //for every docid in vector
1969
        for (int i = 0; i < docIdList.size(); i++) {
1970
            try {
1971
                //get newest version for this docId
1972
                rev = getCurrentRevFromXMLDoumentsTable((String) docIdList
1973
                        .elementAt(i));
1974

    
1975
                // There is no record for this docId in xml_documents table
1976
                if (rev == -5) {
1977
                    // Rather than put DocumentImple object, put a String
1978
                    // Object(docid)
1979
                    // into the documentImplList
1980
                    documentImplList.add((String) docIdList.elementAt(i));
1981
                    // Skip other code
1982
                    continue;
1983
                }
1984

    
1985
                String docidPlusVersion = ((String) docIdList.elementAt(i))
1986
                        + MetaCatUtil.getOption("accNumSeparator") + rev;
1987

    
1988
                //create new documentImpl object
1989
                DocumentImpl documentImplObject = new DocumentImpl(
1990
                        docidPlusVersion);
1991
                //add them to vector
1992
                documentImplList.add(documentImplObject);
1993
            }//try
1994
            catch (Exception e) {
1995
                logMetacat.error("Error in getCurrentAllDocumentImpl: "
1996
                        + e.getMessage());
1997
                // continue the for loop
1998
                continue;
1999
            }
2000
        }//for
2001
        return documentImplList;
2002
    }
2003

    
2004
    /**
2005
     * Transfer a docid vetor to a documentImpl vector. If a DocumentImple
2006
     * object couldn't find for a docid, then the String of this docid was
2007
     * added to vetor rather than DocumentImple object.
2008
     *
2009
     * @param docIdList, a vetor hold a docid list for a data package. In
2010
     *            docid, t here is version number in it.
2011
     */
2012
    private Vector getOldVersionAllDocumentImpl(Vector docIdList)
2013
    {
2014
        //Connection dbConn=null;
2015
        Vector documentImplList = new Vector();
2016
        String siteCode = null;
2017
        String uniqueId = null;
2018
        int rev = 0;
2019

    
2020
        // Check the parameter
2021
        if (docIdList.isEmpty()) { return documentImplList; }//if
2022

    
2023
        //for every docid in vector
2024
        for (int i = 0; i < docIdList.size(); i++) {
2025

    
2026
            String docidPlusVersion = (String) (docIdList.elementAt(i));
2027

    
2028
            try {
2029
                //create new documentImpl object
2030
                DocumentImpl documentImplObject = new DocumentImpl(
2031
                        docidPlusVersion);
2032
                //add them to vector
2033
                documentImplList.add(documentImplObject);
2034
            }//try
2035
            catch (McdbDocNotFoundException notFoundE) {
2036
                logMetacat.error(
2037
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2038
                                + notFoundE.getMessage());
2039
                // Rather than add a DocumentImple object into vetor, a String
2040
                // object
2041
                // - the doicd was added to the vector
2042
                documentImplList.add(docidPlusVersion);
2043
                // Continue the for loop
2044
                continue;
2045
            }//catch
2046
            catch (Exception e) {
2047
                logMetacat.error(
2048
                        "Error in DBQuery.getOldVersionAllDocument" + "Imple"
2049
                                + e.getMessage());
2050
                // Continue the for loop
2051
                continue;
2052
            }//catch
2053

    
2054
        }//for
2055
        return documentImplList;
2056
    }//getOldVersionAllDocumentImple
2057

    
2058
    /**
2059
     * put a data file into a zip output stream
2060
     *
2061
     * @param docImpl, docmentImpl object which will be sent to zip output
2062
     *            stream
2063
     * @param zipOut, the zip output stream which the docImpl will be put
2064
     * @param packageZipEntry, the zip entry name for whole package
2065
     */
2066
    private void addDataFileToZipOutputStream(DocumentImpl docImpl,
2067
            ZipOutputStream zipOut, String packageZipEntry)
2068
            throws ClassNotFoundException, IOException, SQLException,
2069
            McdbException, Exception
2070
    {
2071
        byte[] byteString = null;
2072
        ZipEntry zEntry = null;
2073
        // this is data file; add file to zip
2074
        String filePath = MetaCatUtil.getOption("datafilepath");
2075
        if (!filePath.endsWith("/")) {
2076
            filePath += "/";
2077
        }
2078
        String fileName = filePath + docImpl.getDocID();
2079
        zEntry = new ZipEntry(packageZipEntry + "/data/" + docImpl.getDocID());
2080
        zipOut.putNextEntry(zEntry);
2081
        FileInputStream fin = null;
2082
        try {
2083
            fin = new FileInputStream(fileName);
2084
            byte[] buf = new byte[4 * 1024]; // 4K buffer
2085
            int b = fin.read(buf);
2086
            while (b != -1) {
2087
                zipOut.write(buf, 0, b);
2088
                b = fin.read(buf);
2089
            }//while
2090
            zipOut.closeEntry();
2091
        }//try
2092
        catch (IOException ioe) {
2093
            logMetacat.error("There is an exception: "
2094
                    + ioe.getMessage());
2095
        }//catch
2096
    }//addDataFileToZipOutputStream()
2097

    
2098
    /**
2099
     * create a html summary for data package and put it into zip output stream
2100
     *
2101
     * @param docImplList, the documentImpl ojbects in data package
2102
     * @param zipOut, the zip output stream which the html should be put
2103
     * @param packageZipEntry, the zip entry name for whole package
2104
     */
2105
    private void addHtmlSummaryToZipOutputStream(Vector docImplList,
2106
            ZipOutputStream zipOut, String packageZipEntry) throws Exception
2107
    {
2108
        StringBuffer htmlDoc = new StringBuffer();
2109
        ZipEntry zEntry = null;
2110
        byte[] byteString = null;
2111
        InputStream source;
2112
        DBTransform xmlToHtml;
2113

    
2114
        //create a DBTransform ojbect
2115
        xmlToHtml = new DBTransform();
2116
        //head of html
2117
        htmlDoc.append("<html><head></head><body>");
2118
        for (int i = 0; i < docImplList.size(); i++) {
2119
            // If this String object, this means it is missed data file
2120
            if ((((docImplList.elementAt(i)).getClass()).toString())
2121
                    .equals("class java.lang.String")) {
2122

    
2123
                htmlDoc.append("<a href=\"");
2124
                String dataFileid = (String) docImplList.elementAt(i);
2125
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2126
                htmlDoc.append("Data File: ");
2127
                htmlDoc.append(dataFileid).append("</a><br>");
2128
                htmlDoc.append("<br><hr><br>");
2129

    
2130
            }//if
2131
            else if ((((DocumentImpl) docImplList.elementAt(i)).getDoctype())
2132
                    .compareTo("BIN") != 0) { //this is an xml file so we can
2133
                                              // transform it.
2134
                //transform each file individually then concatenate all of the
2135
                //transformations together.
2136

    
2137
                //for metadata xml title
2138
                htmlDoc.append("<h2>");
2139
                htmlDoc.append(((DocumentImpl) docImplList.elementAt(i))
2140
                        .getDocID());
2141
                //htmlDoc.append(".");
2142
                //htmlDoc.append(((DocumentImpl)docImplList.elementAt(i)).getRev());
2143
                htmlDoc.append("</h2>");
2144
                //do the actual transform
2145
                StringWriter docString = new StringWriter();
2146
                xmlToHtml.transformXMLDocument(((DocumentImpl) docImplList
2147
                        .elementAt(i)).toString(), "-//NCEAS//eml-generic//EN",
2148
                        "-//W3C//HTML//EN", "html", docString);
2149
                htmlDoc.append(docString.toString());
2150
                htmlDoc.append("<br><br><hr><br><br>");
2151
            }//if
2152
            else { //this is a data file so we should link to it in the html
2153
                htmlDoc.append("<a href=\"");
2154
                String dataFileid = ((DocumentImpl) docImplList.elementAt(i))
2155
                        .getDocID();
2156
                htmlDoc.append("./data/").append(dataFileid).append("\">");
2157
                htmlDoc.append("Data File: ");
2158
                htmlDoc.append(dataFileid).append("</a><br>");
2159
                htmlDoc.append("<br><hr><br>");
2160
            }//else
2161
        }//for
2162
        htmlDoc.append("</body></html>");
2163
        byteString = htmlDoc.toString().getBytes();
2164
        zEntry = new ZipEntry(packageZipEntry + "/metadata.html");
2165
        zEntry.setSize(byteString.length);
2166
        zipOut.putNextEntry(zEntry);
2167
        zipOut.write(byteString, 0, byteString.length);
2168
        zipOut.closeEntry();
2169
        //dbConn.close();
2170

    
2171
    }//addHtmlSummaryToZipOutputStream
2172

    
2173
    /**
2174
     * put a data packadge into a zip output stream
2175
     *
2176
     * @param docId, which the user want to put into zip output stream,it has version
2177
     * @param out, a servletoutput stream which the zip output stream will be
2178
     *            put
2179
     * @param user, the username of the user
2180
     * @param groups, the group of the user
2181
     */
2182
    public ZipOutputStream getZippedPackage(String docIdString,
2183
            ServletOutputStream out, String user, String[] groups,
2184
            String passWord) throws ClassNotFoundException, IOException,
2185
            SQLException, McdbException, NumberFormatException, Exception
2186
    {
2187
        ZipOutputStream zOut = null;
2188
        String elementDocid = null;
2189
        DocumentImpl docImpls = null;
2190
        //Connection dbConn = null;
2191
        Vector docIdList = new Vector();
2192
        Vector documentImplList = new Vector();
2193
        Vector htmlDocumentImplList = new Vector();
2194
        String packageId = null;
2195
        String rootName = "package";//the package zip entry name
2196

    
2197
        String docId = null;
2198
        int version = -5;
2199
        // Docid without revision
2200
        docId = MetaCatUtil.getDocIdFromString(docIdString);
2201
        // revision number
2202
        version = MetaCatUtil.getVersionFromString(docIdString);
2203

    
2204
        //check if the reqused docId is a data package id
2205
        if (!isDataPackageId(docId)) {
2206

    
2207
            /*
2208
             * Exception e = new Exception("The request the doc id "
2209
             * +docIdString+ " is not a data package id");
2210
             */
2211

    
2212
            //CB 1/6/03: if the requested docid is not a datapackage, we just
2213
            // zip
2214
            //up the single document and return the zip file.
2215
            if (!hasPermissionToExportPackage(docId, user, groups)) {
2216

    
2217
                Exception e = new Exception("User " + user
2218
                        + " does not have permission"
2219
                        + " to export the data package " + docIdString);
2220
                throw e;
2221
            }
2222

    
2223
            docImpls = new DocumentImpl(docIdString);
2224
            //checking if the user has the permission to read the documents
2225
            if (DocumentImpl.hasReadPermission(user, groups, docImpls
2226
                    .getDocID())) {
2227
                zOut = new ZipOutputStream(out);
2228
                //if the docImpls is metadata
2229
                if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2230
                    //add metadata into zip output stream
2231
                    addDocToZipOutputStream(docImpls, zOut, rootName);
2232
                }//if
2233
                else {
2234
                    //it is data file
2235
                    addDataFileToZipOutputStream(docImpls, zOut, rootName);
2236
                    htmlDocumentImplList.add(docImpls);
2237
                }//else
2238
            }//if
2239

    
2240
            zOut.finish(); //terminate the zip file
2241
            return zOut;
2242
        }
2243
        // Check the permission of user
2244
        else if (!hasPermissionToExportPackage(docId, user, groups)) {
2245

    
2246
            Exception e = new Exception("User " + user
2247
                    + " does not have permission"
2248
                    + " to export the data package " + docIdString);
2249
            throw e;
2250
        } else //it is a packadge id
2251
        {
2252
            //store the package id
2253
            packageId = docId;
2254
            //get current version in database
2255
            int currentVersion = getCurrentRevFromXMLDoumentsTable(packageId);
2256
            //If it is for current version (-1 means user didn't specify
2257
            // revision)
2258
            if ((version == -1) || version == currentVersion) {
2259
                //get current version number
2260
                version = currentVersion;
2261
                //get package zip entry name
2262
                //it should be docId.revsion.package
2263
                rootName = packageId + MetaCatUtil.getOption("accNumSeparator")
2264
                        + version + MetaCatUtil.getOption("accNumSeparator")
2265
                        + "package";
2266
                //get the whole id list for data packadge
2267
                docIdList = getCurrentDocidListForDataPackage(packageId);
2268
                //get the whole documentImple object
2269
                documentImplList = getCurrentAllDocumentImpl(docIdList);
2270

    
2271
            }//if
2272
            else if (version > currentVersion || version < -1) {
2273
                throw new Exception("The user specified docid: " + docId + "."
2274
                        + version + " doesn't exist");
2275
            }//else if
2276
            else //for an old version
2277
            {
2278

    
2279
                rootName = docIdString
2280
                        + MetaCatUtil.getOption("accNumSeparator") + "package";
2281
                //get the whole id list for data packadge
2282
                docIdList = getOldVersionDocidListForDataPackage(docIdString);
2283

    
2284
                //get the whole documentImple object
2285
                documentImplList = getOldVersionAllDocumentImpl(docIdList);
2286
            }//else
2287

    
2288
            // Make sure documentImplist is not empty
2289
            if (documentImplList.isEmpty()) { throw new Exception(
2290
                    "Couldn't find component for data package: " + packageId); }//if
2291

    
2292
            zOut = new ZipOutputStream(out);
2293
            //put every element into zip output stream
2294
            for (int i = 0; i < documentImplList.size(); i++) {
2295
                // if the object in the vetor is String, this means we couldn't
2296
                // find
2297
                // the document locally, we need find it remote
2298
                if ((((documentImplList.elementAt(i)).getClass()).toString())
2299
                        .equals("class java.lang.String")) {
2300
                    // Get String object from vetor
2301
                    String documentId = (String) documentImplList.elementAt(i);
2302
                    logMetacat.info("docid: " + documentId);
2303
                    // Get doicd without revision
2304
                    String docidWithoutRevision = MetaCatUtil
2305
                            .getDocIdFromString(documentId);
2306
                    logMetacat.info("docidWithoutRevsion: "
2307
                            + docidWithoutRevision);
2308
                    // Get revision
2309
                    String revision = MetaCatUtil
2310
                            .getRevisionStringFromString(documentId);
2311
                    logMetacat.info("revsion from docIdentifier: "
2312
                            + revision);
2313
                    // Zip entry string
2314
                    String zipEntryPath = rootName + "/data/";
2315
                    // Create a RemoteDocument object
2316
                    RemoteDocument remoteDoc = new RemoteDocument(
2317
                            docidWithoutRevision, revision, user, passWord,
2318
                            zipEntryPath);
2319
                    // Here we only read data file from remote metacat
2320
                    String docType = remoteDoc.getDocType();
2321
                    if (docType != null) {
2322
                        if (docType.equals("BIN")) {
2323
                            // Put remote document to zip output
2324
                            remoteDoc.readDocumentFromRemoteServerByZip(zOut);
2325
                            // Add String object to htmlDocumentImplList
2326
                            String elementInHtmlList = remoteDoc
2327
                                    .getDocIdWithoutRevsion()
2328
                                    + MetaCatUtil.getOption("accNumSeparator")
2329
                                    + remoteDoc.getRevision();
2330
                            htmlDocumentImplList.add(elementInHtmlList);
2331
                        }//if
2332
                    }//if
2333

    
2334
                }//if
2335
                else {
2336
                    //create a docmentImpls object (represent xml doc) base on
2337
                    // the docId
2338
                    docImpls = (DocumentImpl) documentImplList.elementAt(i);
2339
                    //checking if the user has the permission to read the
2340
                    // documents
2341
                    if (DocumentImpl.hasReadPermission(user, groups, docImpls
2342
                            .getDocID())) {
2343
                        //if the docImpls is metadata
2344
                        if ((docImpls.getDoctype()).compareTo("BIN") != 0) {
2345
                            //add metadata into zip output stream
2346
                            addDocToZipOutputStream(docImpls, zOut, rootName);
2347
                            //add the documentImpl into the vetor which will
2348
                            // be used in html
2349
                            htmlDocumentImplList.add(docImpls);
2350

    
2351
                        }//if
2352
                        else {
2353
                            //it is data file
2354
                            addDataFileToZipOutputStream(docImpls, zOut,
2355
                                    rootName);
2356
                            htmlDocumentImplList.add(docImpls);
2357
                        }//else
2358
                    }//if
2359
                }//else
2360
            }//for
2361

    
2362
            //add html summary file
2363
            addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut,
2364
                    rootName);
2365
            zOut.finish(); //terminate the zip file
2366
            //dbConn.close();
2367
            return zOut;
2368
        }//else
2369
    }//getZippedPackage()
2370

    
2371
    private class ReturnFieldValue
2372
    {
2373

    
2374
        private String docid = null; //return field value for this docid
2375

    
2376
        private String fieldValue = null;
2377

    
2378
        private String xmlFieldValue = null; //return field value in xml
2379
                                             // format
2380
        private String fieldType = null; //ATTRIBUTE, TEXT...
2381

    
2382
        public void setDocid(String myDocid)
2383
        {
2384
            docid = myDocid;
2385
        }
2386

    
2387
        public String getDocid()
2388
        {
2389
            return docid;
2390
        }
2391

    
2392
        public void setFieldValue(String myValue)
2393
        {
2394
            fieldValue = myValue;
2395
        }
2396

    
2397
        public String getFieldValue()
2398
        {
2399
            return fieldValue;
2400
        }
2401

    
2402
        public void setXMLFieldValue(String xml)
2403
        {
2404
            xmlFieldValue = xml;
2405
        }
2406

    
2407
        public String getXMLFieldValue()
2408
        {
2409
            return xmlFieldValue;
2410
        }
2411
        
2412
        public void setFieldType(String myType)
2413
        {
2414
            fieldType = myType;
2415
        }
2416

    
2417
        public String getFieldType()
2418
        {
2419
            return fieldType;
2420
        }
2421

    
2422
    }
2423
    
2424
    /**
2425
     * a class to store one result document consisting of a docid and a document
2426
     */
2427
    private class ResultDocument
2428
    {
2429
      public String docid;
2430
      public String document;
2431
      
2432
      public ResultDocument(String docid, String document)
2433
      {
2434
        this.docid = docid;
2435
        this.document = document;
2436
      }
2437
    }
2438
    
2439
    /**
2440
     * a private class to handle a set of resultDocuments
2441
     */
2442
    private class ResultDocumentSet
2443
    {
2444
      private Vector docids;
2445
      private Vector documents;
2446
      
2447
      public ResultDocumentSet()
2448
      {
2449
        docids = new Vector();
2450
        documents = new Vector();
2451
      }
2452
      
2453
      /**
2454
       * adds a result document to the set
2455
       */
2456
      public void addResultDocument(ResultDocument rd)
2457
      {
2458
        if(rd.docid == null)
2459
          return;
2460
        if(rd.document == null)
2461
          rd.document = "";
2462
       
2463
           docids.addElement(rd.docid);
2464
           documents.addElement(rd.document);
2465
        
2466
      }
2467
      
2468
      /**
2469
       * gets an iterator of docids
2470
       */
2471
      public Iterator getDocids()
2472
      {
2473
        return docids.iterator();
2474
      }
2475
      
2476
      /**
2477
       * gets an iterator of documents
2478
       */
2479
      public Iterator getDocuments()
2480
      {
2481
        return documents.iterator();
2482
      }
2483
      
2484
      /**
2485
       * returns the size of the set
2486
       */
2487
      public int size()
2488
      {
2489
        return docids.size();
2490
      }
2491
      
2492
      /**
2493
       * tests to see if this set contains the given docid
2494
       */
2495
      private boolean containsDocid(String docid)
2496
      {
2497
        for(int i=0; i<docids.size(); i++)
2498
        {
2499
          String docid0 = (String)docids.elementAt(i);
2500
          if(docid0.trim().equals(docid.trim()))
2501
          {
2502
            return true;
2503
          }
2504
        }
2505
        return false;
2506
      }
2507
      
2508
      /**
2509
       * removes the element with the given docid
2510
       */
2511
      public String remove(String docid)
2512
      {
2513
        for(int i=0; i<docids.size(); i++)
2514
        {
2515
          String docid0 = (String)docids.elementAt(i);
2516
          if(docid0.trim().equals(docid.trim()))
2517
          {
2518
            String returnDoc = (String)documents.elementAt(i);
2519
            documents.remove(i);
2520
            docids.remove(i);
2521
            return returnDoc;
2522
          }
2523
        }
2524
        return null;
2525
      }
2526
      
2527
      /**
2528
       * add a result document
2529
       */
2530
      public void put(ResultDocument rd)
2531
      {
2532
        addResultDocument(rd);
2533
      }
2534
      
2535
      /**
2536
       * add a result document by components
2537
       */
2538
      public void put(String docid, String document)
2539
      {
2540
        addResultDocument(new ResultDocument(docid, document));
2541
      }
2542
      
2543
      /**
2544
       * get the document part of the result document by docid
2545
       */
2546
      public Object get(String docid)
2547
      {
2548
        for(int i=0; i<docids.size(); i++)
2549
        {
2550
          String docid0 = (String)docids.elementAt(i);
2551
          if(docid0.trim().equals(docid.trim()))
2552
          {
2553
            return documents.elementAt(i);
2554
          }
2555
        }
2556
        return null;
2557
      }
2558
      
2559
      /**
2560
       * get the document part of the result document by an object
2561
       */
2562
      public Object get(Object o)
2563
      {
2564
        return get((String)o);
2565
      }
2566
      
2567
      /**
2568
       * get an entire result document by index number
2569
       */
2570
      public ResultDocument get(int index)
2571
      {
2572
        return new ResultDocument((String)docids.elementAt(index), 
2573
          (String)documents.elementAt(index));
2574
      }
2575
      
2576
      /**
2577
       * return a string representation of this object
2578
       */
2579
      public String toString()
2580
      {
2581
        String s = "";
2582
        for(int i=0; i<docids.size(); i++)
2583
        {
2584
          s += (String)docids.elementAt(i) + "\n";
2585
        }
2586
        return s;
2587
      }
2588
      /*
2589
       * Set a new document value for a given docid
2590
       */
2591
      public void set(String docid, String document)
2592
      {
2593
    	   for(int i=0; i<docids.size(); i++)
2594
           {
2595
             String docid0 = (String)docids.elementAt(i);
2596
             if(docid0.trim().equals(docid.trim()))
2597
             {
2598
                 documents.set(i, document);
2599
             }
2600
           }
2601
           
2602
      }
2603
    }
2604
}
(20-20/64)