Project

General

Profile

« Previous | Next » 

Revision 2098

Added by Matt Jones about 20 years ago

Reformatted code for readability and consistency.

View differences:

MetaCatServlet.java
27 27

  
28 28
package edu.ucsb.nceas.metacat;
29 29

  
30
import com.oreilly.servlet.multipart.FilePart;
31
import com.oreilly.servlet.multipart.MultipartParser;
32
import com.oreilly.servlet.multipart.ParamPart;
33
import com.oreilly.servlet.multipart.Part;
34

  
30
import java.io.BufferedInputStream;
35 31
import java.io.File;
32
import java.io.FileInputStream;
33
import java.io.IOException;
36 34
import java.io.PrintWriter;
37
import java.io.IOException;
38 35
import java.io.StringReader;
39
import java.io.FileInputStream;
40
import java.io.BufferedInputStream;
36
import java.net.MalformedURLException;
37
import java.net.URL;
38
import java.sql.PreparedStatement;
39
import java.sql.ResultSet;
40
import java.sql.SQLException;
41 41
import java.util.Enumeration;
42 42
import java.util.Hashtable;
43
import java.util.ResourceBundle;
44
import java.util.Random;
45 43
import java.util.PropertyResourceBundle;
46 44
import java.util.Vector;
47
import java.net.URL;
48
import java.net.MalformedURLException;
49
import java.sql.PreparedStatement;
50
import java.sql.ResultSet;
51
import java.sql.Connection;
52
import java.sql.SQLException;
53
import java.lang.reflect.*;
54
import java.net.*;
55
import java.util.zip.*;
45
import java.util.zip.ZipEntry;
46
import java.util.zip.ZipOutputStream;
56 47

  
57 48
import javax.servlet.ServletConfig;
58 49
import javax.servlet.ServletContext;
59 50
import javax.servlet.ServletException;
60
import javax.servlet.ServletInputStream;
51
import javax.servlet.ServletOutputStream;
61 52
import javax.servlet.http.HttpServlet;
62 53
import javax.servlet.http.HttpServletRequest;
63 54
import javax.servlet.http.HttpServletResponse;
64 55
import javax.servlet.http.HttpSession;
65
import javax.servlet.http.HttpUtils;
66
import javax.servlet.ServletOutputStream;
67 56

  
68
import org.ecoinformatics.eml.EMLParser;
69 57
import edu.ucsb.nceas.utilities.Options;
70 58

  
71
import org.xml.sax.SAXException;
59
import org.ecoinformatics.eml.EMLParser;
72 60

  
61
import com.oreilly.servlet.multipart.FilePart;
62
import com.oreilly.servlet.multipart.MultipartParser;
63
import com.oreilly.servlet.multipart.ParamPart;
64
import com.oreilly.servlet.multipart.Part;
65

  
73 66
/**
74 67
 * A metadata catalog server implemented as a Java Servlet
75
 *
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
 * action=squery -- structured query (see pathquery.dtd)<br>
80
 * action= -- export a zip format for data packadge<br>
81
 * action=read -- read any metadata/data file from Metacat and from Internet<br>
82
 * action=insert -- insert an XML document into the database store<br>
83
 * action=update -- update an XML document that is in the database store<br>
84
 * action=delete --  delete an XML document from the database store<br>
85
 * action=validate -- vallidate the xml contained in valtext<br>
86
 * doctype -- document type list returned by the query (publicID)<br>
87
 * qformat=xml -- display resultset from query in XML<br>
88
 * qformat=html -- display resultset from query in HTML<br>
89
 * qformat=zip -- zip resultset from query<br>
90
 * docid=34 -- display the document with the document ID number 34<br>
91
 * doctext -- XML text of the document to load into the database<br>
92
 * acltext -- XML access text for a document to load into the database<br>
93
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog<br>
94
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
95
 * valtext -- XML text to be validated<br>
96
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
97
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
98
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
99
 * action=getdataguide -- retrieve a Data Guide<br>
100
 * action=getprincipals -- retrieve a list of principals in XML<br>
101
 * datadoc -- data document name (id)<br>
68
 * 
102 69
 * <p>
103
 * The particular combination of parameters that are valid for each
104
 * particular action value is quite specific.  This documentation
105
 * will be reorganized to reflect this information.
70
 * Valid parameters are: <br>
71
 * action=query -- query the values of all elements and attributes and return a
72
 * result set of nodes <br>
73
 * action=squery -- structured query (see pathquery.dtd) <br>
74
 * action= -- export a zip format for data packadge <br>
75
 * action=read -- read any metadata/data file from Metacat and from Internet
76
 * <br>
77
 * action=insert -- insert an XML document into the database store <br>
78
 * action=update -- update an XML document that is in the database store <br>
79
 * action=delete -- delete an XML document from the database store <br>
80
 * action=validate -- vallidate the xml contained in valtext <br>
81
 * doctype -- document type list returned by the query (publicID) <br>
82
 * qformat=xml -- display resultset from query in XML <br>
83
 * qformat=html -- display resultset from query in HTML <br>
84
 * qformat=zip -- zip resultset from query <br>
85
 * docid=34 -- display the document with the document ID number 34 <br>
86
 * doctext -- XML text of the document to load into the database <br>
87
 * acltext -- XML access text for a document to load into the database <br>
88
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog <br>
89
 * query -- actual query text (to go with 'action=query' or 'action=squery')
90
 * <br>
91
 * valtext -- XML text to be validated <br>
92
 * action=getaccesscontrol -- retrieve acl info for Metacat document <br>
93
 * action=getdoctypes -- retrieve all doctypes (publicID) <br>
94
 * action=getdtdschema -- retrieve a DTD or Schema file <br>
95
 * action=getdataguide -- retrieve a Data Guide <br>
96
 * action=getprincipals -- retrieve a list of principals in XML <br>
97
 * datadoc -- data document name (id) <br>
98
 * <p>
99
 * The particular combination of parameters that are valid for each particular
100
 * action value is quite specific. This documentation will be reorganized to
101
 * reflect this information.
106 102
 */
