Project

General

Profile

1 51 jones
/**
2 203 jones
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6 361 berkley
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7 348 jones
 *    Release: @release@
8 154 jones
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 51 jones
 */
27
28
package edu.ucsb.nceas.metacat;
29
30 46 jones
import java.io.PrintWriter;
31
import java.io.IOException;
32 50 jones
import java.io.Reader;
33
import java.io.StringReader;
34 59 jones
import java.io.BufferedReader;
35 185 jones
import java.io.File;
36
import java.io.FileInputStream;
37 458 berkley
import java.io.FileOutputStream;
38
import java.io.InputStreamReader;
39 453 berkley
import java.io.DataInputStream;
40 46 jones
import java.util.Enumeration;
41
import java.util.Hashtable;
42 341 berkley
import java.util.ResourceBundle;
43 648 berkley
import java.util.Random;
44 82 jones
import java.util.PropertyResourceBundle;
45 50 jones
import java.net.URL;
46
import java.net.MalformedURLException;
47 85 jones
import java.sql.PreparedStatement;
48
import java.sql.ResultSet;
49 50 jones
import java.sql.Connection;
50 55 jones
import java.sql.SQLException;
51 361 berkley
import java.lang.reflect.*;
52 453 berkley
import java.net.*;
53 458 berkley
import java.util.zip.*;
54 46 jones
55
import javax.servlet.ServletConfig;
56
import javax.servlet.ServletContext;
57
import javax.servlet.ServletException;
58 48 jones
import javax.servlet.ServletInputStream;
59 46 jones
import javax.servlet.http.HttpServlet;
60
import javax.servlet.http.HttpServletRequest;
61
import javax.servlet.http.HttpServletResponse;
62 210 bojilova
import javax.servlet.http.HttpSession;
63 47 jones
import javax.servlet.http.HttpUtils;
64 458 berkley
import javax.servlet.ServletOutputStream;
65 46 jones
66 50 jones
import oracle.xml.parser.v2.XSLStylesheet;
67
import oracle.xml.parser.v2.XSLException;
68
import oracle.xml.parser.v2.XMLDocumentFragment;
69
import oracle.xml.parser.v2.XSLProcessor;
70
71 204 jones
import org.xml.sax.SAXException;
72
73 46 jones
/**
74
 * A metadata catalog server implemented as a Java Servlet
75 154 jones
 *
76
 * <p>Valid parameters are:<br>
77
 * action=query -- query the values of all elements and attributes
78
 *                     and return a result set of nodes<br>
79 205 jones
 * action=squery -- structured query (see pathquery.dtd)<br>
80
 * action=insert -- insert an XML document into the database store<br>
81
 * action=update -- update an XML document that is in the database store<br>
82
 * action=delete --  delete an XML document from the database store<br>
83
 * action=validate -- vallidate the xml contained in valtext<br>
84 566 jones
 * action=read -- display an XML document in XML or HTML<br>
85 205 jones
 * doctype -- document type list returned by the query (publicID)<br>
86 154 jones
 * qformat=xml -- display resultset from query in XML<br>
87
 * qformat=html -- display resultset from query in HTML<br>
88
 * docid=34 -- display the document with the document ID number 34<br>
89 205 jones
 * doctext -- XML text of the document to load into the database<br>
90 598 bojilova
 * acltext -- XML access text for a document to load into the database<br>
91
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog<br>
92 183 jones
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
93 205 jones
 * valtext -- XML text to be validated<br>
94
 * action=getdatadoc -- retreive a stored datadocument<br>
95 302 bojilova
 * action=getdoctypes -- retreive all doctypes (publicID)<br>
96
 * action=getdataguide -- retreive a Data Guide<br>
97 205 jones
 * datadoc -- data document name (id)<br>
98
 * <p>
99
 * The particular combination of parameters that are valid for each
100
 * particular action value is quite specific.  This documentation
101
 * will be reorganized to reflect this information.
102 46 jones
 */