107
public class MetaCatServlet extends HttpServlet {
103
public class MetaCatServlet extends HttpServlet
104
{
108 105

  
109
  private ServletConfig config = null;
110
  private ServletContext context = null;
111
  private String resultStyleURL = null;
112
  private String xmlcatalogfile = null;
113
  private String saxparser = null;
114
  private String datafilepath = null;
115
  private File dataDirectory = null;
116
  private String servletpath = null;
117
  private String htmlpath = null;
118
  private PropertyResourceBundle options = null;
119
  private MetaCatUtil util = null;
120
  private DBConnectionPool connPool = null;
121
  private Hashtable sessionHash = new Hashtable();
122
  private static final String PROLOG = "<?xml version=\"1.0\"?>";
123
  private static final String SUCCESS = "<success>";
124
  private static final String SUCCESSCLOSE = "</success>";
125
  private static final String ERROR = "<error>";
126
  private static final String ERRORCLOSE = "</error>";
127
  public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
128
  public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
129
  public static final String EML2KEYWORD =":eml";
130
  public static final String XMLFORMAT = "xml";
131
  private static final String CONFIG_DIR  = "WEB-INF";
132
  private static final String CONFIG_NAME = "metacat.properties";
106
    private ServletConfig config = null;
133 107

  
134
  /**
135
   * Initialize the servlet by creating appropriate database connections
136
   */
137
  public void init( ServletConfig config ) throws ServletException {
138
    try {
139
      super.init( config );
140
      this.config = config;
141
      this.context = config.getServletContext();
142
      System.out.println("MetaCatServlet Initialize");
108
    private ServletContext context = null;
143 109

  
144
      // Initialize the properties file for our options
145
      String dirPath = context.getRealPath(CONFIG_DIR);
146
      File propertyFile = new File(dirPath,CONFIG_NAME);
147
      Options options = null;
148
      try {
149
          options = Options.initialize(propertyFile);
150
          MetaCatUtil.debugMessage("Options configured: " +
151
            options.getOption("configured"), 20);
152
      } catch (IOException ioe) {
153
        MetaCatUtil.debugMessage("Error in loading options: "
154
           +ioe.getMessage(), 20);
155
      }
110
    private String resultStyleURL = null;
156 111

  
157
      util = new MetaCatUtil();
112
    private String xmlcatalogfile = null;
158 113

  
159
      //initial DBConnection pool
160
      connPool = DBConnectionPool.getInstance();
114
    private String saxparser = null;
161 115

  
162
      // Get the configuration file information
163
      resultStyleURL = util.getOption("resultStyleURL");
164
      xmlcatalogfile = util.getOption("xmlcatalogfile");
165
      saxparser = util.getOption("saxparser");
166
      datafilepath = util.getOption("datafilepath");
167
      dataDirectory = new File(datafilepath);
168
      servletpath = util.getOption("servletpath");
169
      htmlpath = util.getOption("htmlpath");
116
    private String datafilepath = null;
170 117

  
118
    private File dataDirectory = null;
171 119

  
172
    } catch ( ServletException ex ) {
173
      throw ex;
174
    } catch (SQLException e) {
175
      MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
176
                                          +e.getMessage(), 20);
177
    }
178
  }
120
    private String servletpath = null;
179 121

  
180
  /**
181
   * Close all db connections from the pool
182
   */
183
  public void destroy() {
184
      // Close all db connection
185
      System.out.println("Destroying MetacatServlet");
186
      connPool.release();
187
  }
122
    private String htmlpath = null;
188 123

  
189
  /** Handle "GET" method requests from HTTP clients */
190
  public void doGet (HttpServletRequest request, HttpServletResponse response)
191
    throws ServletException, IOException {
124
    private PropertyResourceBundle options = null;
192 125

  
193
    // Process the data and send back the response
194
    handleGetOrPost(request, response);
195
  }
126
    private MetaCatUtil util = null;
196 127

  
197
  /** Handle "POST" method requests from HTTP clients */
198
  public void doPost( HttpServletRequest request, HttpServletResponse response)
199
    throws ServletException, IOException {
128
    private DBConnectionPool connPool = null;
200 129

  
201
    // Process the data and send back the response
202
    handleGetOrPost(request, response);
203
  }
130
    private Hashtable sessionHash = new Hashtable();
204 131

  
205
  /**
206
   * Control servlet response depending on the action parameter specified
207
   */
208
  private void handleGetOrPost(HttpServletRequest request,
209
                               HttpServletResponse response)
210
                               throws ServletException, IOException
211
  {
132
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
212 133

  
213
    if ( util == null ) {
214
        util = new MetaCatUtil();
215
    }
216
    /*MetaCatUtil.debugMessage("Connection pool size: "
217
                                     +connPool.getSizeOfDBConnectionPool(),10);
218
    MetaCatUtil.debugMessage("Free DBConnection number: "
219
                                  +connPool.getFreeDBConnectionNumber(), 10);*/
220
    //If all DBConnection in the pool are free and DBConnection pool
221
    //size is greater than initial value, shrink the connection pool
222
    //size to initial value
223
    DBConnectionPool.shrinkDBConnectionPoolSize();
134
    private static final String SUCCESS = "<success>";
224 135

  
225
    //Debug message to print out the method which have a busy DBConnection
226
    connPool.printMethodNameHavingBusyDBConnection();
136
    private static final String SUCCESSCLOSE = "</success>";
227 137

  
228
    String ctype = request.getContentType();
229
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
230
      handleMultipartForm(request, response);
231
    } else {
138
    private static final String ERROR = "<error>";
232 139

  
140
    private static final String ERRORCLOSE = "</error>";
233 141

  
234
      String name = null;
235
      String[] value = null;
236
      String[] docid = new String[3];
237
      Hashtable params = new Hashtable();
238
      Enumeration paramlist = request.getParameterNames();
142
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
239 143

  
144
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
240 145

  
241
      while (paramlist.hasMoreElements()) {
146
    public static final String EML2KEYWORD = ":eml";
242 147

  
243
        name = (String)paramlist.nextElement();
244
        value = request.getParameterValues(name);
148
    public static final String XMLFORMAT = "xml";
245 149

  
246
        // Decode the docid and mouse click information
247
        if (name.endsWith(".y")) {
248
          docid[0] = name.substring(0,name.length()-2);
249
          params.put("docid", docid);
250
          name = "ypos";
251
        }
252
        if (name.endsWith(".x")) {
253
          name = "xpos";
254
        }
150
    private static final String CONFIG_DIR = "WEB-INF";
255 151

  
256
        params.put(name,value);
257
      }
152
    private static final String CONFIG_NAME = "metacat.properties";
258 153

  
154
    /**
155
     * Initialize the servlet by creating appropriate database connections
156
     */
157
    public void init(ServletConfig config) throws ServletException
158
    {
159
        try {
160
            super.init(config);
161
            this.config = config;
162
            this.context = config.getServletContext();
259 163

  
260
      //handle param is emptpy
261
      if (params.isEmpty() || params == null)
262
      {
263
        return;
264
      }
164
            // Initialize the properties file for our options
165
            String dirPath = context.getRealPath(CONFIG_DIR);
166
            File propertyFile = new File(dirPath, CONFIG_NAME);
167
            Options options = null;
168
            try {
169
                options = Options.initialize(propertyFile);
170
                MetaCatUtil.debugMessage("Options configured: "
171
                        + options.getOption("configured"), 20);
172
            } catch (IOException ioe) {
173
                MetaCatUtil.debugMessage("Error in loading options: "
174
                        + ioe.getMessage(), 20);
175
            }
265 176

  
266
      //if the user clicked on the input images, decode which image
267
      //was clicked then set the action.
268
      String action = ((String[])params.get("action"))[0];
269
      util.debugMessage("Line 230: Action is: " + action, 1);
177
            util = new MetaCatUtil();
270 178

  
271
      // This block handles session management for the servlet
272
      // by looking up the current session information for all actions
273
      // other than "login" and "logout"
274
      String username = null;
275
      String password = null;
276
      String[] groupnames = null;
277
      String sess_id = null;
179
            //initial DBConnection pool
180
            connPool = DBConnectionPool.getInstance();
278 181

  
279
      // handle login action
280
      if (action.equals("login")) {
281
        PrintWriter out = response.getWriter();
282
        handleLoginAction(out, params, request, response);
283
        out.close();
182
            // Get the configuration file information
183
            resultStyleURL = MetaCatUtil.getOption("resultStyleURL");
184
            xmlcatalogfile = MetaCatUtil.getOption("xmlcatalogfile");
185
            saxparser = MetaCatUtil.getOption("saxparser");
186
            datafilepath = MetaCatUtil.getOption("datafilepath");
187
            dataDirectory = new File(datafilepath);
188
            servletpath = MetaCatUtil.getOption("servletpath");
189
            htmlpath = MetaCatUtil.getOption("htmlpath");
284 190

  
285
      // handle logout action
286
      } else if (action.equals("logout")) {
287
        PrintWriter out = response.getWriter();
288
        handleLogoutAction(out, params, request, response);
289
        out.close();
290

  
291
      // handle shrink DBConnection request
292
      } else if (action.equals("shrink")) {
293
        PrintWriter out = response.getWriter();
294
        boolean success = false;
295
        //If all DBConnection in the pool are free and DBConnection pool
296
        //size is greater than initial value, shrink the connection pool
297
        //size to initial value
298
        success = DBConnectionPool.shrinkConnectionPoolSize();
299
        if (success)
300
        {
301
          //if successfully shrink the pool size to initial value
302
          out.println("DBConnection Pool shrink successfully");
303
        }//if
304
        else
305
        {
306
          out.println("DBConnection pool couldn't shrink successfully");
191
            System.out.println("Metacat (" + Version.getVersion()
192
                    + ") initialized.");
193
        } catch (ServletException ex) {
194
            throw ex;
195
        } catch (SQLException e) {
196
            MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
197
                    + e.getMessage(), 20);
307 198
        }
308
       //close out put
309
        out.close();
199
    }
310 200

  
311
      // aware of session expiration on every request
312
      }
313
      else
314
      {
315
        HttpSession sess = request.getSession(true);
316
        if (sess.isNew() && !params.containsKey("sessionid")) {
317
          // session expired or has not been stored b/w user requests
318
          MetaCatUtil.debugMessage("in session is new or no sessionid", 40);
319
          username = "public";
320
          sess.setAttribute("username", username);
321
        }
322
        else
323
        {
324
          MetaCatUtil.debugMessage("in session is not new or " +
325
                                    " has sessionid parameter", 40);
326
          try
327
          {
328
            if(params.containsKey("sessionid"))
329
            {
330
              sess_id = ((String[])params.get("sessionid"))[0];
331
              MetaCatUtil.debugMessage("in has sessionid " + sess_id, 40);
332
              if(sessionHash.containsKey(sess_id))
333
              {
334
                MetaCatUtil.debugMessage("find the id " + sess_id +
335
                                         " in hash table", 40);
336
                sess = (HttpSession)sessionHash.get(sess_id);
337
              }
338
            }
339
            else
340
            {
341
              // we already store the session in login, so we don't need here
342
              /*MetaCatUtil.debugMessage("in no sessionid parameter ", 40);
343
              sess_id = (String)sess.getId();
344
              MetaCatUtil.debugMessage("storing the session id "+ sess_id +
345
                  " which has username " + sess.getAttribute("username") +
346
                 " into session hash in handleGetOrPost method", 35);
347
              sessionHash.put(sess_id, sess);*/
348
            }
349
          }
350
          catch(IllegalStateException ise)
351
          {
352
            System.out.println("error in handleGetOrPost: this shouldn't " +
353
                               "happen: the session should be valid: " +
354
                               ise.getMessage());
355
          }
201
    /**
202
     * Close all db connections from the pool
203
     */
204
    public void destroy()
205
    {
206
        // Close all db connection
207
        System.out.println("Destroying MetacatServlet");
208
        connPool.release();
209
    }
356 210

  
357
          username = (String)sess.getAttribute("username");
358
          MetaCatUtil.debugMessage("The user name from session is: "+
359
                                   username, 20);
360
          password = (String)sess.getAttribute("password");
361
          groupnames = (String[])sess.getAttribute("groupnames");
362
        }
211
    /** Handle "GET" method requests from HTTP clients */
212
    public void doGet(HttpServletRequest request, HttpServletResponse response)
213
            throws ServletException, IOException
214
    {
363 215

  
364
        //make user user username should be public
365
        if (username == null || (username.trim().equals("")))
366
        {
367
          username = "public";
368
        }
369
        MetaCatUtil.debugMessage("The user is : "+ username, 5);
370
      }
371
       // Now that we know the session is valid, we can delegate the request
372
      // to a particular action handler
373
      if(action.equals("query")) {
374
        PrintWriter out = response.getWriter();
375
        handleQuery(out,params,response,username,groupnames,sess_id);
376
        out.close();
377
      } else if(action.equals("squery")) {
378
        PrintWriter out = response.getWriter();
379
        if(params.containsKey("query")) {
380
         handleSQuery(out, params,response,username,groupnames,sess_id);
381
         out.close();
382
        } else {
383
          out.println("Illegal action squery without \"query\" parameter");
384
          out.close();
385
        }
386
      } else if (action.equals("export")) {
387

  
388
        handleExportAction(params, response, username, groupnames, password);
389
      } else if (action.equals("read")) {
390
        handleReadAction(params, response, username,password, groupnames);
391
      } else if (action.equals("readinlinedata")) {
392
        handleReadInlineDataAction(params, response, username,
393
                                   password, groupnames);
394
      } else if (action.equals("insert") || action.equals("update")) {
395
        PrintWriter out = response.getWriter();
396
        if ( (username != null) &&  !username.equals("public") ) {
397
          handleInsertOrUpdateAction(out,params,username,groupnames);
398
        } else {
399
          out.println("Permission denied for user "+username +" " + action);
400
       }
401
        out.close();
402
      } else if (action.equals("delete")) {
403
        PrintWriter out = response.getWriter();
404
        if ( (username != null) &&  !username.equals("public") ) {
405
          handleDeleteAction(out, params, response, username, groupnames);
406
        } else {
407
          out.println("Permission denied for " + action);
408
        }
409
        out.close();
410
      } else if (action.equals("validate")) {
411
        PrintWriter out = response.getWriter();
412
        handleValidateAction(out, params);
413
        out.close();
414
      } else if (action.equals("setaccess")) {
415
         PrintWriter out = response.getWriter();
416
         handleSetAccessAction(out, params, username);
417
        out.close();
418
      } else if (action.equals("getaccesscontrol")) {
419
        PrintWriter out = response.getWriter();
420
        handleGetAccessControlAction(out,params,response,username,groupnames);
421
        out.close();
422
      } else if (action.equals("getprincipals")) {
423
        PrintWriter out = response.getWriter();
424
        handleGetPrincipalsAction(out, username, password);
425
        out.close();
426
      } else if (action.equals("getdoctypes")) {
427
        PrintWriter out = response.getWriter();
428
        handleGetDoctypesAction(out, params, response);
429
        out.close();
430
      } else if (action.equals("getdtdschema")) {
431
        PrintWriter out = response.getWriter();
432
        handleGetDTDSchemaAction(out, params, response);
433
        out.close();
434
      } else if (action.equals("getlastdocid")) {
435
        PrintWriter out = response.getWriter();
436
        handleGetMaxDocidAction(out, params, response);
437
        out.close();
438
      } else if (action.equals("getrevisionanddoctype")) {
439
        PrintWriter out = response.getWriter();
440
        handleGetRevisionAndDocTypeAction(out, params);
441
        out.close();
442
      } else if (action.equals("getversion")) {
443
          response.setContentType("text/xml");
444
          PrintWriter out = response.getWriter();
445
          out.println(Version.getVersionAsXml());
446
          out.close();
447
      } else if (action.equals("login") || action.equals("logout")) {
448
      } else if (action.equals("protocoltest")) {
449
        String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
450
        try {
451
          testURL = ((String[])params.get("url"))[0];
452
        } catch (Throwable t) {
453
        }
454
        String phandler = System.getProperty("java.protocol.handler.pkgs");
455
        response.setContentType("text/html");
456
        PrintWriter out = response.getWriter();
457
        out.println("<body bgcolor=\"white\">");
458
        out.println("<p>Handler property: <code>" + phandler + "</code></p>");
459
        out.println("<p>Starting test for:<br>");
460
        out.println("    " + testURL + "</p>");
461
        try {
462
          URL u = new URL(testURL);
463
          out.println("<pre>");
464
          out.println("Protocol: " + u.getProtocol());
465
          out.println("    Host: " + u.getHost());
466
          out.println("    Port: " + u.getPort());
467
          out.println("    Path: " + u.getPath());
468
          out.println("     Ref: " + u.getRef());
469
          String pquery = u.getQuery();
470
          out.println("   Query: " + pquery);
471
          out.println("  Params: ");
472
          if (pquery != null) {
473
            Hashtable qparams = util.parseQuery(u.getQuery());
474
            for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
475
              String pname = (String)en.nextElement();
476
              String pvalue = (String)qparams.get(pname);
477
              out.println("    " + pname + ": " + pvalue);
478
            }
479
          }
480
          out.println("</pre>");
481
          out.println("</body>");
482
          out.close();
483
        } catch (MalformedURLException mue) {
484
          System.out.println("bad url from MetacatServlet.handleGetOrPost");
485
          out.println(mue.getMessage());
486
          mue.printStackTrace(out);
487
          out.close();
488
        }
489
      } else {
490
        PrintWriter out = response.getWriter();
491
        out.println("<?xml version=\"1.0\"?>");
492
        out.println("<error>");
493
        out.println("Error: action not registered.  Please report this error.");
494
        out.println("</error>");
495
        out.close();
496
      }
497

  
498
      //util.closeConnections();
499
      // Close the stream to the client
500
      //out.close();
216
        // Process the data and send back the response
217
        handleGetOrPost(request, response);
501 218
    }
502
  }