103
public class MetaCatServlet extends HttpServlet {
104
105 370 berkley
  private ServletConfig config = null;
106
  private ServletContext context = null;
107
  private Hashtable connectionPool = new Hashtable();
108
  private String resultStyleURL = null;
109
  private String xmlcatalogfile = null;
110
  private String saxparser = null;
111
  private String defaultdatapath = null;
112
  private String servletpath = null;
113 380 jones
  private PropertyResourceBundle options = null;
114
  private MetaCatUtil util = null;
115
116
  // path to directory where data files
117
  // that can be downloaded will be stored
118 370 berkley
  private String htmlpath = null;
119 380 jones
  // script to get data file and put it
120
  // in defaultdocpath dir
121 370 berkley
  private String executescript  = null;
122 46 jones
123 50 jones
  /**
124
   * Initialize the servlet by creating appropriate database connections
125
   */
126 46 jones
  public void init( ServletConfig config ) throws ServletException {
127
    try {
128
      super.init( config );
129
      this.config = config;
130 332 bojilova
      this.context = config.getServletContext();
131 184 jones
      System.out.println("MetaCatServlet Initialize");
132 82 jones
133 184 jones
      util = new MetaCatUtil();
134
135 83 jones
      // Get the configuration file information
136 184 jones
      resultStyleURL = util.getOption("resultStyleURL");
137
      xmlcatalogfile = util.getOption("xmlcatalogfile");
138
      saxparser = util.getOption("saxparser");
139
      defaultdatapath = util.getOption("defaultdatapath");
140 593 berkley
      executescript = util.getOption("executescript");
141 360 bojilova
      servletpath = util.getOption("servletpath");
142
      htmlpath = util.getOption("htmlpath");
143 598 bojilova
144
//      try {
145
//        // Open a pool of db connections
146
//        connectionPool = util.getConnectionPool();
147
//      } catch (Exception e) {
148
//        System.err.println("Error creating pool of database connections");
149
//        System.err.println(e.getMessage());
150
//      }
151 46 jones
    } catch ( ServletException ex ) {
152
      throw ex;
153
    }
154
  }
155
156 320 bojilova
  /**
157
   * Close all db connections from the pool
158
   */
159
  public void destroy() {
160
161
    if (util != null) {
162
        util.closeConnections();
163
    }
164
  }
165
166 50 jones
  /** Handle "GET" method requests from HTTP clients */
167 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
168
    throws ServletException, IOException {
169
170 48 jones
    // Process the data and send back the response
171 59 jones
    handleGetOrPost(request, response);
172 48 jones
  }
173
174 50 jones
  /** Handle "POST" method requests from HTTP clients */
175 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
176
    throws ServletException, IOException {
177
178
    // Process the data and send back the response
179 59 jones
    handleGetOrPost(request, response);
180 48 jones
  }
181
182 49 jones
  /**
183 50 jones
   * Control servlet response depending on the action parameter specified
184 49 jones
   */
185 382 berkley
  private void handleGetOrPost(HttpServletRequest request,
186 59 jones
    HttpServletResponse response)
187 355 berkley
    throws ServletException, IOException
188
 {
189 48 jones
190 309 bojilova
    if ( util == null ) {
191
        util = new MetaCatUtil();
192
    }
193 598 bojilova
    if ( connectionPool.isEmpty() ) {
194 309 bojilova
      try {
195
        // Open a pool of db connections
196
        connectionPool = util.getConnectionPool();
197
      } catch (Exception e) {
198
        System.err.println("Error creating pool of database connections");
199
        System.err.println(e.getMessage());
200
      }
201
    }
202 49 jones
    // Get a handle to the output stream back to the client
203 566 jones
    //PrintWriter pwout = response.getWriter();
204 102 jones
    //response.setContentType("text/html");
205 49 jones
206 59 jones
    String name = null;
207
    String[] value = null;
208 103 jones
    String[] docid = new String[3];
209 59 jones
    Hashtable params = new Hashtable();
210
    Enumeration paramlist = request.getParameterNames();
211
    while (paramlist.hasMoreElements()) {
212
      name = (String)paramlist.nextElement();
213
      value = request.getParameterValues(name);
214 103 jones
215
      // Decode the docid and mouse click information
216
      if (name.endsWith(".y")) {
217
        docid[0] = name.substring(0,name.length()-2);
218
        //out.println("docid => " + docid[0]);
219
        params.put("docid", docid);
220
        name = "ypos";
221
      }
222
      if (name.endsWith(".x")) {
223
        name = "xpos";
224 373 berkley
      }
225 103 jones
226 566 jones
      //pwout.println(name + " => " + value[0]);
227 373 berkley
      params.put(name,value);
228
    }
229 355 berkley
230 509 bojilova
    //if the user clicked on the input images, decode which image
231
    //was clicked then set the action.
232 505 jones
    String action = ((String[])params.get("action"))[0];
233
    util.debugMessage("Line 213: Action is: " + action);
234 509 bojilova
235 505 jones
    //MBJELIMINATE String action = decodeMouseAction(params);
236
    //if(action.equals("error"))
237
    //{
238 509 bojilova
      //util.debugMessage("Line 218: Action is: " + action);
239 505 jones
      //action = ((String[])params.get("action"))[0];
240
    //}
241 355 berkley
242 380 jones
    // This block handles session management for the servlet
243
    // by looking up the current session information for all actions
244 509 bojilova
    // other than "login" and "logout"
245 425 bojilova
    String username = null;
246
    String groupname = null;
247 648 berkley
    String sess_id = null;
248 509 bojilova
249
    // handle login action
250
    if (action.equals("login")) {
251
252 458 berkley
      handleLoginAction(response.getWriter(), params, request, response);
253 509 bojilova
254 210 bojilova
    // handle logout action
255 509 bojilova
    } else if (action.equals("logout")) {
256 361 berkley
257 509 bojilova
      handleLogoutAction(response.getWriter(), params, request, response);
258 361 berkley
259 251 bojilova
    // aware of session expiration on every request
260 343 jones
    } else {
261 509 bojilova
262 332 bojilova
      HttpSession sess = request.getSession(true);
263
      if (sess.isNew()) {
264 251 bojilova
        // session expired or has not been stored b/w user requests
265 441 bojilova
        username = "public";
266 673 bojilova
        sess.setAttribute("username", username);
267 425 bojilova
      } else {
268
        username = (String)sess.getAttribute("username");
269
        groupname = (String)sess.getAttribute("groupname");
270 648 berkley
        try
271
        {
272
          sess_id = (String)sess.getId();
273
        }
274
        catch(IllegalStateException ise)
275
        {
276
          System.out.println("error in handleGetOrPost: this shouldn't " +
277
                             "happen: the session should be valid: " +
278
                             ise.getMessage());
279
        }
280 425 bojilova
      }
281 210 bojilova
    }
282 219 jones
283 380 jones
    // Now that we know the session is valid, we can delegate the request
284
    // to a particular action handler
285 361 berkley
    if(action.equals("query"))
286
    {
287 458 berkley
      handleQuery(response.getWriter(), params, response, username, groupname);
288 373 berkley
    }
289 371 berkley
    else if(action.equals("squery"))
290 361 berkley
    {
291 373 berkley
      if(params.containsKey("query"))
292
      {
293 458 berkley
        handleSQuery(response.getWriter(), params, response, username, groupname);
294 373 berkley
      }
295
      else
296
      {
297 458 berkley
        PrintWriter out = response.getWriter();
298 373 berkley
        out.println("Illegal action squery without \"query\" parameter");
299
      }
300
    }
301 566 jones
    else if (action.equals("read")) {
302 636 berkley
      //PrintWriter out = response.getWriter();
303 87 jones
      try {
304 661 berkley
        handleReadAction(/*out,*/ params, response, username);
305 87 jones
      } catch (ClassNotFoundException e) {
306 636 berkley
        System.out.println(e.getMessage());
307 87 jones
      } catch (SQLException se) {
308 636 berkley
        System.out.println(se.getMessage());
309 87 jones
      }
310 453 berkley
    }
311 566 jones
/*
312 453 berkley
    else if (action.equals("getrelateddocument")) {
313 458 berkley
      PrintWriter out = response.getWriter();
314 453 berkley
      try {
315
        handleGetRelatedDocumentAction(out, params, response);
316
      } catch (ClassNotFoundException e) {
317
        out.println(e.getMessage());
318
      } catch (SQLException se) {
319
        out.println(se.getMessage());
320
      }
321
    }
322 566 jones
*/
323 453 berkley
    else if (action.equals("insert") || action.equals("update")) {
324 458 berkley
      PrintWriter out = response.getWriter();
325 509 bojilova
      if ( (username != null) &&  !username.equals("public") ) {
326 425 bojilova
        handleInsertOrUpdateAction(out, params, response, username, groupname);
327
      } else {
328
        out.println("Permission denied for " + action);
329
      }
330 203 jones
    } else if (action.equals("delete")) {
331 458 berkley
      PrintWriter out = response.getWriter();
332 509 bojilova
      if ( (username != null) &&  !username.equals("public") ) {
333 425 bojilova
        handleDeleteAction(out, params, response, username, groupname);
334
      } else {
335
        out.println("Permission denied for " + action);
336
      }
337 68 higgins
    } else if (action.equals("validate")) {
338 458 berkley
      PrintWriter out = response.getWriter();
339 437 berkley
      handleValidateAction(out, params, response);
340
    } else if (action.equals("getabstract")) {
341 458 berkley
      PrintWriter out = response.getWriter();
342 437 berkley
      try{
343
        handleViewAbstractAction(out, params, response);
344
      }
345
      catch(Exception e)
346
      {
347
        out.println("error viewing abstract: " + e.getMessage());
348
      }
349 91 higgins
    } else if (action.equals("getdatadoc")) {
350 458 berkley
      response.setContentType("application/zip");
351
      ServletOutputStream out = response.getOutputStream();
352 91 higgins
      handleGetDataDocumentAction(out, params, response);
353 302 bojilova
    } else if (action.equals("getdoctypes")) {
354 458 berkley
      PrintWriter out = response.getWriter();
355 302 bojilova
      handleGetDoctypesAction(out, params, response);
356 648 berkley
    } else if (action.equals("getdataport")) {
357
      PrintWriter out = response.getWriter();
358 649 berkley
      if ( (username != null) &&  !username.equals("public") ) {
359 648 berkley
      handleGetDataPortAction(out, params, response, username, groupname,
360
                              sess_id);
361 649 berkley
      } else {
362
        out.println("You must be authenticated to perform the getdataport " +
363
                    "action!");
364
      }
365 302 bojilova
    } else if (action.equals("getdataguide")) {
366 458 berkley
      PrintWriter out = response.getWriter();
367 302 bojilova
      handleGetDataGuideAction(out, params, response);
368 509 bojilova
    } else if (action.equals("login") || action.equals("logout")) {
369 566 jones
    } else if (action.equals("protocoltest")) {
370
      String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
371
      try {
372
        testURL = ((String[])params.get("url"))[0];
373
      } catch (Throwable t) {
374
      }
375
      String phandler = System.getProperty("java.protocol.handler.pkgs");
376
      response.setContentType("text/html");
377
      PrintWriter out = response.getWriter();
378
      out.println("<body bgcolor=\"white\">");
379
      out.println("<p>Handler property: <code>" + phandler + "</code></p>");
380
      out.println("<p>Starting test for:<br>");
381
      out.println("    " + testURL + "</p>");
382
      try {
383
        URL u = new URL(testURL);
384
        out.println("<pre>");
385
        out.println("Protocol: " + u.getProtocol());
386
        out.println("    Host: " + u.getHost());
387
        out.println("    Port: " + u.getPort());
388
        out.println("    Path: " + u.getPath());
389
        out.println("     Ref: " + u.getRef());
390
        String pquery = u.getQuery();
391
        out.println("   Query: " + pquery);
392
        out.println("  Params: ");
393
        if (pquery != null) {
394
          Hashtable qparams = util.parseQuery(u.getQuery());
395
          for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
396
            String pname = (String)en.nextElement();
397
            String pvalue = (String)qparams.get(pname);
398
            out.println("    " + pname + ": " + pvalue);
399
          }
400
        }
401
        out.println("</pre>");
402
        out.println("</body>");
403
        out.close();
404
      } catch (MalformedURLException mue) {
405
        out.println(mue.getMessage());
406
        mue.printStackTrace(out);
407
        out.close();
408
      }
409 50 jones
    } else {
410 458 berkley
      PrintWriter out = response.getWriter();
411 50 jones
      out.println("Error: action not registered.  Please report this error.");
412 46 jones
    }
413 465 berkley
    util.closeConnections();
414 49 jones
    // Close the stream to the client
415 458 berkley
    //out.close();
416 46 jones
  }