503 219

  
504
  // LOGIN & LOGOUT SECTION
505
  /**
506
   * Handle the login request. Create a new session object.
507
   * Do user authentication through the session.
508
   */
509
  private void handleLoginAction(PrintWriter out, Hashtable params,
510
               HttpServletRequest request, HttpServletResponse response) {
220
    /** Handle "POST" method requests from HTTP clients */
221
    public void doPost(HttpServletRequest request, HttpServletResponse response)
222
            throws ServletException, IOException
223
    {
511 224

  
512
    AuthSession sess = null;
513
    String un = ((String[])params.get("username"))[0];
514
    MetaCatUtil.debugMessage("user " + un + " try to login", 20);
515
    String pw = ((String[])params.get("password"))[0];
516
    String action = ((String[])params.get("action"))[0];
517
    String qformat = ((String[])params.get("qformat"))[0];
518

  
519
    try {
520
      sess = new AuthSession();
521
    } catch (Exception e) {
522
      System.out.println("error in MetacatServlet.handleLoginAction: " +
523
                          e.getMessage());
524
      out.println(e.getMessage());
525
      return;
225
        // Process the data and send back the response
226
        handleGetOrPost(request, response);
526 227
    }
527
    boolean isValid = sess.authenticate(request, un, pw);
528 228

  
529
    //if it is authernticate is true, store the session
530
    if (isValid)
229
    /**
230
     * Control servlet response depending on the action parameter specified
231
     */
232
    private void handleGetOrPost(HttpServletRequest request,
233
            HttpServletResponse response) throws ServletException, IOException
531 234
    {
532
      HttpSession session = sess.getSessions();
533
      String id = session.getId();
534
      MetaCatUtil.debugMessage("Store session id " + id +
535
               "which has username" + session.getAttribute("username")+
536
               " into hash in login method", 35);
537
      sessionHash.put(id, session);
538
    }
539 235

  
540
    // format and transform the output
541
    if (qformat.equals("xml")) {
542
      response.setContentType("text/xml");
543
      out.println(sess.getMessage());
544
    } else {
236
        if (util == null) {
237
            util = new MetaCatUtil();
238
        }
239
        /*
240
         * MetaCatUtil.debugMessage("Connection pool size: "
241
         * +connPool.getSizeOfDBConnectionPool(),10);
242
         * MetaCatUtil.debugMessage("Free DBConnection number: "
243
         */
244
        //If all DBConnection in the pool are free and DBConnection pool
245
        //size is greater than initial value, shrink the connection pool
246
        //size to initial value
247
        DBConnectionPool.shrinkDBConnectionPoolSize();
545 248

  
546
      try {
249
        //Debug message to print out the method which have a busy DBConnection
250
        connPool.printMethodNameHavingBusyDBConnection();
547 251

  
548
        DBTransform trans = new DBTransform();
549
        response.setContentType("text/html");
550
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
551
                                   "-//W3C//HTML//EN", qformat, out, null);
252
        String ctype = request.getContentType();
253
        if (ctype != null && ctype.startsWith("multipart/form-data")) {
254
            handleMultipartForm(request, response);
255
        } else {
552 256

  
553
      } catch(Exception e) {
257
            String name = null;
258
            String[] value = null;
259
            String[] docid = new String[3];
260
            Hashtable params = new Hashtable();
261
            Enumeration paramlist = request.getParameterNames();
554 262

  
555
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
556
                                +e.getMessage(), 30);
557
      }
263
            while (paramlist.hasMoreElements()) {
558 264

  
559
    // any output is returned
560
    }
561
  }
265
                name = (String) paramlist.nextElement();
266
                value = request.getParameterValues(name);
562 267

  
563
  /**
564
   * Handle the logout request. Close the connection.
565
   */
566
  private void handleLogoutAction(PrintWriter out, Hashtable params,
567
               HttpServletRequest request, HttpServletResponse response) {
268
                // Decode the docid and mouse click information
269
                if (name.endsWith(".y")) {
270
                    docid[0] = name.substring(0, name.length() - 2);
271
                    params.put("docid", docid);
272
                    name = "ypos";
273
                }
274
                if (name.endsWith(".x")) {
275
                    name = "xpos";
276
                }
568 277

  
569
    String qformat = ((String[])params.get("qformat"))[0];
278
                params.put(name, value);
279
            }
570 280

  
571
    // close the connection
572
    HttpSession sess = request.getSession(false);
573
    MetaCatUtil.debugMessage("After get session in logout request", 40);
574
    if (sess != null)
575
    {
576
     MetaCatUtil.debugMessage("The session id " + sess.getId() +
577
                              " will be invalidate in logout action", 30);
578
     MetaCatUtil.debugMessage("The session contains user " +
579
                               sess.getAttribute("username") +
580
                               " will be invalidate in logout action", 30);
581
      sess.invalidate();
582
    }
281
            //handle param is emptpy
282
            if (params.isEmpty() || params == null) { return; }
583 283

  
584
    // produce output
585
    StringBuffer output = new StringBuffer();
586
    output.append("<?xml version=\"1.0\"?>");
587
    output.append("<logout>");
588
    output.append("User logged out");
589
    output.append("</logout>");
284
            //if the user clicked on the input images, decode which image
285
            //was clicked then set the action.
286
            String action = ((String[]) params.get("action"))[0];
287
            MetaCatUtil.debugMessage("Line 230: Action is: " + action, 1);
590 288

  
591
    //format and transform the output
592
    if (qformat.equals("xml")) {
593
      response.setContentType("text/xml");
594
      out.println(output.toString());
595
    } else {
289
            // This block handles session management for the servlet
290
            // by looking up the current session information for all actions
291
            // other than "login" and "logout"
292
            String username = null;
293
            String password = null;
294
            String[] groupnames = null;
295
            String sess_id = null;
596 296

  
597
      try {
297
            // handle login action
298
            if (action.equals("login")) {
299
                PrintWriter out = response.getWriter();
300
                handleLoginAction(out, params, request, response);
301
                out.close();
598 302

  
599
        DBTransform trans = new DBTransform();
600
        response.setContentType("text/html");
601
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
602
                                   "-//W3C//HTML//EN", qformat, out, null);
303
                // handle logout action
304
            } else if (action.equals("logout")) {
305
                PrintWriter out = response.getWriter();
306
                handleLogoutAction(out, params, request, response);
307
                out.close();
603 308

  
604
      } catch(Exception e) {
309
                // handle shrink DBConnection request
310
            } else if (action.equals("shrink")) {
311
                PrintWriter out = response.getWriter();
312
                boolean success = false;
313
                //If all DBConnection in the pool are free and DBConnection
314
                // pool
315
                //size is greater than initial value, shrink the connection
316
                // pool
317
                //size to initial value
318
                success = DBConnectionPool.shrinkConnectionPoolSize();
319
                if (success) {
320
                    //if successfully shrink the pool size to initial value
321
                    out.println("DBConnection Pool shrunk successfully.");
322
                }//if
323
                else {
324
                    out.println("DBConnection pool not shrunk successfully.");
325
                }
326
                //close out put
327
                out.close();
605 328

  
606
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
607
                                  +e.getMessage(), 30);
608
      }
609
    }
610
  }
611
  // END OF LOGIN & LOGOUT SECTION
329
                // aware of session expiration on every request
330
            } else {
331
                HttpSession sess = request.getSession(true);
332
                if (sess.isNew() && !params.containsKey("sessionid")) {
333
                    // session expired or has not been stored b/w user requests
334
                    MetaCatUtil.debugMessage(
335
                            "in session is new or no sessionid", 40);
336
                    username = "public";
337
                    sess.setAttribute("username", username);
338
                } else {
339
                    MetaCatUtil.debugMessage("in session is not new or "
340
                            + " has sessionid parameter", 40);
341
                    try {
342
                        if (params.containsKey("sessionid")) {
343
                            sess_id = ((String[]) params.get("sessionid"))[0];
344
                            MetaCatUtil.debugMessage("in has sessionid "
345
                                    + sess_id, 40);
346
                            if (sessionHash.containsKey(sess_id)) {
347
                                MetaCatUtil.debugMessage("find the id "
348
                                        + sess_id + " in hash table", 40);
349
                                sess = (HttpSession) sessionHash.get(sess_id);
350
                            }
351
                        } else {
352
                            // we already store the session in login, so we
353
                            // don't need here
354
                            /*
355
                             * MetaCatUtil.debugMessage("in no sessionid
356
                             * parameter ", 40); sess_id =
357
                             * (String)sess.getId();
358
                             * MetaCatUtil.debugMessage("storing the session id "
359
                             * + sess_id + " which has username " +
360
                             * sess.getAttribute("username") + " into session
361
                             * hash in handleGetOrPost method", 35);
362
                             */
363
                        }
364
                    } catch (IllegalStateException ise) {
365
                        System.out.println(
366
                                "error in handleGetOrPost: this shouldn't "
367
                                + "happen: the session should be valid: "
368
                                + ise.getMessage());
369
                    }
612 370

  
613
  // SQUERY & QUERY SECTION
614
  /**
615
   * Retreive the squery xml, execute it and display it
616
   *
617
   * @param out the output stream to the client
618
   * @param params the Hashtable of parameters that should be included
619
   * in the squery.
620
   * @param response the response object linked to the client
621
   * @param conn the database connection
622
   */
623
  protected void handleSQuery(PrintWriter out, Hashtable params,
624
                 HttpServletResponse response, String user, String[] groups,
625
                 String sessionid)
626
  {
627
    double startTime = System.currentTimeMillis()/1000;
628
    DBQuery queryobj = new DBQuery(saxparser);
629
    queryobj.findDocuments(response, out, params, user, groups, sessionid);
630
    double outPutTime = System.currentTimeMillis()/1000;
631
    MetaCatUtil.debugMessage("total search time: "+(outPutTime-startTime), 30);
371
                    username = (String) sess.getAttribute("username");
372
                    MetaCatUtil.debugMessage("The user name from session is: "
373
                            + username, 20);
374
                    password = (String) sess.getAttribute("password");
375
                    groupnames = (String[]) sess.getAttribute("groupnames");
376
                }
632 377

  
633
  }
378
                //make user user username should be public
379
                if (username == null || (username.trim().equals(""))) {
380
                    username = "public";
381
                }
382
                MetaCatUtil.debugMessage("The user is : " + username, 5);
383
            }