417 355 berkley
418
  /**
419
   * decodes the mouse click information coming from the client.
420
   * This function may be overwritten to provide specific functionality
421
   * for different applications.
422
   * @param params the parameters from the CGI
423
   * @return action the action to be performed or "error" if an error was
424
   * generated
425
   */
426 375 berkley
  protected String decodeMouseAction(Hashtable params)
427 355 berkley
  {
428
    // Determine what type of request the user made
429
    // if the action parameter is set, use it as a default
430
    // but if the ypos param is set, calculate the action needed
431
    String action=null;
432
    long ypos = 0;
433
    try {
434
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
435
      //out.println("<P>YPOS IS " + ypos);
436
      if (ypos <= 13) {
437 566 jones
        action = "read";
438 355 berkley
      } else if (ypos > 13 && ypos <= 27) {
439
        action = "validate";
440
      } else if (ypos > 27) {
441
        action = "transform";
442
      }
443
      return action;
444
    } catch (Exception npe) {
445 380 jones
      //
446
      // MBJ -- NOTE that this should be handled more gracefully with
447
      //        the new exception infrastructure -- this "error" return
448
      //        value is inappropriate
449 355 berkley
      //out.println("<P>Caught exception looking for Y value.");
450
      return "error";
451 382 berkley
    }
452 355 berkley
  }
453 648 berkley
454
  /**
455
   * sends the port number that the data socket is running on.  This is a
456
   * parameter set in the metacat.properties file.
457
   */
458
  private void handleGetDataPortAction(PrintWriter out, Hashtable params,
459
                                       HttpServletResponse response,
460
                                       String username, String groupname,
461
                                       String sess_id)
462
  {
463
    int port;
464
    String filedir = null;
465
    try
466
    {
467
      filedir = util.getOption("datafilepath");
468
469
      Random r = new Random();
470
      port = r.nextInt(65000);  //pick a random port between 0-65000
471
      //System.out.println("random port is: " + port);
472
      while(!DataFileServer.portIsAvailable(port))
473
      {
474
        port = r.nextInt(65000);
475
        //System.out.println("next port used: " + port);
476
      }
477
      DataFileServer dfs = new DataFileServer(port, username, sess_id);
478
      dfs.start();
479
480
      //System.out.println("filedir: " + filedir);
481
      //System.out.println("port: " + port);
482
      response.setContentType("text/xml");
483
      out.println("<?xml version=\"1.0\"?>");
484
      out.println("<port>");
485
      out.print(port);
486
      out.print("</port>");
487
488
    }
489
	  catch (Exception e)
490
    {
491
      System.out.println("error in handleGetDataPortAction: " + e.getMessage());
492
    }
493
  }
494 49 jones
495 50 jones
  /**
496 509 bojilova
   * Handle the login request. Create a new session object.
497 503 bojilova
   * Do user authentication through the session.
498 210 bojilova
   */
499
  private void handleLoginAction(PrintWriter out, Hashtable params,
500
               HttpServletRequest request, HttpServletResponse response) {
501 251 bojilova
502 503 bojilova
    AuthSession sess = null;
503 228 bojilova
    String un = ((String[])params.get("username"))[0];
504
    String pw = ((String[])params.get("password"))[0];
505 297 bojilova
    String action = ((String[])params.get("action"))[0];
506 509 bojilova
    String qformat = ((String[])params.get("qformat"))[0];
507 332 bojilova
508 297 bojilova
    try {
509 509 bojilova
      sess = new AuthSession();
510 297 bojilova
    } catch (Exception e) {
511
      out.println(e.getMessage());
512 509 bojilova
      return;
513 297 bojilova
    }
514 411 bojilova
515 509 bojilova
    boolean isValid = sess.authenticate(request, un, pw);
516
517
    // format and transform the output
518
    if (qformat.equals("html")) {
519
      Connection conn = null;
520 503 bojilova
      try {
521 509 bojilova
        conn = util.getConnection();
522
        DBTransform trans = new DBTransform(conn);
523
        response.setContentType("text/html");
524 510 bojilova
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
525
                                   "-//W3C//HTML//EN", out);
526 509 bojilova
        util.returnConnection(conn);
527
      } catch(Exception e) {
528
        util.returnConnection(conn);
529
      }
530
531
    // any output is returned
532
    } else {
533
      response.setContentType("text/xml");
534
      out.println(sess.getMessage());
535 503 bojilova
    }
536 510 bojilova
537
/* WITHOUT XSLT transformation
538
    // redirects response to html page
539
    if (qformat.equals("html")) {
540
      // user authentication successful
541
      if (isValid) {
542
        response.sendRedirect(
543
                 response.encodeRedirectUrl(htmlpath + "/metacat.html"));
544
      // unsuccessful user authentication
545
      } else {
546
        response.sendRedirect(htmlpath + "/login.html");
547
      }
548
    // any output is returned
549
    } else {
550
      response.setContentType("text/xml");
551
      out.println(sess.getMessage());
552
    }
553
*/
554 509 bojilova
555 370 berkley
  }
556 509 bojilova
557
  /**
558
   * Handle the logout request. Close the connection.
559
   */
560
  private void handleLogoutAction(PrintWriter out, Hashtable params,
561
               HttpServletRequest request, HttpServletResponse response) {
562
563
    String qformat = ((String[])params.get("qformat"))[0];
564
565
    // close the connection
566
    HttpSession sess = request.getSession(false);
567
    if (sess != null) { sess.invalidate();  }
568
569
    // produce output
570
    StringBuffer output = new StringBuffer();
571
    output.append("<?xml version=\"1.0\"?>");
572 510 bojilova
    output.append("<logout>");
573
    output.append("User logged out");
574
    output.append("</logout>");
575 509 bojilova
576
    //format and transform the output
577
    if (qformat.equals("html")) {
578
      Connection conn = null;
579
      try {
580
        conn = util.getConnection();
581
        DBTransform trans = new DBTransform(conn);
582
        response.setContentType("text/html");
583 510 bojilova
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
584
                                   "-//W3C//HTML//EN", out);
585 509 bojilova
        util.returnConnection(conn);
586
      } catch(Exception e) {
587
        util.returnConnection(conn);
588
      }
589
    // any output is returned
590
    } else {
591
      response.setContentType("text/xml");
592
      out.println(output.toString());
593
    }
594
595 510 bojilova
/* WITHOUT XSLT transformation
596
    // redirects response to html page
597
    if (qformat.equals("html")) {
598
        response.sendRedirect(htmlpath + "/index.html");
599
      } catch(Exception e) {
600
        util.returnConnection(conn);
601
      }
602
    // any output is returned
603
    } else {
604
      response.setContentType("text/xml");
605
      out.println(output.toString());
606
    }
607
*/
608 509 bojilova
  }
609
610 370 berkley
611 373 berkley
  /**
612 380 jones
   * Retreive the squery xml, execute it and display it
613
   *
614
   * @param out the output stream to the client
615
   * @param params the Hashtable of parameters that should be included
616
   * in the squery.
617
   * @param response the response object linked to the client
618
   * @param conn the database connection
619
   */
620
  protected void handleSQuery(PrintWriter out, Hashtable params,
621 441 bojilova
                 HttpServletResponse response, String user, String group)
622 373 berkley
  {
623 380 jones
    String xmlquery = ((String[])params.get("query"))[0];
624
    String qformat = ((String[])params.get("qformat"))[0];
625 465 berkley
    String resultdoc = null;
626
    String[] returndoc = null;
627
    if(params.contains("returndoc"))
628
    {
629
      returndoc = (String[])params.get("returndoc");
630
    }
631
632
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
633
    //String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
634 444 berkley
635 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
636
637 380 jones
    //format and transform the results
638
    if(qformat.equals("html")) {
639
      transformResultset(resultdoc, response, out);
640
    } else if(qformat.equals("xml")) {
641
      response.setContentType("text/xml");
642
      out.println(resultdoc);
643
    } else {
644
      out.println("invalid qformat: " + qformat);
645
    }
646 341 berkley
  }
647
648
   /**
649 380 jones
    * Create the xml query, execute it and display the results.
650
    *
651
    * @param out the output stream to the client
652
    * @param params the Hashtable of parameters that should be included
653 370 berkley
    * in the squery.
654 380 jones
    * @param response the response object linked to the client
655 370 berkley
    */
656 375 berkley
  protected void handleQuery(PrintWriter out, Hashtable params,
657 441 bojilova
                 HttpServletResponse response, String user, String group)
658 341 berkley
  {
659 370 berkley
    //create the query and run it
660 465 berkley
    String[] returndoc = null;
661
    if(params.containsKey("returndoc"))
662
    {
663
      returndoc = (String[])params.get("returndoc");
664
    }
665 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
666 465 berkley
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
667
    String qformat = ((String[])params.get("qformat"))[0];
668
    String resultdoc = null;
669
670
    resultdoc = createResultDocument(doclist, transformQuery(params));
671 425 bojilova
672 370 berkley
    //format and transform the results
673 380 jones
    if(qformat.equals("html")) {
674 370 berkley
      transformResultset(resultdoc, response, out);
675 380 jones
    } else if(qformat.equals("xml")) {
676 370 berkley
      response.setContentType("text/xml");
677
      out.println(resultdoc);
678 443 berkley
    } else {
679 370 berkley
      out.println("invalid qformat: " + qformat);
680
    }
681 341 berkley
  }
682
683
  /**
684 384 berkley
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
685
   * so it can properly be placed in the <query> tag of the resultset.
686
   * This method is overwritable so that other applications can customize
687
   * the structure of what is in the <query> tag.
688
   *
689
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
690
   */
691
  protected String transformQuery(Hashtable params)
692
  {
693
    //DBQuery.createSQuery is a re-calling of a previously called
694
    //function but it is necessary
695
    //so that overriding methods have access to the params hashtable
696
    String xmlquery = DBQuery.createSQuery(params);
697
    //the <?xml version="1.0"?> tag is the first 22 characters of the
698
    xmlquery = xmlquery.trim();
699
    int index = xmlquery.indexOf("?>");
700
    return xmlquery.substring(index + 2, xmlquery.length());
701
  }
702
703
  /**
704 443 berkley
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
705
   * string as a param instead of a hashtable.
706
   *
707
   * @param xmlquery a string representing a query.
708
   */
709
  protected String transformQuery(String xmlquery)
710
  {
711
    xmlquery = xmlquery.trim();
712
    int index = xmlquery.indexOf("?>");
713
    return xmlquery.substring(index + 2, xmlquery.length());
714
  }
715
716
  /**
717 380 jones
   * Run the query and return a hashtable of results.
718
   *
719
   * @param xmlquery the query to run
720
   */
721 465 berkley
  private Hashtable runQuery(String xmlquery, String user, String group,
722
                             String[] returndoc)
723 341 berkley
  {
724
    Hashtable doclist=null;
725
    Connection conn = null;
726
    try
727
    {
728 441 bojilova
      conn = util.getConnection();
729
      DBQuery queryobj = new DBQuery(conn, saxparser);
730 465 berkley
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
731
                                       returndoc);
732 441 bojilova
      util.returnConnection(conn);
733
      return doclist;
734 341 berkley
    }
735
    catch (Exception e)
736
    {
737 441 bojilova
      util.returnConnection(conn);
738 341 berkley
      util.debugMessage("Error in runQuery: " + e.getMessage());
739
      doclist = null;
740
      return doclist;
741
    }
742
  }
743
744 380 jones
  /**
745 370 berkley
   * Transorms an xml resultset document to html and sends it to the browser
746 380 jones
   *
747 370 berkley
   * @param resultdoc the string representation of the document that needs
748
   * to be transformed.
749
   * @param response the HttpServletResponse object bound to the client.
750
   * @param out the output stream to the client
751 375 berkley
   */
752
  protected void transformResultset(String resultdoc,
753 380 jones
                                    HttpServletResponse response,
754
                                    PrintWriter out)
755 370 berkley
  {
756
    Connection conn = null;
757 380 jones
    try {
758 370 berkley
      conn = util.getConnection();
759
      DBTransform trans = new DBTransform(conn);
760
      response.setContentType("text/html");
761
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
762
                                 "-//W3C//HTML//EN", out);
763 382 berkley
      util.returnConnection(conn);
764
    }
765
    catch(Exception e)
766
    {
767 441 bojilova
      util.returnConnection(conn);
768 370 berkley
    }
769
  }
770
771 355 berkley
  /**
772
   * Transforms a hashtable of documents to an xml or html result.
773 465 berkley
   * If there is a returndoc, then it only displays documents of
774
   * whatever type returndoc represents.  If a result is found in a document
775
   * that is not of type returndoc then this attempts to find a relation
776
   * between this document and one that satifies the returndoc doctype.
777 380 jones
   *
778 355 berkley
   * @param doclist- the hashtable to transform
779
   * @param xmlquery- the query that returned the dolist result
780 465 berkley
   * @param resultdoc- the document type to backtrack to.
781 355 berkley
   */
782 375 berkley
  protected String createResultDocument(Hashtable doclist, String xmlquery)