384
            // Now that we know the session is valid, we can delegate the
385
            // request
386
            // to a particular action handler
387
            if (action.equals("query")) {
388
                PrintWriter out = response.getWriter();
389
                handleQuery(out, params, response, username, groupnames,
390
                        sess_id);
391
                out.close();
392
            } else if (action.equals("squery")) {
393
                PrintWriter out = response.getWriter();
394
                if (params.containsKey("query")) {
395
                    handleSQuery(out, params, response, username, groupnames,
396
                            sess_id);
397
                    out.close();
398
                } else {
399
                    out.println(
400
                            "Illegal action squery without \"query\" parameter");
401
                    out.close();
402
                }
403
            } else if (action.equals("export")) {
634 404

  
635
   /**
636
    * Create the xml query, execute it and display the results.
637
    *
638
    * @param out the output stream to the client
639
    * @param params the Hashtable of parameters that should be included
640
    * in the squery.
641
    * @param response the response object linked to the client
642
    */
643
  protected void handleQuery(PrintWriter out, Hashtable params,
644
                 HttpServletResponse response, String user, String[] groups,
645
                 String sessionid)
646
  {
647
    //create the query and run it
648
    String xmlquery = DBQuery.createSQuery(params);
649
    String []queryArray = new String[1];
650
    queryArray[0] = xmlquery;
651
    params.put("query", queryArray);
652
    double startTime = System.currentTimeMillis()/1000;
653
    DBQuery queryobj = new DBQuery(saxparser);
654
    queryobj.findDocuments(response, out, params, user, groups, sessionid);
655
    double outPutTime = System.currentTimeMillis()/1000;
656
    MetaCatUtil.debugMessage("total search time: "+(outPutTime-startTime), 30);
405
                handleExportAction(params, response, username, groupnames,
406
                        password);
407
            } else if (action.equals("read")) {
408
                handleReadAction(params, response, username, password,
409
                        groupnames);
410
            } else if (action.equals("readinlinedata")) {
411
                handleReadInlineDataAction(params, response, username,
412
                        password, groupnames);
413
            } else if (action.equals("insert") || action.equals("update")) {
414
                PrintWriter out = response.getWriter();
415
                if ((username != null) && !username.equals("public")) {
416
                    handleInsertOrUpdateAction(out, params, username,
417
                            groupnames);
418
                } else {
419
                    out.println("Permission denied for user " + username + " "
420
                            + action);
421
                }
422
                out.close();
423
            } else if (action.equals("delete")) {
424
                PrintWriter out = response.getWriter();
425
                if ((username != null) && !username.equals("public")) {
426
                    handleDeleteAction(out, params, response, username,
427
                            groupnames);
428
                } else {
429
                    out.println("Permission denied for " + action);
430
                }
431
                out.close();
432
            } else if (action.equals("validate")) {
433
                PrintWriter out = response.getWriter();
434
                handleValidateAction(out, params);
435
                out.close();
436
            } else if (action.equals("setaccess")) {
437
                PrintWriter out = response.getWriter();
438
                handleSetAccessAction(out, params, username);
439
                out.close();
440
            } else if (action.equals("getaccesscontrol")) {
441
                PrintWriter out = response.getWriter();
442
                handleGetAccessControlAction(out, params, response, username,
443
                        groupnames);
444
                out.close();
445
            } else if (action.equals("getprincipals")) {
446
                PrintWriter out = response.getWriter();
447
                handleGetPrincipalsAction(out, username, password);
448
                out.close();
449
            } else if (action.equals("getdoctypes")) {
450
                PrintWriter out = response.getWriter();
451
                handleGetDoctypesAction(out, params, response);
452
                out.close();
453
            } else if (action.equals("getdtdschema")) {
454
                PrintWriter out = response.getWriter();
455
                handleGetDTDSchemaAction(out, params, response);
456
                out.close();
457
            } else if (action.equals("getlastdocid")) {
458
                PrintWriter out = response.getWriter();
459
                handleGetMaxDocidAction(out, params, response);
460
                out.close();
461
            } else if (action.equals("getrevisionanddoctype")) {
462
                PrintWriter out = response.getWriter();
463
                handleGetRevisionAndDocTypeAction(out, params);
464
                out.close();
465
            } else if (action.equals("getversion")) {
466
                response.setContentType("text/xml");
467
                PrintWriter out = response.getWriter();
468
                out.println(Version.getVersionAsXml());
469
                out.close();
470
            } else if (action.equals("login") || action.equals("logout")) {
471
            } else if (action.equals("protocoltest")) {
472
                String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
473
                try {
474
                    testURL = ((String[]) params.get("url"))[0];
475
                } catch (Throwable t) {
476
                }
477
                String phandler = System
478
                        .getProperty("java.protocol.handler.pkgs");
479
                response.setContentType("text/html");
480
                PrintWriter out = response.getWriter();
481
                out.println("<body bgcolor=\"white\">");
482
                out.println("<p>Handler property: <code>" + phandler
483
                        + "</code></p>");
484
                out.println("<p>Starting test for:<br>");
485
                out.println("    " + testURL + "</p>");
486
                try {
487
                    URL u = new URL(testURL);
488
                    out.println("<pre>");
489
                    out.println("Protocol: " + u.getProtocol());
490
                    out.println("    Host: " + u.getHost());
491
                    out.println("    Port: " + u.getPort());
492
                    out.println("    Path: " + u.getPath());
493
                    out.println("     Ref: " + u.getRef());
494
                    String pquery = u.getQuery();
495
                    out.println("   Query: " + pquery);
496
                    out.println("  Params: ");
497
                    if (pquery != null) {
498
                        Hashtable qparams = util.parseQuery(u.getQuery());
499
                        for (Enumeration en = qparams.keys(); en
500
                                .hasMoreElements();) {
501
                            String pname = (String) en.nextElement();
502
                            String pvalue = (String) qparams.get(pname);
503
                            out.println("    " + pname + ": " + pvalue);
504
                        }
505
                    }
506
                    out.println("</pre>");
507
                    out.println("</body>");
508
                    out.close();
509
                } catch (MalformedURLException mue) {
510
                    System.out.println(
511
                            "bad url from MetacatServlet.handleGetOrPost");
512
                    out.println(mue.getMessage());
513
                    mue.printStackTrace(out);
514
                    out.close();
515
                }
516
            } else {
517
                PrintWriter out = response.getWriter();
518
                out.println("<?xml version=\"1.0\"?>");
519
                out.println("<error>");
520
                out.println(
521
                     "Error: action not registered.  Please report this error.");
522
                out.println("</error>");
523
                out.close();
524
            }
657 525

  
526
            //util.closeConnections();
527
            // Close the stream to the client
528
            //out.close();
529
        }