783 341 berkley
  {
784
    // Create a buffer to hold the xml result
785
    StringBuffer resultset = new StringBuffer();
786
787 382 berkley
    // Print the resulting root nodes
788 341 berkley
    String docid = null;
789
    String document = null;
790
    resultset.append("<?xml version=\"1.0\"?>\n");
791
    resultset.append("<resultset>\n");
792 465 berkley
793 384 berkley
    resultset.append("  <query>" + xmlquery + "</query>");
794 478 berkley
795
    if(doclist != null)
796 341 berkley
    {
797 478 berkley
      Enumeration doclistkeys = doclist.keys();
798
      while (doclistkeys.hasMoreElements())
799
      {
800
        docid = (String)doclistkeys.nextElement();
801
        document = (String)doclist.get(docid);
802
        resultset.append("  <document>" + document + "</document>");
803
      }
804
    }
805
806 341 berkley
    resultset.append("</resultset>");
807 444 berkley
    //System.out.println(resultset.toString());
808 370 berkley
    return resultset.toString();
809 341 berkley
  }
810 437 berkley
811
  /**
812
   * Handle the request to view the abstract of a document.
813 444 berkley
   * The abstractpath CGI parameter gives the xml path to the abstract
814
   * node.
815 437 berkley
   */
816
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
817
               HttpServletResponse response) throws IOException, SQLException
818
  {
819
    String abstractpath = null;
820
    String docid = null;
821
    Connection conn = null;
822
    response.setContentType("text/html");
823
    try
824
    {
825
      docid = ((String[])params.get("docid"))[0];
826
      if(params.containsKey("abstractpath"))
827
      {
828 444 berkley
        //the CGI parameter abstractpath holds the path to the abstract
829
        //that should be displayed.
830 437 berkley
        abstractpath = ((String[])params.get("abstractpath"))[0];
831
      }
832
      else
833
      {
834
        out.println("error: no abstractpath parameter");
835
      }
836
      conn = util.getConnection();
837
838
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
839
840 444 berkley
      out.println("<html><head><title>Abstract</title></head>");
841
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
842 437 berkley
      for(int i=0; i<abstracts.length; i++)
843
      {
844
        out.println("<p>" + (String)abstracts[i] + "</p>");
845
      }
846
      out.println("</body></html>");
847
    }
848
    catch (IOException ioe)
849
    {
850 444 berkley
       util.debugMessage("error in handlegetabstract: " + ioe.getMessage());
851 437 berkley
    }
852
    catch(SQLException sqle)
853
    {
854 444 berkley
      util.debugMessage("error in handlegetabstract: " + sqle.getMessage());
855 437 berkley
    }
856
    catch(Exception e)
857
    {
858 444 berkley
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
859 437 berkley
    }
860
861
    util.returnConnection(conn);
862
  }
863 181 jones
864 50 jones
  /**
865 453 berkley
   * Handle the database getrelateddocument request and return a XML document,
866
   * possibly transformed from XML into HTML
867
   */
868 566 jones
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params,
869
               HttpServletResponse response, URL murl)
870 453 berkley
               throws ClassNotFoundException, IOException, SQLException
871
  {
872
    String docid = null;
873
    Connection conn = null;
874
875 566 jones
    //if(params.containsKey("url"))
876
    //{//the identifier for the related document is contained in the URL param
877 453 berkley
      try
878
      {
879
        DocumentImpl xmldoc=null;
880 566 jones
        //MetacatURL murl = new MetacatURL(((String[])params.get("url"))[0]);
881
        if(murl.getProtocol().equals("metacat"))
882 453 berkley
        {//get the document from the database if it is the right type of url
883 566 jones
          //Hashtable murlParams = murl.getHashParams();
884
          Hashtable murlParams = util.parseQuery(murl.getQuery());
885 473 berkley
          if(murlParams.containsKey("docid"))
886 453 berkley
          {//the docid should be first
887 473 berkley
            docid = (String)murlParams.get("docid"); //get the docid value
888 453 berkley
            conn = util.getConnection();
889
            xmldoc = new DocumentImpl(conn, docid);
890 485 berkley
            String qformat = ((String[])params.get("qformat"))[0];
891
            if (qformat.equals("xml"))
892
            {
893
              // set content type and other response header fields first
894
              response.setContentType("text/xml");
895
              xmldoc.toXml(out);
896
              //out.println(xmldoc);
897
            }
898
            else if (qformat.equals("html"))
899
            {
900
              response.setContentType("text/html");
901
              // Look up the document type
902
              String sourcetype = xmldoc.getDoctype();
903
              // Transform the document to the new doctype
904
              DBTransform dbt = new DBTransform(conn);
905
              dbt.transformXMLDocument(xmldoc.toString(), sourcetype,
906
                                 "-//W3C//HTML//EN", out);
907
            }
908
909 473 berkley
            util.returnConnection(conn);
910 453 berkley
          }
911
          else
912
          {
913
            //throw new Exception("handleGetDocument: bad URL");
914
            System.err.println("handleGetDocument: bad URL");
915
          }
916
        }
917 566 jones
        else if(murl.getProtocol().equals("http"))
918 453 berkley
        {//get the document from the internet
919 566 jones
          //Hashtable murlParams = murl.getHashParams();
920
          Hashtable murlParams = util.parseQuery(murl.getQuery());
921 473 berkley
          if(murlParams.containsKey("httpurl"))
922 453 berkley
          {//httpurl is the param name for an http url.
923 473 berkley
            URL urlconn = new URL((String)murlParams.get("httpurl"));
924
            //create a new url obj.
925 458 berkley
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
926
            BufferedReader htmldoc = new BufferedReader(
927
                                   new InputStreamReader(urlconn.openStream()));
928 453 berkley
            //bind a data stream.
929
            try
930
            { //display the document
931
              String line=null;
932
              while((line = htmldoc.readLine()) != null)
933
              {
934
                out.println(line);
935
              }
936
            }
937
            catch(Exception e)
938
            {
939
              util.debugMessage("error viewing html document");
940
            }
941
          }
942
        }
943
      }
944
      catch (McdbException e) {
945
        response.setContentType("text/xml");
946
        e.toXml(out);
947
      } catch   (Throwable t) {
948
        response.setContentType("text/html");
949
        out.println(t.getMessage());
950
      } finally {
951
        util.returnConnection(conn);
952
      }
953 566 jones
    //} // end if
954 453 berkley
  }
955
956
  /**
957 566 jones
   * Handle the database read request and return an XML document,
958 50 jones
   * possibly transformed from XML into HTML
959
   */
960 636 berkley
  private void handleReadAction(/*PrintWriter out,*/ Hashtable params,
961 661 berkley
               HttpServletResponse response, String username)
962 566 jones
               throws ClassNotFoundException, IOException, SQLException
963
  {
964 636 berkley
     PrintWriter out;
965 566 jones
    try {
966
      //MetacatURL murl = new MetacatURL(((String[])params.get("docid"))[0]);
967 636 berkley
      if(params.containsKey(new String("qformat")) &&
968
         ((String[])params.get("qformat"))[0].equals("bin"))
969
      {
970 661 berkley
        handleGetData(params, response, username);
971 636 berkley
      }
972
      else
973
      {
974
        out = response.getWriter();
975
        URL murl = new URL(((String[])params.get("docid"))[0]);
976
        handleGetRelatedDocumentAction(out, params, response, murl);
977
      }
978 566 jones
    } catch (MalformedURLException mue) {
979 636 berkley
      System.out.println("in catch");
980
      out = response.getWriter();
981 566 jones
      handleGetDocumentAction(out, params, response);
982
    }
983
  }
984 636 berkley
985
  /**
986
   * Handle the read of a data file.
987
   */
988
  private void handleGetData(Hashtable params,
989 661 berkley
                             HttpServletResponse response, String username)
990 636 berkley
  {
991
    String docid = null;
992
    try
993
    {
994
      URL murl = new URL(((String[])params.get("docid"))[0]);
995
      Hashtable murlParams = util.parseQuery(murl.getQuery());
996
      if(murlParams.containsKey("docid"))
997
      {
998 641 berkley
        docid = (String)murlParams.get("docid");
999 636 berkley
      }
1000
    }
1001
    catch(MalformedURLException mue)
1002
    {
1003
      docid = ((String[])params.get("docid"))[0];
1004
    }
1005
1006
    File f = null;
1007
    FileInputStream fin = null;
1008
    Connection conn;
1009
1010
    try
1011
    {
1012
      StringBuffer sql = new StringBuffer();
1013
      sql.append("select docname from xml_documents where docid like '");
1014
      sql.append(docid).append("'");
1015
      conn = util.openDBConnection();
1016 661 berkley
1017
      AccessControlList aclobj = new AccessControlList(conn);
1018
      boolean hasPermission = aclobj.hasPermission("READ",username,docid);
1019
1020
      if(!hasPermission)
1021
      {
1022
        response.setContentType("text/html");
1023
        PrintWriter out = response.getWriter();
1024
        out.println("Error: you do not have permission to view this document");
1025
        return;
1026
      }
1027
      response.setContentType("application/octet-stream");
1028
      ServletOutputStream sosout = response.getOutputStream();
1029 636 berkley
      PreparedStatement pstmt = conn.prepareStatement(sql.toString());
1030
      pstmt.execute();
1031
      ResultSet rs = pstmt.getResultSet();
1032
      boolean tablehasrows = rs.next();
1033
      while(tablehasrows)
1034
      {
1035
        //get the file stream from the file then send it to the output stream
1036
        String filepath = util.getOption("datafilepath");
1037
        if(!filepath.endsWith("/"))
1038
        {
1039
          filepath += "/";
1040
        }
1041
        f = new File(filepath + rs.getString(1));
1042
        fin = new FileInputStream(f);
1043 661 berkley
1044 636 berkley
        int b = fin.read();
1045
        while(b != -1)
1046
        {
1047
          sosout.write(b);
1048
          b = fin.read();
1049
        }
1050
        tablehasrows = rs.next();
1051
      }
1052
1053
      fin.close();
1054 667 berkley
      pstmt.close();
1055 636 berkley
      conn.close();
1056
    }
1057
    catch(Exception e)
1058
    {
1059
      System.out.println("error in handleGetData: " + e.getMessage());
1060
      e.printStackTrace(System.out);
1061
    }
1062
  }
1063 566 jones
1064
  /**
1065
   * Handle the database read request and return an XML document,
1066
   * possibly transformed from XML into HTML
1067
   */
1068 382 berkley
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
1069 87 jones
               HttpServletResponse response)
1070
               throws ClassNotFoundException, IOException, SQLException {
1071 102 jones
    String docidstr = null;
1072 162 bojilova
    String docid = null;
1073 102 jones
    String doc = null;
1074 309 bojilova
    Connection conn = null;
1075
1076 102 jones
    try {
1077 87 jones
      // Find the document id number
1078 102 jones
      docidstr = ((String[])params.get("docid"))[0];
1079 162 bojilova
      docid = docidstr;
1080 625 berkley
1081 309 bojilova
      conn = util.getConnection();
1082 393 jones
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1083
      // Get the document indicated from the db
1084
      //doc = docreader.readXMLDocument(docid);
1085 85 jones
1086 87 jones
      // Return the document in XML or HTML format
1087 437 berkley
      String qformat=null;
1088
      if(params.containsKey("qformat"))
1089
      {
1090
        qformat = ((String[])params.get("qformat"))[0];
1091
      }
1092
      else
1093
      {
1094
        qformat = "html";
1095
      }
1096
      if (qformat.equals("xml")) {
1097 85 jones
        // set content type and other response header fields first
1098
        response.setContentType("text/xml");
1099 431 jones
        xmldoc.toXml(out);
1100
        //out.println(xmldoc);
1101 85 jones
      } else if (qformat.equals("html")) {
1102 437 berkley
        response.setContentType("text/html");
1103 87 jones
        // Look up the document type
1104 393 jones
        String sourcetype = xmldoc.getDoctype();
1105 87 jones
        // Transform the document to the new doctype
1106 393 jones
        DBTransform dbt = new DBTransform(conn);
1107
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype,
1108
                                 "-//W3C//HTML//EN", out);
1109 85 jones
      }
1110 343 jones
    } catch (McdbException e) {
1111
      response.setContentType("text/xml");
1112
      e.toXml(out);
1113
    } catch (Throwable t) {
1114 309 bojilova
      response.setContentType("text/html");
1115 343 jones
      out.println(t.getMessage());
1116 309 bojilova
    } finally {
1117 320 bojilova
      util.returnConnection(conn);
1118 309 bojilova
    }
1119
1120 49 jones
  }
1121 55 jones
1122
  /**
1123
   * Handle the database putdocument request and write an XML document
1124
   * to the database connection
1125
   */
1126 382 berkley
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1127 425 bojilova
               HttpServletResponse response, String user, String group) {
1128 59 jones
1129 309 bojilova
    Connection conn = null;
1130
1131 204 jones
    try {
1132
      // Get the document indicated
1133
      String[] doctext = (String[])params.get("doctext");
1134 557 bojilova
1135
      StringReader acl = null;
1136 617 bojilova
      if(params.containsKey("acltext"))
1137 557 bojilova
      {
1138 598 bojilova
        String[] acltext = (String[])params.get("acltext");
1139 557 bojilova
        try {
1140 619 bojilova
          if ( !acltext[0].equals("") ) {
1141
            acl = new StringReader(acltext[0]);
1142
          }
1143 557 bojilova
        } catch (NullPointerException npe) {}
1144
      }
1145 598 bojilova
      StringReader dtd = null;
1146 617 bojilova
      if(params.containsKey("dtdtext"))
1147 598 bojilova
      {
1148
        String[] dtdtext = (String[])params.get("dtdtext");
1149
        try {
1150 619 bojilova
          if ( !dtdtext[0].equals("") ) {
1151
            dtd = new StringReader(dtdtext[0]);
1152
          }
1153 598 bojilova
        } catch (NullPointerException npe) {}
1154
      }
1155 557 bojilova
1156 204 jones
      StringReader xml = null;
1157
      try {
1158
        xml = new StringReader(doctext[0]);
1159 59 jones
1160 204 jones
        String[] action = (String[])params.get("action");
1161
        String[] docid = (String[])params.get("docid");
1162
        String newdocid = null;
1163 203 jones
1164 204 jones
        String doAction = null;
1165
        if (action[0].equals("insert")) {
1166
          doAction = "INSERT";
1167
        } else if (action[0].equals("update")) {
1168
          doAction = "UPDATE";
1169
        }
1170 203 jones
1171 204 jones
        try {
1172 309 bojilova
            // get a connection from the pool
1173
            conn = util.getConnection();
1174 408 jones
1175 309 bojilova
            // write the document to the database
1176
            try {
1177
                String accNumber = docid[0];
1178
                if (accNumber.equals("")) {
1179
                    accNumber = null;
1180
                }
1181 598 bojilova
                newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1182 557 bojilova
                                              accNumber, user, group);
1183 465 berkley
1184 309 bojilova
            } catch (NullPointerException npe) {
1185 598 bojilova
              newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1186 557 bojilova
                                            null, user, group);
1187 309 bojilova
            }
1188 462 bojilova
//        } catch (Exception e) {
1189
//          response.setContentType("text/html");
1190
//          out.println(e.getMessage());
1191 309 bojilova
        } finally {
1192 320 bojilova
          util.returnConnection(conn);
1193 309 bojilova
        }
1194
1195 204 jones
        // set content type and other response header fields first
1196
        response.setContentType("text/xml");
1197
        out.println("<?xml version=\"1.0\"?>");
1198
        out.println("<success>");
1199
        out.println("<docid>" + newdocid + "</docid>");
1200
        out.println("</success>");
1201
1202 203 jones
      } catch (NullPointerException npe) {
1203 204 jones
        response.setContentType("text/xml");
1204
        out.println("<?xml version=\"1.0\"?>");
1205
        out.println("<error>");
1206
        out.println(npe.getMessage());
1207
        out.println("</error>");
1208 55 jones
      }