530
    }
658 531

  
659
    //handleSQuery(out, params, response,user, groups, sessionid);
660
  }
661

  
662
  // END OF SQUERY & QUERY SECTION
663

  
664
 //Exoport section
665
 /**
666
   * Handle the "export" request of data package from Metacat in zip format
667
   * @param params the Hashtable of HTTP request parameters
668
   * @param response the HTTP response object linked to the client
669
   * @param user the username sent the request
670
   * @param groups the user's groupnames
671
   */
672
  private void handleExportAction(Hashtable params,
673
    HttpServletResponse response, String user, String[] groups, String passWord)
674
  {
675
    // Output stream
676
    ServletOutputStream out = null;
677
    // Zip output stream
678
    ZipOutputStream zOut = null;
679
    DocumentImpl docImpls=null;
680
    DBQuery queryObj=null;
681

  
682
    String[] docs = new String[10];
683
    String docId = "";
684

  
685
    try
532
    // LOGIN & LOGOUT SECTION
533
    /**
534
     * Handle the login request. Create a new session object. Do user
535
     * authentication through the session.
536
     */
537
    private void handleLoginAction(PrintWriter out, Hashtable params,
538
            HttpServletRequest request, HttpServletResponse response)
686 539
    {
687
      // read the params
688
      if (params.containsKey("docid"))
689
      {
690
        docs = (String[])params.get("docid");
691
      }//if
692
      // Create a DBuery to handle export
693
      queryObj = new DBQuery(saxparser);
694
      // Get the docid
695
      docId=docs[0];
696
      // Make sure the client specify docid
697
      if (docId == null || docId.equals(""))
698
      {
699
        response.setContentType("text/xml"); //MIME type
700
        // Get a printwriter
701
        PrintWriter pw = response.getWriter();
702
        // Send back message
703
        pw.println("<?xml version=\"1.0\"?>");
704
        pw.println("<error>");
705
        pw.println("You didn't specify requested docid");
706
        pw.println("</error>");
707
        // Close printwriter
708
        pw.close();
709
        return;
710
      }//if
711
      // Get output stream
712
      out = response.getOutputStream();
713
      response.setContentType("application/zip"); //MIME type
714
      zOut = new ZipOutputStream(out);
715
      zOut =queryObj.getZippedPackage(docId, out, user, groups, passWord);
716
      zOut.finish(); //terminate the zip file
717
      zOut.close();  //close the zip stream
718 540

  
719
    }//try
720
    catch (Exception e)
721
    {
722
      try
723
      {
724
        response.setContentType("text/xml"); //MIME type
725
        // Send error message back
726
        if (out != null)
727
        {
728
            PrintWriter pw = new PrintWriter(out);
729
            pw.println("<?xml version=\"1.0\"?>");
730
            pw.println("<error>");
731
            pw.println(e.getMessage());
732
            pw.println("</error>");
733
            // Close printwriter
734
            pw.close();
735
            // Close output stream
736
            out.close();
737
        }//if
738
        // Close zip output stream
739
        if ( zOut != null )
740
        {
741
          zOut.close();
742
        }//if
743
      }//try
744
      catch (IOException ioe)
745
      {
746
        MetaCatUtil.debugMessage("Problem with the servlet output " +
747
                           "in MetacatServlet.handleExportAction: " +
748
                           ioe.getMessage(), 30);
749
      }//catch
541
        AuthSession sess = null;
542
        String un = ((String[]) params.get("username"))[0];
543
        MetaCatUtil.debugMessage("user " + un + " try to login", 20);
544
        String pw = ((String[]) params.get("password"))[0];
545
        String action = ((String[]) params.get("action"))[0];
546
        String qformat = ((String[]) params.get("qformat"))[0];
750 547

  
751
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleExportAction: " +
752
                         e.getMessage(), 30);
753
      e.printStackTrace(System.out);
548
        try {
549
            sess = new AuthSession();
550
        } catch (Exception e) {
551
            System.out.println("error in MetacatServlet.handleLoginAction: "
552
                    + e.getMessage());
553
            out.println(e.getMessage());
554
            return;
555
        }
556
        boolean isValid = sess.authenticate(request, un, pw);
754 557

  
755
    }//catch