1209 204 jones
    } catch (Exception e) {
1210
      response.setContentType("text/xml");
1211
      out.println("<?xml version=\"1.0\"?>");
1212
      out.println("<error>");
1213
      out.println(e.getMessage());
1214
      if (e instanceof SAXException) {
1215
        Exception e2 = ((SAXException)e).getException();
1216
        out.println("<error>");
1217
        out.println(e2.getMessage());
1218
        out.println("</error>");
1219
      }
1220
      //e.printStackTrace(out);
1221
      out.println("</error>");
1222 203 jones
    }
1223 55 jones
  }
1224 203 jones
1225
  /**
1226
   * Handle the database delete request and delete an XML document
1227
   * from the database connection
1228
   */
1229
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1230 425 bojilova
               HttpServletResponse response, String user, String group) {
1231 203 jones
1232
    String[] docid = (String[])params.get("docid");
1233 309 bojilova
    Connection conn = null;
1234 203 jones
1235
    // delete the document from the database
1236
    try {
1237 309 bojilova
      // get a connection from the pool
1238
      conn = util.getConnection();
1239 203 jones
                                      // NOTE -- NEED TO TEST HERE
1240 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
1241 203 jones
                                      // BEFORE ACCESSING ARRAY
1242 375 berkley
      try {
1243 425 bojilova
        DocumentImpl.delete(conn, docid[0], user, group);
1244 204 jones
        response.setContentType("text/xml");
1245
        out.println("<?xml version=\"1.0\"?>");
1246
        out.println("<success>");
1247 203 jones
        out.println("Document deleted.");
1248 204 jones
        out.println("</success>");
1249 203 jones
      } catch (AccessionNumberException ane) {
1250 204 jones
        response.setContentType("text/xml");
1251
        out.println("<?xml version=\"1.0\"?>");
1252
        out.println("<error>");
1253
        out.println("Error deleting document!!!");
1254 203 jones
        out.println(ane.getMessage());
1255 204 jones
        out.println("</error>");
1256 203 jones
      }
1257 204 jones
    } catch (Exception e) {
1258
      response.setContentType("text/xml");
1259
      out.println("<?xml version=\"1.0\"?>");
1260
      out.println("<error>");
1261
      out.println(e.getMessage());
1262
      out.println("</error>");
1263 309 bojilova
    } finally {
1264 320 bojilova
      util.returnConnection(conn);
1265 309 bojilova
    }
1266 203 jones
  }
1267 68 higgins
1268
  /**
1269 380 jones
   * Handle the validation request and return the results to the requestor
1270 68 higgins
   */
1271 185 jones
  private void handleValidateAction(PrintWriter out, Hashtable params,
1272
               HttpServletResponse response) {
1273 68 higgins
1274 103 jones
    // Get the document indicated
1275
    String valtext = null;
1276 309 bojilova
1277 103 jones
    try {
1278
      valtext = ((String[])params.get("valtext"))[0];
1279
    } catch (Exception nullpe) {
1280 68 higgins
1281 309 bojilova
      Connection conn = null;
1282 162 bojilova
      String docid = null;
1283 103 jones
      try {
1284
        // Find the document id number
1285 185 jones
        docid = ((String[])params.get("docid"))[0];
1286 309 bojilova
1287
        // get a connection from the pool
1288
        conn = util.getConnection();
1289 393 jones
1290 309 bojilova
        // Get the document indicated from the db
1291 393 jones
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1292
        valtext = xmldoc.toString();
1293 185 jones
1294 103 jones
      } catch (NullPointerException npe) {
1295 253 jones
        response.setContentType("text/xml");
1296
        out.println("<error>Error getting document ID: " + docid + "</error>");
1297 320 bojilova
        if ( conn != null ) { util.returnConnection(conn); }
1298 380 jones
        return;
1299 309 bojilova
      } catch (Exception e) {
1300
        response.setContentType("text/html");
1301
        out.println(e.getMessage());
1302
      } finally {
1303 320 bojilova
        util.returnConnection(conn);
1304 309 bojilova
      }
1305 103 jones
    }
1306 68 higgins
1307 309 bojilova
    Connection conn = null;
1308 103 jones
    try {
1309 309 bojilova
      // get a connection from the pool
1310
      conn = util.getConnection();
1311 253 jones
      DBValidate valobj = new DBValidate(saxparser,conn);
1312 185 jones
      boolean valid = valobj.validateString(valtext);
1313 68 higgins
1314
      // set content type and other response header fields first
1315 253 jones
      response.setContentType("text/xml");
1316
      out.println(valobj.returnErrors());
1317
1318 103 jones
    } catch (NullPointerException npe2) {
1319
      // set content type and other response header fields first
1320 253 jones
      response.setContentType("text/xml");
1321
      out.println("<error>Error validating document.</error>");
1322 309 bojilova
    } catch (Exception e) {
1323
      response.setContentType("text/html");
1324
      out.println(e.getMessage());
1325
    } finally {
1326 320 bojilova
      util.returnConnection(conn);
1327 309 bojilova
    }
1328 103 jones
  }
1329 87 jones
1330
  /**
1331 380 jones
   * Handle the document request and return the results to the requestor
1332 458 berkley
   * If a docid is passed in through the params then that document
1333
   * will be retrieved form the DB and put in the zip file.
1334
   * In addition if 1 or more relations parameters are passed, those file
1335
   * will be zipped as well.  Currently this is only implemented for
1336
   * metacat:// and http:// files.  Support should be added for srb:// files
1337
   * as well.
1338 91 higgins
   */
1339 458 berkley
  private void handleGetDataDocumentAction(ServletOutputStream out,
1340
               Hashtable params,
1341 185 jones
               HttpServletResponse response) {
1342 458 berkley
  //find the related files, get them from their source and zip them into
1343
  //a zip file.
1344
  try
1345
  {
1346
    Connection conn = util.getConnection();
1347
    String currentDocid = ((String[])params.get("docid"))[0];
1348
    ZipOutputStream zout = new ZipOutputStream(out);
1349
    byte[] bytestring = null;
1350
    ZipEntry zentry = null;
1351
    DocumentImpl xmldoc = null;
1352
    String[] reldocs = null;
1353
1354
    if(params.containsKey("relation"))
1355
    { //get the relations from the parameters.
1356
      reldocs = ((String[])params.get("relation"));
1357
    }
1358
    else
1359
    { //let the for loop know that there are no relations to zip
1360
      reldocs = new String[0];
1361
    }
1362
1363
    //write the base file to the zip file.
1364
    xmldoc = new DocumentImpl(conn, currentDocid);
1365
    bytestring = (xmldoc.toString()).getBytes();
1366
    zentry = new ZipEntry(currentDocid + ".xml");
1367
    //create a new zip entry and write the file to the stream
1368
    zentry.setSize(bytestring.length);
1369
    zout.putNextEntry(zentry);
1370
    zout.write(bytestring, 0, bytestring.length);
1371
    zout.closeEntry(); //get ready for the next entry.
1372
1373
    //zip up the related documents
1374
    for(int i=0; i<reldocs.length; i++)
1375
    {
1376 566 jones
      //MetacatURL murl = new MetacatURL(((String)reldocs[i]));
1377
      URL murl = new URL(((String)reldocs[i]));
1378
      Hashtable qparams = util.parseQuery(murl.getQuery());
1379
      if(murl.getProtocol().equals("metacat"))
1380 458 berkley
      {
1381
        //get the document from the database
1382 566 jones
        //xmldoc = new DocumentImpl(conn, (String)murl.getHashParam("docid"));
1383
        xmldoc = new DocumentImpl(conn, (String)qparams.get("docid"));
1384 458 berkley
        bytestring = (xmldoc.toString()).getBytes();
1385 566 jones
        zentry = new ZipEntry(qparams.get("docid") + ".xml");
1386 458 berkley
        //create a new zip entry and write the file to the stream
1387
        zentry.setSize(bytestring.length);
1388
        zout.putNextEntry(zentry);
1389
        zout.write(bytestring, 0, bytestring.length);
1390
        zout.closeEntry(); //get ready for the next entry.
1391
      }
1392 566 jones
      else if(murl.getProtocol().equals("http"))
1393 458 berkley
      {
1394 566 jones
        //Hashtable murlParams = murl.getHashParams();
1395
        if(qparams.containsKey("httpurl"))
1396 458 berkley
        {//httpurl is the param name for an http url.
1397 566 jones
          URL urlconn = new URL((String)qparams.get("httpurl"));
1398 473 berkley
          //create a new url obj.
1399 458 berkley
          BufferedReader htmldoc = new BufferedReader(
1400
                                   new InputStreamReader(urlconn.openStream()));
1401
          //get the data from the web server
1402
          try
1403
          { //zip the document
1404
            String line=null;
1405 566 jones
            zentry = new ZipEntry((String)qparams.get("filename"));
1406 458 berkley
            //get just the filename from the URL.
1407
            zout.putNextEntry(zentry);
1408
            //make a new entry in the zip file stream
1409
            while((line = htmldoc.readLine()) != null)
1410
            {
1411
              bytestring = (line.toString()).getBytes();
1412
              zout.write(bytestring, 0, bytestring.length);
1413
              //write out the file line by line
1414
            }
1415
            zout.closeEntry(); //close the entry in the file
1416
          }
1417
          catch(Exception e)
1418
          {
1419
            util.debugMessage("error downloading html document");
1420
          }
1421
        }
1422
      }
1423
    }
1424
    zout.finish();  //terminate the zip file
1425
    zout.close();   //close the stream.
1426
    util.returnConnection(conn); //return the connection to the pool
1427
  }
1428
  catch(Exception e)
1429
  {
1430
    System.out.println("Error creating zip file: " + e.getMessage());
1431
    e.printStackTrace(System.out);
1432
  }
1433
1434
   /*
1435
   //////////old code using a shell script/////////////////////////////////
1436
1437 91 higgins
      boolean error_flag = false;
1438
      String error_message = "";
1439
      // Get the document indicated
1440
      String[] datadoc = (String[])params.get("datadoc");
1441 185 jones
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1442
      // executescript = "test.bat";        // for testing only!!!
1443 91 higgins
1444
      // set content type and other response header fields first
1445
      response.setContentType("application/octet-stream");
1446 185 jones
      if (defaultdatapath!=null) {
1447
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1448
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1449 91 higgins
        }
1450 185 jones
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1451
        if (executescript!=null) {
1452
          String command = null;
1453
          File scriptfile = new File(executescript);
1454
          if (scriptfile.exists()) {
1455
            command=executescript+" "+datadoc[0]; // script includes path
1456
        } else {     // look in defaultdatapath
1457
            // on Win98 one MUST include the .bat extender
1458
            command = defaultdatapath+executescript+" "+datadoc[0];
1459
        }
1460 91 higgins
      System.out.println(command);
1461
      try {
1462
      Process proc = Runtime.getRuntime().exec(command);
1463
      proc.waitFor();
1464
      }
1465
      catch (Exception eee) {
1466
        System.out.println("Error running process!");
1467
        error_flag = true;
1468
        error_message = "Error running process!";}
1469
      } // end executescript not null if
1470
      File datafile = new File(defaultdatapath+datadoc[0]);
1471
      try {
1472
      FileInputStream fw = new FileInputStream(datafile);
1473
      int x;
1474 185 jones
      while ((x = fw.read())!=-1) {
1475 91 higgins
        out.write(x); }
1476 185 jones
        fw.close();
1477
      } catch (Exception e) {
1478 91 higgins
        System.out.println("Error in returning file\n"+e.getMessage());
1479
        error_flag=true;
1480 185 jones
        error_message = error_message+"\nError in returning file\n"+
1481
                        e.getMessage();
1482
      }
1483
    } // end defaultdatapath not null if
1484 458 berkley
    */
1485 91 higgins
  }
1486 302 bojilova
1487
  /**
1488
   * Handle the getdoctypes Action.
1489
   * Read all doctypes from db connection in XML format
1490
   */
1491
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1492
                                       HttpServletResponse response) {
1493
1494 309 bojilova
    Connection conn = null;
1495
1496 302 bojilova
    try {
1497
1498 309 bojilova
        // get connection from the pool
1499
        conn = util.getConnection();
1500
        DBUtil dbutil = new DBUtil(conn);
1501 302 bojilova
        String doctypes = dbutil.readDoctypes();
1502
        out.println(doctypes);
1503
1504
    } catch (Exception e) {
1505
      out.println("<?xml version=\"1.0\"?>");
1506
      out.println("<error>");
1507
      out.println(e.getMessage());
1508
      out.println("</error>");
1509 309 bojilova
    } finally {
1510 320 bojilova
      util.returnConnection(conn);
1511 309 bojilova
    }
1512 302 bojilova
1513
  }
1514
1515
  /**
1516
   * Handle the getdataguide Action.
1517
   * Read Data Guide for a given doctype from db connection in XML format
1518
   */
1519
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
1520
                                        HttpServletResponse response) {
1521
1522 309 bojilova
    Connection conn = null;
1523 316 bojilova
    String doctype = null;
1524
    String[] doctypeArr = (String[])params.get("doctype");
1525 309 bojilova
1526 316 bojilova
    // get only the first doctype specified in the list of doctypes
1527
    // it could be done for all doctypes in that list
1528
    if (doctypeArr != null) {
1529
        doctype = ((String[])params.get("doctype"))[0];
1530
    }
1531
1532 302 bojilova
    try {
1533
1534 309 bojilova
        // get connection from the pool
1535
        conn = util.getConnection();
1536
        DBUtil dbutil = new DBUtil(conn);
1537 316 bojilova
        String dataguide = dbutil.readDataGuide(doctype);
1538 302 bojilova
        out.println(dataguide);
1539
1540
    } catch (Exception e) {
1541
      out.println("<?xml version=\"1.0\"?>");
1542
      out.println("<error>");
1543
      out.println(e.getMessage());
1544
      out.println("</error>");
1545 309 bojilova
    } finally {
1546 320 bojilova
      util.returnConnection(conn);
1547 309 bojilova
    }
1548 302 bojilova
1549
  }
1550
1551 46 jones
}