558
        //if it is authernticate is true, store the session
559
        if (isValid) {
560
            HttpSession session = sess.getSessions();
561
            String id = session.getId();
562
            MetaCatUtil.debugMessage("Store session id " + id
563
                    + "which has username" + session.getAttribute("username")
564
                    + " into hash in login method", 35);
565
            sessionHash.put(id, session);
566
        }
756 567

  
757
  }//handleExportAction
568
        // format and transform the output
569
        if (qformat.equals("xml")) {
570
            response.setContentType("text/xml");
571
            out.println(sess.getMessage());
572
        } else {
573
            try {
574
                DBTransform trans = new DBTransform();
575
                response.setContentType("text/html");
576
                trans.transformXMLDocument(sess.getMessage(),
577
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
578
                        out, null);
579
            } catch (Exception e) {
758 580

  
581
                MetaCatUtil.debugMessage(
582
                        "Error in MetaCatServlet.handleLoginAction: "
583
                                + e.getMessage(), 30);
584
            }
585
        }
586
    }
759 587

  
760
   //read inline data section
761
 /**
762
   * In eml2 document, the xml can have inline data and data was stripped off
763
   * and store in file system. This action can be used to read inline data only
764
   * @param params the Hashtable of HTTP request parameters
765
   * @param response the HTTP response object linked to the client
766
   * @param user the username sent the request
767
   * @param groups the user's groupnames
768
   */
769
  private void handleReadInlineDataAction(Hashtable params,
770
                                          HttpServletResponse response,
771
                                          String user, String passWord,
772
                                          String[] groups)
773
  {
774
    String[] docs = new String[10];
775
    String inlineDataId = null;
776
    String docId = "";
777
    ServletOutputStream out = null;
778

  
779
    try
588
    /**
589
     * Handle the logout request. Close the connection.
590
     */
591
    private void handleLogoutAction(PrintWriter out, Hashtable params,
592
            HttpServletRequest request, HttpServletResponse response)
780 593
    {
781
      // read the params
782
      if (params.containsKey("inlinedataid"))
783
      {
784
        docs = (String[])params.get("inlinedataid");
785
      }//if
786
      // Get the docid
787
      inlineDataId=docs[0];
788
      // Make sure the client specify docid
789
      if (inlineDataId == null || inlineDataId.equals(""))
790
      {
791
        throw new Exception("You didn't specify requested inlinedataid");
792
      }//if
793 594

  
794
      // check for permission
795
      docId = MetaCatUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
796
      PermissionController controller = new PermissionController(docId);
797
      // check top level read permission
798
      if (!controller.hasPermission(user, groups,
799
                                    AccessControlInterface.READSTRING))
800
      {
801
          throw new Exception("User "+ user + " doesn't have permission "+
802
                              " to read document " + docId);
803
      }//if
804
      // if the document has subtree control, we need to check subtree control
805
      else if(controller.hasSubTreeAccessControl())
806
      {
807
        // get node id for inlinedata
808
        long nodeId=getInlineDataNodeId(inlineDataId, docId);
809
        if (!controller.hasPermissionForSubTreeNode(user, groups,
810
                                     AccessControlInterface.READSTRING, nodeId))
811
        {
812
           throw new Exception("User "+ user + " doesn't have permission "+
813
                              " to read inlinedata " + inlineDataId);
814
        }//if
595
        String qformat = ((String[]) params.get("qformat"))[0];
815 596

  
816
      }//else
597
        // close the connection
598
        HttpSession sess = request.getSession(false);
599
        MetaCatUtil.debugMessage("After get session in logout request", 40);
600
        if (sess != null) {
601
            MetaCatUtil.debugMessage("The session id " + sess.getId()
602
                    + " will be invalidate in logout action", 30);
603
            MetaCatUtil.debugMessage("The session contains user "
604
                    + sess.getAttribute("username")
605
                    + " will be invalidate in logout action", 30);
606
            sess.invalidate();
607
        }
817 608

  
818
      // Get output stream
819
      out = response.getOutputStream();
820
      // read the inline data from the file
821
      String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
822
      File lineData = new File(inlinePath, inlineDataId);
823
      FileInputStream input = new FileInputStream(lineData);
824
      byte [] buffer = new byte[4*1024];
825
      int bytes = input.read(buffer);
826
      while (bytes != -1)
827
      {
828
        out.write(buffer, 0, bytes);
829
        bytes = input.read(buffer);
830
      }
831
      out.close();
609
        // produce output
610
        StringBuffer output = new StringBuffer();
611
        output.append("<?xml version=\"1.0\"?>");
612
        output.append("<logout>");
613
        output.append("User logged out");
614
        output.append("</logout>");
832 615

  
833
    }//try
834
    catch (Exception e)
835
    {
836
      try
837
      {
838
        PrintWriter pw = null;
839
        // Send error message back
840
        if (out != null)
841
        {
842
            pw = new PrintWriter(out);
843
        }//if
844
        else
845
        {
846
          pw = response.getWriter();
616
        //format and transform the output
617
        if (qformat.equals("xml")) {
618
            response.setContentType("text/xml");
619
            out.println(output.toString());
620
        } else {
621
            try {
622
                DBTransform trans = new DBTransform();
623
                response.setContentType("text/html");
624
                trans.transformXMLDocument(output.toString(),
625
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
626
                        out, null);
627
            } catch (Exception e) {
628
                MetaCatUtil.debugMessage(
629
                        "Error in MetaCatServlet.handleLogoutAction"
630
                                + e.getMessage(), 30);
631
            }
847 632
        }
848
         pw.println("<?xml version=\"1.0\"?>");
849
         pw.println("<error>");
850
         pw.println(e.getMessage());
851
         pw.println("</error>");
852
         // Close printwriter
853
         pw.close();
854
         // Close output stream if out is not null
855
         if (out != null)
856
         {
857
           out.close();
858
         }
859
     }//try
860
     catch (IOException ioe)
861
     {
862
        MetaCatUtil.debugMessage("Problem with the servlet output " +
863
                           "in MetacatServlet.handleExportAction: " +
864
                           ioe.getMessage(), 30);
865
     }//catch
633
    }
866 634

  
867
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadInlineDataAction: "
868
                                + e.getMessage(), 30);
635
    // END OF LOGIN & LOGOUT SECTION
869 636

  
870
    }//catch
637
    // SQUERY & QUERY SECTION
638
    /**
639
     * Retreive the squery xml, execute it and display it
640
     * 
641
     * @param out the output stream to the client
642
     * @param params the Hashtable of parameters that should be included in the
643
     *            squery.
644
     * @param response the response object linked to the client
645
     * @param conn the database connection
646
     */
647
    protected void handleSQuery(PrintWriter out, Hashtable params,
648
            HttpServletResponse response, String user, String[] groups,
649
            String sessionid)
650
    {
651
        double startTime = System.currentTimeMillis() / 1000;
652
        DBQuery queryobj = new DBQuery(saxparser);
653
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
654
        double outPutTime = System.currentTimeMillis() / 1000;
655
        MetaCatUtil.debugMessage("total search time: "
656
                + (outPutTime - startTime), 30);
871 657

  
872
  }//handleReadInlineDataAction
658
    }
873 659

  
874
  /*
875
   * Get the nodeid from xml_nodes for the inlinedataid
876
   */
877
  private long getInlineDataNodeId(String inLineDataId, String docId)
878
                                   throws SQLException
879
  {
880
    long nodeId = 0;
881
    String INLINE = "inline";
882
    boolean hasRow;
883
    PreparedStatement pStmt = null;
884
    DBConnection conn = null;
885
    int serialNumber = -1;
886
    String sql ="SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? " +
887
                "AND nodetype='TEXT' AND parentnodeid IN " +
888
                "(SELECT nodeid FROM xml_nodes WHERE docid=? AND " +
889
                "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
890

  
891
    try
660
    /**
661
     * Create the xml query, execute it and display the results.
662
     * 
663
     * @param out the output stream to the client
664
     * @param params the Hashtable of parameters that should be included in the
665
     *            squery.
666
     * @param response the response object linked to the client
667
     */
668
    protected void handleQuery(PrintWriter out, Hashtable params,
669
            HttpServletResponse response, String user, String[] groups,
670
            String sessionid)
892 671
    {
893
      //check out DBConnection
894
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
895
      serialNumber=conn.getCheckOutSerialNumber();
672
        //create the query and run it
673
        String xmlquery = DBQuery.createSQuery(params);
674
        String[] queryArray = new String[1];
675
        queryArray[0] = xmlquery;
676
        params.put("query", queryArray);
677
        double startTime = System.currentTimeMillis() / 1000;
678
        DBQuery queryobj = new DBQuery(saxparser);
679
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
680
        double outPutTime = System.currentTimeMillis() / 1000;
681
        MetaCatUtil.debugMessage("total search time: "
682
                + (outPutTime - startTime), 30);
896 683

  
897
      pStmt = conn.prepareStatement(sql);
898
      //bind value
899
      pStmt.setString(1, docId);//docid
900
      pStmt.setString(2, inLineDataId);//inlinedataid
901
      pStmt.setString(3, docId);
902
      // excute query
903
      pStmt.execute();
904
      ResultSet rs = pStmt.getResultSet();
905
      hasRow=rs.next();
906
      // get result
907
      if (hasRow)
908
      {
909
        nodeId = rs.getLong(1);
910
      }//if
911

  
912
    }//try
913
    catch (SQLException e)
914
    {
915
      throw e;
684
        //handleSQuery(out, params, response,user, groups, sessionid);
916 685
    }
917
    finally
918
    {
919
      try
920
      {
921
        pStmt.close();
922
      }
923
      finally
924
      {
925
        DBConnectionPool.returnDBConnection(conn, serialNumber);
926
      }
927
    }
928
    MetaCatUtil.debugMessage("The nodeid for inlinedataid " + inLineDataId +
929
                             " is: "+nodeId, 35);
930
    return nodeId;
931
  }
932 686

  
687
    // END OF SQUERY & QUERY SECTION
933 688

  
689
    //Exoport section
690
    /**
691
     * Handle the "export" request of data package from Metacat in zip format
692
     * 
693
     * @param params the Hashtable of HTTP request parameters
694
     * @param response the HTTP response object linked to the client
695
     * @param user the username sent the request
696
     * @param groups the user's groupnames
697
     */
698
    private void handleExportAction(Hashtable params,
699
            HttpServletResponse response, String user, String[] groups,
700
            String passWord)
701
    {
702
        // Output stream
703
        ServletOutputStream out = null;
704
        // Zip output stream
705
        ZipOutputStream zOut = null;
706
        DocumentImpl docImpls = null;
707
        DBQuery queryObj = null;
934 708

  
935
  // READ SECTION
936
  /**
937
   * Handle the "read" request of metadata/data files from Metacat
938
   * or any files from Internet;
939
   * transformed metadata XML document into HTML presentation if requested;
940
   * zip files when more than one were requested.
941
   *
942
   * @param params the Hashtable of HTTP request parameters
943
   * @param response the HTTP response object linked to the client
944
   * @param user the username sent the request
945
   * @param groups the user's groupnames
946
   */
947
  private void handleReadAction(Hashtable params, HttpServletResponse response,
948
                                String user, String passWord, String[] groups)
949
  {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff