Project

General

Profile

« Previous | Next » 

Revision 6268

cleaning up the handlers -- removing superclass methods.

View differences:

src/edu/ucsb/nceas/metacat/restservice/MNResourceHandler.java
211 211
                        status = true;
212 212
                    }
213 213
                    
214
                    // post to register system metadata
215
                    if (httpVerb == POST) {
216
                    	registerSystemMetadata(objectId);
217
                    	status = true;
218
                    }
219

  
220 214
                } else if (resource.equals(RESOURCE_OBJECTS)) {
221 215
                    System.out.println("Using resource 'object'");
222 216

  
......
661 655
     * Implements REST version of DataONE CRUD API --> get
662 656
     * @param guid ID of data object to be read
663 657
     */
664
    @Override
665 658
    protected void getObject(String guid) {
666 659
        OutputStream out = null;
667 660
        try {
......
856 849
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
857 850
     * @param guid ID of data object to be read
858 851
     */
859
    @Override
860 852
    protected void getSystemMetadataObject(String guid) {
861 853
        OutputStream out = null;
862 854
        try {
......
981 973
     * @param guid - ID of data object to be inserted or updated.  If action is update, the pid
982 974
     *               is the existing pid.  If insert, the pid is the new one
983 975
     */
984
    @Override
985 976
    protected void putObject(String pid, String action) {
986 977
        System.out.println("putObject with pid " + pid);
987 978
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
......
1199 1190
        out.close();
1200 1191
    }
1201 1192
    
1193
    
1194
    
1195
    
1202 1196
    /**
1203 1197
     * set the access perms on a document
1204 1198
     * @throws Exception
1205 1199
     */
1206
    @Override
1207 1200
    protected void setaccess() throws Exception
1208 1201
    {
1209 1202
        try
src/edu/ucsb/nceas/metacat/restservice/CNResourceHandler.java
28 28
import java.io.IOException;
29 29
import java.io.InputStream;
30 30
import java.io.OutputStream;
31
import java.io.PrintWriter;
31 32
import java.util.Date;
32 33
import java.util.Hashtable;
33 34
import java.util.Iterator;
......
56 57
import org.dataone.service.exceptions.NotImplemented;
57 58
import org.dataone.service.exceptions.ServiceFailure;
58 59
import org.dataone.service.exceptions.UnsupportedType;
60
import org.dataone.service.types.AccessPolicy;
59 61
import org.dataone.service.types.Checksum;
60 62
import org.dataone.service.types.Event;
61 63
import org.dataone.service.types.Identifier;
......
196 198
                    }
197 199
                    // reserve the ID (in params)
198 200
                    if (httpVerb == GET) {
199
                    	asserRelation(objectId);
201
                    	assertRelation(objectId);
200 202
                    	status = true;
201 203
                    }    
202 204
                } else if (resource.equals(RESOURCE_RESOLVE)) {
......
545 547
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
546 548
     * @param guid ID of data object to be read
547 549
     */
548
    @Override
549 550
    protected void getSystemMetadataObject(String guid) {
550 551
        OutputStream out = null;
551 552
        try {
......
927 928
		}
928 929
    }
929 930

  
930
    private boolean asserRelation(String id) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented {
931
    private boolean assertRelation(String id) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented {
931 932
		Identifier pidOfSubject = new Identifier();
932 933
		pidOfSubject.setValue(id);
933 934
		Identifier pidOfObject = new Identifier();
......
1112 1113
			serializeException(e, out);
1113 1114
    }
1114 1115
	}
1116
    
1117
    /**
1118
     * set the access perms on a document
1119
     * @throws Exception
1120
     */
1121
    protected void setaccess() throws Exception
1122
    {
1123
        try
1124
        {
1125
            String guid = params.get("guid")[0];
1126
            Identifier id = new Identifier();
1127
            id.setValue(guid);
1128
            String accesspolicy = params.get("accesspolicy")[0];
1129
            AccessPolicy accessPolicy = (AccessPolicy) deserializeServiceType(AccessPolicy.class, new ByteArrayInputStream(accesspolicy.getBytes("UTF-8")));
1130
            CNodeService.getInstance().setAccessPolicy(session, id, accessPolicy);
1131
        }
1132
        catch(Exception e)
1133
        {
1134
            response.setStatus(500);
1135
            printError("Error setting access in D1ResourceHandler: " + e.getClass() + ": " + e.getMessage(), response);
1136
            throw e;
1137
        }
1138
    }
1139
    
1140
    /**
1141
     * Earthgrid API > Query Service > Query Function : translates ecogrid query document to metacat query 
1142
     * then calls DBQuery > createResultDocument function and then again translate resultset to ecogrid resultset
1143
     * 
1144
     * NOTE:
1145
     *      This is the only method that uses EcoGrid classes for its implementation.  
1146
     *      It does so because it takes an EcoGrid Query as input, and outputs an
1147
     *      EcoGrid ResultSet document.  These documents are parsed by the auto-generated
1148
     *      EcoGrid classes from axis, and so we link to them here rather than re-inventing them.
1149
     *      This creates a circular dependency, because the Metacat classes are needed
1150
     *      to build the EcoGrid implementation, and the EcoGrid jars are needed to build this query()
1151
     *      method.  This circularity could be resolved by moving the EcoGrid classes
1152
     *      to Metacat directly.  As we transition away from EcoGrid SOAP methods in
1153
     *      favor of these REST interfaces, this circular dependency can be eliminated.
1154
     *        
1155
     * @throws Exception
1156
     */
1157
    private void query() throws Exception {
1158
        /*  This block commented out because of the EcoGrid circular dependency.
1159
         *  For now, query will not be supported until the circularity can be
1160
         *  resolved, probably by moving the ecogrid query syntax transformers
1161
         *  directly into the Metacat codebase.  MBJ 2010-02-03
1162
         
1163
        try {
1164
            EcogridQueryParser parser = new EcogridQueryParser(request
1165
                    .getReader());
1166
            parser.parseXML();
1167
            QueryType queryType = parser.getEcogridQuery();
1168
            EcogridJavaToMetacatJavaQueryTransformer queryTransformer = 
1169
                new EcogridJavaToMetacatJavaQueryTransformer();
1170
            QuerySpecification metacatQuery = queryTransformer
1171
                    .transform(queryType);
1115 1172

  
1173
            DBQuery metacat = new DBQuery();
1174

  
1175
            boolean useXMLIndex = (new Boolean(PropertyService
1176
                    .getProperty("database.usexmlindex"))).booleanValue();
1177
            String xmlquery = "query"; // we don't care the query in resultset,
1178
            // the query can be anything
1179
            PrintWriter out = null; // we don't want metacat result, so set out null
1180

  
1181
            // parameter: queryspecification, user, group, usingIndexOrNot
1182
            StringBuffer result = metacat.createResultDocument(xmlquery,
1183
                    metacatQuery, out, username, groupNames, useXMLIndex);
1184

  
1185
            // create result set transfer       
1186
            String saxparser = PropertyService.getProperty("xml.saxparser");
1187
            MetacatResultsetParser metacatResultsetParser = new MetacatResultsetParser(
1188
                    new StringReader(result.toString()), saxparser, queryType
1189
                            .getNamespace().get_value());
1190
            ResultsetType records = metacatResultsetParser.getEcogridResult();
1191

  
1192
            System.out
1193
                    .println(EcogridResultsetTransformer.toXMLString(records));
1194
            response.setContentType("text/xml");
1195
            out = response.getWriter();
1196
            out.print(EcogridResultsetTransformer.toXMLString(records));
1197

  
1198
        } catch (Exception e) {
1199
            e.printStackTrace();
1200
        }*/
1201
        response.setContentType("text/xml");
1202
        response.setStatus(501);
1203
        PrintWriter out = response.getWriter();
1204
        out.print("<error>Query operation not yet supported by Metacat.</error>");
1205
        out.close();
1206
    }
1207

  
1116 1208
}
src/edu/ucsb/nceas/metacat/restservice/D1ResourceHandler.java
22 22
 */
23 23
package edu.ucsb.nceas.metacat.restservice;
24 24

  
25
import java.io.ByteArrayInputStream;
26 25
import java.io.File;
27
import java.io.FileInputStream;
28
import java.io.FileOutputStream;
29 26
import java.io.IOException;
30 27
import java.io.InputStream;
31 28
import java.io.OutputStream;
32 29
import java.io.PrintWriter;
33
import java.io.StringReader;
34
import java.net.URL;
35 30
import java.text.DateFormat;
36 31
import java.text.ParseException;
37 32
import java.text.SimpleDateFormat;
38 33
import java.util.Date;
39 34
import java.util.Enumeration;
40 35
import java.util.Hashtable;
41
import java.util.Iterator;
42
import java.util.List;
43
import java.util.Map;
44 36
import java.util.TimeZone;
45 37
import java.util.Timer;
46 38

  
......
50 42

  
51 43
import org.apache.commons.io.IOUtils;
52 44
import org.apache.log4j.Logger;
53
import org.apache.maven.artifact.ant.shaded.IOUtil;
54
import org.dataone.client.MNode;
55
import org.dataone.client.ObjectFormatCache;
56 45
import org.dataone.client.auth.CertificateManager;
57
import org.dataone.mimemultipart.MultipartRequest;
58
import org.dataone.mimemultipart.MultipartRequestResolver;
59
import org.dataone.service.NodeListParser;
60 46
import org.dataone.service.exceptions.BaseException;
61
import org.dataone.service.exceptions.IdentifierNotUnique;
62
import org.dataone.service.exceptions.InsufficientResources;
63
import org.dataone.service.exceptions.InvalidRequest;
64
import org.dataone.service.exceptions.InvalidSystemMetadata;
65
import org.dataone.service.exceptions.InvalidToken;
66
import org.dataone.service.exceptions.NotAuthorized;
67
import org.dataone.service.exceptions.NotFound;
68
import org.dataone.service.exceptions.NotImplemented;
69
import org.dataone.service.exceptions.ServiceFailure;
70
import org.dataone.service.exceptions.UnsupportedType;
71
import org.dataone.service.types.AccessPolicy;
72
import org.dataone.service.types.Checksum;
73
import org.dataone.service.types.DescribeResponse;
74
import org.dataone.service.types.Event;
75
import org.dataone.service.types.Identifier;
76
import org.dataone.service.types.Log;
77
import org.dataone.service.types.Node;
78
import org.dataone.service.types.NodeList;
79
import org.dataone.service.types.NodeReference;
80
import org.dataone.service.types.NodeType;
81
import org.dataone.service.types.ObjectFormat;
82
import org.dataone.service.types.ObjectFormatIdentifier;
83
import org.dataone.service.types.ObjectFormatList;
84
import org.dataone.service.types.ObjectList;
85
import org.dataone.service.types.Service;
86
import org.dataone.service.types.Services;
87 47
import org.dataone.service.types.Session;
88
import org.dataone.service.types.SystemMetadata;
89 48
import org.dataone.service.types.util.ServiceTypeUtil;
90
import org.jibx.runtime.BindingDirectory;
91
import org.jibx.runtime.IBindingFactory;
92
import org.jibx.runtime.IUnmarshallingContext;
93 49
import org.jibx.runtime.JiBXException;
94 50

  
95
import edu.ucsb.nceas.metacat.DBUtil;
96
import edu.ucsb.nceas.metacat.IdentifierManager;
97
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
98
import edu.ucsb.nceas.metacat.MetaCatServlet;
99 51
import edu.ucsb.nceas.metacat.MetacatHandler;
100
import edu.ucsb.nceas.metacat.dataone.CNodeService;
101
import edu.ucsb.nceas.metacat.dataone.HealthService;
102
import edu.ucsb.nceas.metacat.dataone.MNodeService;
103 52
import edu.ucsb.nceas.metacat.properties.PropertyService;
104
import edu.ucsb.nceas.metacat.service.SessionService;
105
import edu.ucsb.nceas.metacat.util.RequestUtil;
106
import edu.ucsb.nceas.metacat.util.SessionData;
107
import edu.ucsb.nceas.metacat.util.SystemUtil;
108 53
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
109 54
/**
110 55
 * 
111
 * Implements Earthgrid REST API to Metacat <br/><br/> 
56
 * Base class for handling D1 REST calls in Metacat
112 57
 * 
113
 * <ul>
114
 * <li>
115
 * <h3> EarthGrid Query Service</h3>
116
 * <ul><li>
117
 * <h3>Get & Authenticated Get:</h3> 
118
 * is equal to Metacat's read action and returns a data file having
119
 * the specified <doc-id> in the resource path. For authenticated Get service, a session id must be provided 
120
 * in the query string. <br/><br/>
121
 * 
122
 * <b>REST URL:</b> <code>GET, [context-root]/object/[doc-id]?sessionid=[sessionid] </code><br/>
123
 * <b>Returns:</b> data file <br/><br/>
124
 * </li>
125
 * 
126
 * <li>
127
 * <h3>Query & Authenticated Query:</h3> 
128
 * Metacat's equivalent is squery action but this function 
129
 * receives a Earthgrid query document and returns Earthgrid resultset document by transforming those documents
130
 * to Metacat's equivalents by the means of Metacat Implementation in Earthgrid library. For authenticated Query service 
131
 * a session id must be provided in the query string. See Earthgrid (a.k.a. Ecogrid) project for XSD files of 
132
 * query and resultset documents<br/><br/>
133
 * 
134
 * <b>REST URL:</b> <code>POST, [context-root]/object?sessionid=[sessionid]</code>    <br/>
135
 * <b>POST Data:</b> Earthgrid query document , Content-type: <code>text/xml</code><br/>
136
 * <b>Returns:</b> Earthgrid resultset document<br/><br/>
137
 * 
138
 * </li>
139
 * </ul>
140
 * 
141
 * </li>
142
 * 
143
 * <li>
144
 * <h3> EarthGrid Authentication Service</h3>
145
 * <ul><li>
146
 * <h3>Login: </h3> 
147
 * Receives username and password parameters in POST data and 
148
 * returns SessionId (in XML format) or failure message and uses MetacatHandler's handleLoginAction function<br/><br/>
149
 *  
150
 * <b>REST URL:</b> <code>POST, [context-root]/session?op=login</code> <br/>
151
 * <b>POST Data:</b> username=[username]&password=[password], Content-type: <code>application/x-www-form-urlencoded</code>
152
 * <b>Returns:</b> sessionId in XML format<br/><br/>
153
 * </li>
154
 * 
155
 * <li>
156
 * <h3>Logout: </h3> 
157
 * Receives session Id parameters in querystring and returns xml message, calls 
158
 * MetacatHandler's handleLogoutAction function<br/><br/>
159
 *  
160
 * <b>REST URL:</b> <code>GET, [context-root]/session?op=logout&sessionid=[sessionid]</code>   <br/>
161
 * <b>Returns:</b> message in XML format<br/><br/>
162
 * </li>
163
 * </ul>
164
 * 
165
 * <li>
166
 * <h3>EarthGrid Put Service</h3>
167
 * 
168
 * <ul>
169
 * <li><h3>Update/Insert: </h3>     
170
 * <br/>
171
 * <b>REST URL:</b> <code>PUT, [context-root]/object/[doc-id]?op={update|insert}&sessionid=[sessionid]</code>   <br/>
172
 * <b>POST Data:</b> document object, Content-type: <code>text/xml</code><br/>
173
 * <b>Returns:</b> message in XML format<br/><br/>
174
 * </li>
175
 * 
176
 * <li><h3>Delete: </h3>        
177
 * <br/>
178
 * <b>REST URL:</b> <code>DELETE, [context-root]/object/[doc-id]?sessionid=[sessionid]</code>   <br/>
179
 * <b>Returns:</b> message in XML format<br/><br/>
180
 * </li>
181

  
182
 * </ul>
183
 * </li>
184
 * 
185
 * <li>
186
 * <h3>EarthGrid Identifier Service</h3><br/>
187
 * 
188
 * <ul>
189
 * <li><h3>isRegistered: </h3>      <br/>
190
 * <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=isregistered</code>   <br/>
191
 * <b>Returns:</b> message in XML format<br/><br/>
192
 * </li>
193

  
194
 * <li><h3>getAllDocIds:</h3>       <br/>       
195
 * <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getalldocids</code>   <br/>
196
 * <b>Returns:</b> document id list in XML format<br/><br/>
197
 * </li>
198
 * 
199
 * <li><h3>addLSID Function:</h3> 
200
 * Metacat does not support this function       <br/>
201
 * <b>REST URL:</b> <code>PUT, [context-root]/identifier/[doc-id]</code>   <br/>
202
 * <b>Returns:</b> error message in XML format<br/><br/>
203
 * </li>
204
 * 
205
 * <li><h3>getNextRevision:</h3>        <br/>
206
 * <b>REST URL:</b> <code>GET, [context-root]/identifier/[doc-id]?op=getnextrevision</code>   <br/>
207
 * <b>Returns:</b> message in XML format<br/><br/>
208
 * </li>
209
 * 
210
 * <li><h3>getNextObject:</h3>      <br/>
211
 * <b>REST URL:</b> <code>GET, [context-root]/identifier?op=getnextobject&scope=[scope]</code>   <br/>
212
 * <b>Returns:</b> message in XML format<br/><br/>
213
 * </li>
214
 * 
215
 * </li>
216
 * </ul>
217
 * 
58
 * @author leinfelder
218 59
 */
219 60
public class D1ResourceHandler {
220 61

  
......
287 128
    }
288 129

  
289 130
    /**
290
     * This function is called from REST APU servlet and handles each request to the servlet 
131
     * This function is called from REST API servlet and handles each request 
291 132
     * 
292 133
     * @param httpVerb (GET, POST, PUT or DELETE)
293 134
     */
294 135
    public void handle(byte httpVerb) {
295 136
        logMetacat = Logger.getLogger(D1ResourceHandler.class);
296 137
        try {
297
            String resource = request.getServletPath();
298
            if(resource.endsWith("d1/") || resource.endsWith("d1"))
299
            {
300
                resource = RESOURCE_BASE_URL;
301
            }
302
            else
303
            {
304
                //substring off the /d1/
305
                resource = resource.substring(resource.indexOf("d1/") + 3, resource.length());
306
                resource = resource.trim();
307
            }
308
            
309
            String verb = "";
310
            
311
            System.out.println("handling verb " + httpVerb + " request with resource '" + resource + "'");
312
            System.out.println("resource: '" + resource + "'");
313
            System.out.println("resource_monitor: '" + RESOURCE_MONITOR + "'");
314
            boolean status = false;
315
            // load session the old way
316
            loadSessionData();
317
            
138
  
318 139
            // load session from certificate in request
319 140
            session = CertificateManager.getInstance().getSession(request);
320
            
321
            
322
            if (resource != null) {
323
                //resource = request.getServletPath().substring(1);
324 141

  
325
                params = new Hashtable<String, String[]>();
326
                initParams();
142
            // initialize the parameters
143
            params = new Hashtable<String, String[]>();
144
            initParams();
327 145

  
328
                Timer timer = new Timer();
329
                handler = new MetacatHandler(timer);
146
            // create the handler for interacting with Metacat
147
            Timer timer = new Timer();
148
            handler = new MetacatHandler(timer);
330 149

  
331
                if(resource.equals(RESOURCE_BASE_URL)) {
332
                    //node registry response
333
                    System.out.println("Using resource 'd1' (node registry response)");
334
                    createNodeResponse();
335
                    status = true;
336
                    
337
                } else if (resource.equals(RESOURCE_SESSION) && 
338
                        httpVerb == POST && 
339
                        params.get(FUNCTION_KEYWORD) != null) {
340
                    System.out.println("Using resource 'session'");
341
                    //System.out.println("function_keyword: " + params.get(FUNCTION_KEYWORD)[0]);
342
                    if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGIN)) {
343
                        login();
344
                        status = true;
345
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_LOGOUT)) {
346
                        logout();
347
                        status = true;
348
                    } else if (params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_SET_ACCESS)) {
349
                        setaccess();
350
                        status = true;
351
                        System.out.println("done setting access");
352
                    }
353
                } else if (resource.equals(RESOURCE_META)) {
354
                    System.out.println("Using resource 'meta'");
355
                    if (params != null && params.get(FUNCTION_KEYWORD) != null &&
356
                            params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA))
357
                    { 
358
                        status = true;
359
                    }
360
                    else
361
                    {
362
                        String objectId = request.getPathInfo();
363
                        if (objectId != null && objectId.length() > 1) 
364
                        {
365
                            objectId = request.getPathInfo().substring(1);
366
                        }
367
                        
368
                        // get
369
                        if (httpVerb == GET) {
370
	                        getSystemMetadataObject(objectId);
371
	                        status = true;
372
                        }
373
                        
374
                        // post to register system metadata
375
                        if (httpVerb == POST) {
376
                        	registerSystemMetadata(objectId);
377
                        	status = true;
378
                        }
379
                        
380
                    }
381

  
382
                } else if (resource.equals(RESOURCE_OBJECTS)) {
383
                    System.out.println("Using resource 'object'");
384
                    logMetacat.debug("D1 Rest: Starting resource processing...");
385
                    loadSessionData();
386

  
387
                    String objectId = request.getPathInfo();
388
                    if (objectId != null && objectId.length() > 1) 
389
                    {
390
                        objectId = request.getPathInfo().substring(1);
391
                    }
392
                    else
393
                    {
394
                        objectId = null;
395
                    }
396
                    
397
                    System.out.println("objectId in ReasourceHandler.handle: " + objectId);
398

  
399
                    logMetacat.debug("verb:" + httpVerb);
400

  
401
                    if (httpVerb == GET) {
402
                        getObject(objectId);
403
                        status = true;
404
                    } else if (httpVerb == POST) {
405
                        putObject(objectId, FUNCTION_NAME_INSERT);
406
                        status = true;
407
                    } else if (httpVerb == PUT) {
408
                        putObject(objectId, FUNCTION_NAME_UPDATE);
409
                        status = true;
410
                    } else if (httpVerb == DELETE) {
411
                        deleteObject(objectId);
412
                        status = true;
413
                    } else if (httpVerb == HEAD) {
414
                        describeObject(objectId);
415
                        status = true;
416
                    }
417
                    
418
                } else if (resource.equals(RESOURCE_FORMATS)) {
419
                  System.out.println("Using resource 'formats'");
420
                  
421
                  // check for a format identifier
422
                  String fmtid = request.getPathInfo();
423
                  
424
                  if ( fmtid != null && fmtid.length() > 1 ) {
425
                  	fmtid = request.getPathInfo().substring(1);
426
                  	
427
                  } else {
428
                  	fmtid = null;
429
                  	
430
                  }
431
                  
432
                  // handle each verb
433
                  if ( httpVerb == GET ) {
434
                  	if ( fmtid == null ) {
435
                      // list the formats collection
436
                  		listFormats();
437
                  		
438
                  	} else {
439
                  		// get the specified format
440
                  		getFormat(fmtid);
441

  
442
                  	}
443
                  	status = true;
444
                  
445
                  } else if ( httpVerb == PUT ) {
446
                  	status = true;
447
                  	
448
                  } else if ( httpVerb == POST ) {
449
                  	status = true;
450
                  	
451
                  } else if ( httpVerb == DELETE ) {
452
                  	status = true;
453
                  	
454
                  } else if ( httpVerb == HEAD ) {
455
                  	status = true;
456
                  	
457
                  }
458
                  
459
                } else if (resource.equals(RESOURCE_IDENTIFIER)) {
460
                    System.out.println("Using resource 'identifier'");
461
                    String identifierId = request.getPathInfo();
462
                    if (identifierId != null && identifierId.length() > 1)
463
                        identifierId = request.getPathInfo().substring(1); //trim the slash
464

  
465
                    if (httpVerb == GET) {
466
                        String op = params.get(FUNCTION_KEYWORD)[0];
467
                        if (op.equals(FUNCTION_NAME_ISREGISTERED)) {
468
                            isRegistered(identifierId);
469
                            status = true;
470
                        } else if (op.equals(FUNCTION_NAME_GETALLDOCS)) {
471
                            getAllDocIds();
472
                            status = true;
473
                        } else if (op.equals(FUNCTION_NAME_GETNEXTREV)) {
474
                            getNextRevision(identifierId);
475
                            status = true;
476
                        } else if (op.equals(FUNCTION_NAME_GETNEXTOBJ)) {
477
                            getNextObject();
478
                            status = true;
479
                        } 
480

  
481
                    } else if (httpVerb == PUT) {
482
                        //Earthgrid API > Identifier Service > addLSID Function 
483
                        response.setStatus(501);
484
                        printError(
485
                                "This method is not supported by metacat.  To "
486
                                + "add a new LSID, add a document to metacat.",
487
                                response);
488
                        status = true;
489
                    }
490

  
491
                } else if (resource.equals(RESOURCE_LOG)) {
492
                    System.out.println("Using resource 'log'");
493
                    //handle log events
494
                    if(httpVerb == GET)
495
                    {
496
                        getLog();
497
                        status = true;
498
                    }
499
                    else
500
                    {
501
                        //change to D1 spec for specifying which http methods are allowed for a resource
502
                        response.setStatus(501);
503
                        printError("POST, PUT, DELETE is not supported for logs.", response);
504
                        status = true;
505
                    }
506

  
507
                } else if(resource.equals(RESOURCE_CHECKSUM)) {
508
                    System.out.println("Using resource 'checksum'");
509
                    //handle checksum requests
510
                    if(httpVerb == GET)
511
                    {
512
                        String checksumAlgorithm = "MD5";
513
                    
514
                        String guid = request.getPathInfo();
515
                        if (guid != null && guid.length() > 1)
516
                            guid = request.getPathInfo().substring(1); //trim the slash
517
                        
518
                        Identifier guidid = new Identifier();
519
                        guidid.setValue(guid);
520
                        try
521
                        {
522
                            checksumAlgorithm = params.get("checksumAlgorithm")[0];
523
                        }
524
                        catch(Exception e)
525
                        {
526
                            //do nothing.  default to MD5
527
                        }
528
                        System.out.println("getting checksum for object " + guid +
529
                                " with algorithm " + checksumAlgorithm);
530
                        try
531
                        {
532
                            Checksum c = MNodeService.getInstance().getChecksum(session, guidid, checksumAlgorithm);
533
                            System.out.println("got checksum " + c.getValue());
534
                            response.setStatus(200);
535
                            System.out.println("serializing response");
536
                            serializeServiceType(Checksum.class, c, response.getOutputStream());
537
                            System.out.println("done serializing response.");
538
                        }
539
                        catch(NotAuthorized na)
540
                        {
541
                            na.setDetail_code("1400");
542
                            serializeException(na, response.getOutputStream());
543
                        }
544
                        catch(NotFound nf)
545
                        {
546
                            nf.setDetail_code("1420");
547
                            serializeException(nf, response.getOutputStream());
548
                        }
549
                        catch(InvalidRequest ir)
550
                        {
551
                            ir.setDetail_code("1402");
552
                            serializeException(ir, response.getOutputStream());
553
                        }
554
                        catch(ServiceFailure sf)
555
                        {
556
                            sf.setDetail_code("1410");
557
                            serializeException(sf, response.getOutputStream());
558
                        }
559
                        catch(InvalidToken it)
560
                        {
561
                            it.setDetail_code("1430");
562
                            serializeException(it, response.getOutputStream());
563
                        }
564
                        status = true;
565
                    }
566
                } else if(resource.equals(RESOURCE_MONITOR)) {
567
                    //health monitoring calls
568
                    System.out.println("processing monitor request");
569
                    String pathInfo = request.getPathInfo();
570
                    if(httpVerb == GET)
571
                    {
572
                        System.out.println("verb is GET");
573
                        System.out.println("pathInfo is " + pathInfo);
574
                        pathInfo = pathInfo.substring(1);
575
                        HealthService hs = new HealthService(request, response);
576
                        if (pathInfo.toLowerCase().equals("ping")) {
577
                            System.out.println("processing ping request");
578
                            hs.ping();
579
                        } else if (pathInfo.toLowerCase().equals("status")) {
580
                            System.out.println("processing status request");
581
                            hs.getStatus();
582
                        } else if (pathInfo.toLowerCase().equals("object")) {
583
                            System.out.println("processing object request");
584
                            boolean day = false;
585
                            Identifier pid = null;
586
                            String url = null;
587
                            ObjectFormat of = null;
588
                            Date time = null;
589
                            
590
                            if(params.containsKey("day"))
591
                            {
592
                               day = true; 
593
                            }
594
                            if(params.containsKey("pid"))
595
                            {
596
                                String id = params.get("pid")[0];
597
                                pid = new Identifier();
598
                                pid.setValue(id);
599
                            }
600
                            if(params.containsKey("url"))
601
                            {
602
                                url = params.get("url")[0];
603
                            }
604
                            if(params.containsKey("format"))
605
                            {
606
                                String format = params.get("format")[0];
607
                                of = ObjectFormatCache.getInstance().getFormat(format);
608
                            }
609
                            if(params.containsKey("time"))
610
                            {
611
                                String t = params.get("time")[0];
612
                                time = dateFormat.parse(t);
613
                            }
614
                            
615
                            hs.getObjectStatistics(day, pid, url, of, time);
616
                        } else if (pathInfo.toLowerCase().equals("event")) {
617
                            System.out.println("processing event request");
618
                            boolean day = false;
619
                            Identifier pid = null;
620
                            Date created = null;
621
                            ObjectFormat of = null;
622
                            Date time = null;
623
                            String ipAddress = null;
624
                            String event = null;
625
                            
626
                            if(params.containsKey("day"))
627
                            {
628
                               day = true; 
629
                            }
630
                            if(params.containsKey("pid"))
631
                            {
632
                                String id = params.get("pid")[0];
633
                                pid = new Identifier();
634
                                pid.setValue(id);
635
                            }
636
                            if(params.containsKey("created"))
637
                            {
638
                                String t = params.get("created")[0];
639
                                created = dateFormat.parse(t);
640
                            }
641
                            if(params.containsKey("format"))
642
                            {
643
                                String format = params.get("format")[0];
644
                                of = ObjectFormatCache.getInstance().getFormat(format);
645
                            }
646
                            if(params.containsKey("eventtime"))
647
                            {
648
                                String t = params.get("eventtime")[0];
649
                                time = dateFormat.parse(t);
650
                            }
651
                            if(params.containsKey("ip_address"))
652
                            {
653
                                ipAddress = params.get("ip_address")[0];
654
                            }
655
                            if(params.containsKey("event"))
656
                            {
657
                                event = params.get("event")[0];
658
                            }
659
                            
660
                            hs.getOperationStatistics(day, pid, of, created, time, ipAddress, event);
661
                        }
662
                    }
663
                    status = true;
664
                } else if(resource.equals(RESOURCE_REPLICATE)) {
665
                    System.out.println("processing replicate request");
666
                    replicate(httpVerb, request, response);
667
                    status = true;
668
                }
669
                    
670
                if (!status)
671
                {
672
                    response.setStatus(400);
673
                    printError("Incorrect parameters!", response);
674
                }
675
            } else {
676
                response.setStatus(400);
677
                printError("Incorrect resource!", response);
678
            }
679 150
        } catch (Exception e) {
680
            logMetacat.error(e.getClass() + ": " + e.getMessage());
681
            System.out.println("Error in D1ResourceHandler.handle(): " + e.getClass() + ": " + e.getMessage());
682
            e.printStackTrace();
151
        	// TODO: more D1 structure when failing here
152
        	response.setStatus(400);
153
            printError("Incorrect resource!", response);
154
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
683 155
        }
684 156
    }
685 157
    
686 158
		/**
687
     * handle the /replicate action
688
     * @param httpVerb
689
     * @param request
690
     * @param response
691
     * @throws Exception
692
     */
693
    private void replicate(int httpVerb, HttpServletRequest request, HttpServletResponse response)
694
        throws Exception
695
    {
696
        if(httpVerb == POST)
697
        {
698
            System.out.println("in POST replicate()");
699
            /*InputStream is = request.getInputStream();
700
            String input = IOUtils.toString(is);
701
            System.out.println("input: " + input);
702
            is = IOUtils.toInputStream(input);*/
703
            
704
            File tmpDir = getTempDirectory();
705
            File tmpSMFile = new File(tmpDir + 
706
                    ".sysmeta." + new Date().getTime() + ".tmp");
707
            System.out.println("temp dir: " + tmpDir.getAbsolutePath());
708
            MultipartRequestResolver mrr = new MultipartRequestResolver(
709
                    tmpDir.getAbsolutePath(), 1000000000, 0);
710
            MultipartRequest mr = mrr.resolveMultipart(request);
711
            Map<String, File> files = mr.getMultipartFiles();
712
            Iterator keys = files.keySet().iterator();
713
            while(keys.hasNext())
714
            {
715
                String key = (String)keys.next();
716
                System.out.println("files key: " + key);
717
                System.out.println("files value: " + files.get(key));
718
            }
719
            
720
            Map<String, List<String>> params = mr.getMultipartParameters();
721
            keys = params.keySet().iterator();
722
            while(keys.hasNext())
723
            {
724
                String key = (String)keys.next();
725
                System.out.println("params key: " + key);
726
                System.out.println("params value: " + params.get(key));
727
            }
728
            
729
            //File f = files.get("sysmeta");
730
            //the files are not being keyed by the part name, but rather the filename
731
            File f = files.get(files.keySet().iterator().next());
732
            
733
            System.out.println("file: " + f.getAbsolutePath());
734
            String sourceNode = params.get("sourceNode").get(0);
735
            System.out.println("sourceNode: " + sourceNode);
736
            FileInputStream fis = new FileInputStream(f);
737
            
738
            //lookup the id in the registry
739
            URL url = new URL("http://cn.dataone.org/cn/node");
740
            InputStream urlis = url.openStream();
741
            Map<String,String> m = NodeListParser.parseNodeListFile(urlis);
742
            String nodeUrl = m.get(sourceNode);
743
            System.out.println("sourceNodeId: " + sourceNode);
744
            System.out.println("resolved sourceNodeUrl: " + nodeUrl);
745
            
746
            if(nodeUrl == null)
747
            {
748
                response.setStatus(500);
749
                response.getOutputStream().write(("Member Node id " + 
750
                        sourceNode + " not found in node registry.").getBytes());
751
                response.getOutputStream().close();
752
            }
753
            
754
            //respond to cn with 200/OK
755
            //String s;
756
            //s = "sysmeta: " + IOUtils.toString(fis);
757
            //s += "\n\n";
758
            response.setStatus(200);
759
            //response.getOutputStream().write(("sourceNode: " + sourceNode + "\n\n").getBytes());
760
            //response.getOutputStream().write(("s: " + s).getBytes());
761
            OutputStream out = response.getOutputStream();
762
            out.write("OK\n".getBytes());
763
            out.write(("sourceNodeId: " + sourceNode + "\n").getBytes());
764
            out.write(("sourceNodeUrl: " + nodeUrl + "\n").getBytes());
765
            out.close();
766
            
767
            //parse the systemMetadata
768
            SystemMetadata sm = (SystemMetadata)deserializeServiceType(SystemMetadata.class, fis);
769
            NodeReference nr = sm.getOriginMemberNode();
770
            nr.setValue(sourceNode);
771
            sm.setOriginMemberNode(nr);
772
            //get the document
773
            MNode mnode = new MNode(nodeUrl);
774
            //get the doc from the remote host
775
            InputStream docStream = mnode.get(session, sm.getIdentifier());
776
            File outputTmpFile = getTempFile();
777
            System.out.println("wrote xml file to " + outputTmpFile.getAbsolutePath());
778
            FileOutputStream outputTmpFileStream = new FileOutputStream(outputTmpFile);
779
            IOUtils.copy(docStream, outputTmpFileStream);
780
            
781
            //verify checksum
782
            System.out.println("verifying checksum");
783
            Checksum sourceFileChecksum = ServiceTypeUtil.checksum(new FileInputStream(outputTmpFile), 
784
                    sm.getChecksum().getAlgorithm());
785
            
786
            String cs1 = sm.getChecksum().getValue();
787
            String cs2 = sourceFileChecksum.getValue();
788
            System.out.println("original checksum: " + cs1);
789
            System.out.println(" created checksum: " + cs2);
790
            
791
            if(!cs1.equals(cs2))
792
            {
793
                System.out.println("ERROR: Checksums do not match!");
794
            }
795
            
796
            //insert the document in local db
797
            //System.out.println("creating new doc");
798
            //CrudService.getInstance().create(token, 
799
            //        sm.getIdentifier(), new FileInputStream(outputTmpFile), sm);
800
            //call cn.setReplicationStatus(guid, COMPLETE)
801
            
802
        }
803
    }
804
    
805
    /**
806
     * create the root node registry response.  
807
     * @throws JiBXException
808
     * @throws IOException
809
     */
810
    private void createNodeResponse() 
811
        throws JiBXException, IOException
812
    {
813
        String nodeName = null;
814
        String nodeId = null;
815
        String nodeUrl = null;
816
        String nodeDesc = null;
817
        String nodeType = null;
818
        
819
        try
820
        {
821
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
822
            nodeName = PropertyService.getProperty("dataone.nodeName");
823
            nodeUrl = SystemUtil.getContextURL() + "/d1/";
824
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
825
            nodeType = PropertyService.getProperty("dataone.nodeType");
826
        }
827
        catch(PropertyNotFoundException pnfe)
828
        {
829
            logMetacat.error("createNodeResponse: " +
830
                    "property not found: " + pnfe.getMessage());
831
        }
832
        
833
        NodeList nl = new NodeList();
834
        Node n = new Node();
835
        NodeReference nr = new NodeReference();
836
        nr.setValue(nodeId);
837
        n.setIdentifier(nr);
838
        n.setBaseURL(nodeUrl);
839
        n.setDescription(nodeDesc);
840
        n.setName(nodeName + " -- WAR version WARVERSION");
841
        n.setType(NodeType.convert(nodeType));
842
        
843
        //create the services
844
        Service mnCrud03 = new Service();
845
        mnCrud03.setName("Metacat MN_Crud Services Version 0.3");
846
        mnCrud03.setVersion("0.3");
847
        
848
        Service mnCrud04 = new Service();
849
        mnCrud04.setName("Metacat MN_Crud Services Version 0.4");
850
        mnCrud04.setVersion("0.4");
851
        
852
        Service mnCrud09 = new Service();
853
        mnCrud09.setName("Metacat MN_Crud Services Version 0.9");
854
        mnCrud09.setVersion("0.9");
855
        
856
        Service mnReplication03 = new Service();
857
        mnReplication03.setName("Metcat MN_Replication Version 0.3");
858
        mnReplication03.setVersion("0.3");
859
        
860
        Service mnHealth04 = new Service();
861
        mnHealth04.setName("Metacat MN_Health Version 0.4");
862
        mnHealth04.setVersion("0.4");
863
        
864
        Service mnHealth06 = new Service();
865
        mnHealth06.setName("Metacat MN_Health Version 0.6");
866
        mnHealth06.setVersion("0.6");
867
        
868
        Service mnAuthentication07 = new Service();
869
        mnAuthentication07.setName("Metacat MN_Authentication Version 0.7");
870
        mnAuthentication07.setVersion("0.7");
871
        
872
        Service mnAuthorization07 = new Service();
873
        mnAuthorization07.setName("Metacat MN_Authorization Version 0.7");
874
        mnAuthorization07.setVersion("0.7");
875
        
876
        Services ss = new Services();
877
        ss.addService(mnCrud03);
878
        ss.addService(mnCrud04);
879
        ss.addService(mnCrud09);
880
        ss.addService(mnReplication03);
881
        ss.addService(mnHealth04);
882
        ss.addService(mnHealth06);
883
        ss.addService(mnAuthentication07);
884
        ss.addService(mnAuthorization07);
885
        nl.addNode(n);
886
        response.setContentType("text/xml");
887
        response.setStatus(200);
888
        serializeServiceType(NodeList.class, nl, response.getOutputStream());
889
    }
890
    
891
    /**
892
     * MN_crud.describe()
893
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.describe
894
     * @param guid
895
     */
896
    private void describeObject(String guid)
897
    {
898
        Logger logMetacat = Logger.getLogger(D1ResourceHandler.class);
899
        OutputStream out = null;
900
        try
901
        {
902
            out = response.getOutputStream();
903
        }
904
        catch(Exception e)
905
        {
906
            logMetacat.error("Error getting output stream in D1ResourceHandler.describeObject: " + e.getClass() + ": " + e.getMessage());
907
            return;
908
        }
909
        response.setStatus(200);
910
        response.setContentType("text/xml");
911
        Identifier id = new Identifier();
912
        id.setValue(guid);
913
        try
914
        {
915
            DescribeResponse dr = MNodeService.getInstance().describe(session, id);
916
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SZ");
917
            response.addHeader("guid", guid);
918
            response.addHeader("checksum", dr.getDataONE_Checksum().getValue());
919
            response.addHeader("checksum_algorithm", dr.getDataONE_Checksum().getAlgorithm().name());
920
            response.addHeader("content_length", dr.getContent_Length() + "");
921
            response.addHeader("last_modified", dateFormat.format(dr.getLast_Modified()));
922
            response.addHeader("format", dr.getDataONE_ObjectFormat().toString());
923
        }
924
        catch(InvalidRequest ir)
925
        {
926
            serializeException(ir, out);
927
        }
928
        catch(NotImplemented ni)
929
        {
930
            serializeException(ni, out);
931
        }
932
        catch(NotAuthorized na)
933
        {
934
            serializeException(na, out);
935
        }
936
        catch(ServiceFailure sf)
937
        {
938
            serializeException(sf, out);
939
        }
940
        catch(NotFound nf)
941
        {
942
            serializeException(nf, out);
943
        }
944
        catch(InvalidToken it)
945
        {
946
            serializeException(it, out);
947
        }
948
    }
949
    
950
    /**
951
     * get the logs from the CrudService based on passed params.  Available 
952
     * params are token, fromDate, toDate, event.  See 
953
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
954
     * for more info
955
     */
956
    private void getLog()
957
    {
958
        OutputStream out = null;
959
        try
960
        {
961
            out = response.getOutputStream();
962
            response.setStatus(200);
963
            response.setContentType("text/xml");
964
            String fromDateS = params.get("fromDate")[0];
965
            System.out.println("param fromDateS: " + fromDateS);
966
            Date fromDate = null;
967
            String toDateS = params.get("toDate")[0];
968
            System.out.println("param toDateS: " + toDateS);
969
            Date toDate = null;
970
            String eventS = params.get("event")[0];
971
            Event event = null;
972
            if(fromDateS != null)
973
            {
974
                //fromDate = dateFormat.parse(fromDateS);
975
                fromDate = parseDateAndConvertToGMT(fromDateS);
976
            }
977
            if(toDateS != null)
978
            {
979
                //toDate = dateFormat.parse(toDateS);
980
                toDate = parseDateAndConvertToGMT(toDateS);
981
            }
982
            if(eventS != null)
983
            {
984
                event = Event.convert(eventS);
985
            }
986
            System.out.println("fromDate: " + fromDate + " toDate: " + toDate);
987
            
988
            Integer start = null;
989
            Integer count = null;
990
            try {
991
            	start =  Integer.parseInt(params.get("start")[0]);
992
            } catch (Exception e) {
993
				logMetacat.warn("Could not parse start: " + e.getMessage());
994
			}
995
            try {
996
            	count =  Integer.parseInt(params.get("count")[0]);
997
            } catch (Exception e) {
998
				logMetacat.warn("Could not count start: " + e.getMessage());
999
			}
1000
            
1001
            System.out.println("calling crudservice.getLogRecords");
1002
            Log log = MNodeService.getInstance().getLogRecords(session, fromDate, toDate, event, start, count);
1003
            serializeServiceType(Log.class, log, out);
1004
        }
1005
        catch(Exception e)
1006
        {
1007
            String msg = "Could not get logs from CrudService: " + e.getClass() + ": " + e.getMessage();
1008
            response.setStatus(500);
1009
            ServiceFailure sf = new ServiceFailure("1490", msg);
1010
            logMetacat.error(msg);
1011
            e.printStackTrace();
1012
            serializeException(sf, out);
1013
        }
1014
    }
1015
    
1016
    /**
1017 159
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
1018 160
     */
1019 161
    protected void initParams() {
......
1029 171
    }
1030 172

  
1031 173
    /**
1032
     * 
1033
     * Load user details of metacat session from the request 
1034
     * 
1035
     */
1036
    private void loadSessionData()
1037
      throws Exception
1038
    {
1039
        SessionData sessionData = RequestUtil.getSessionData(request);
1040
        try
1041
        {
1042
            username = null;
1043
            password = null;
1044
            groupNames = null;
1045
            sessionId = null;
1046
            
1047
            boolean validSession = false;
1048
            SessionService ss = SessionService.getInstance();
1049
            System.out.println("sessionData: " + sessionData);
1050
            if(sessionData == null)
1051
            {
1052
                username = "public";
1053
                sessionId = "0";
1054
                System.out.println("sessiondata is null.  Creating a public session.");
1055
                return;
1056
            }
1057
            
1058
            System.out.println("username: " + sessionData.getUserName());
1059
            System.out.println("sessionid: " + sessionData.getId());
1060
            //validate the session
1061
            if(ss.isSessionRegistered(sessionData.getId()) && 
1062
               !(sessionData.getUserName().equals("public") || sessionData.getId().equals("0")))
1063
            {
1064
                validSession = true;
1065
            }
1066
            
1067
            if(validSession)
1068
            {
1069
                //if the session is valid, set these variables
1070
                username = sessionData.getUserName();
1071
                password = sessionData.getPassword();
1072
                groupNames = sessionData.getGroupNames();
1073
                sessionId = sessionData.getId();
1074
                System.out.println("setting sessionid to " + sessionId);
1075
                System.out.println("username: " + username);
1076
            }
1077
            
1078
            //if the session is not valid or the username is null, set
1079
            //username to public
1080
            if (username == null) 
1081
            {
1082
                System.out.println("setting username to public.");
1083
                username = "public";
1084
            }
1085
        }
1086
        catch(Exception e)
1087
        {
1088
            e.printStackTrace();
1089
            throw new Exception("Could not load the session data: " + e.getClass() + ": " + e.getMessage());
1090
        }
1091
    }
1092

  
1093
    /**
1094
     *  Earthgrid API > Identifier Service > isRegistered Function : 
1095
     *  calls MetacatHandler > handleIdIsRegisteredAction
1096
     * @param guid
1097
     * @throws IOException
1098
     */
1099
    private void isRegistered(String guid) throws IOException
1100
    {
1101
        
1102
        // Look up the localId for this guid
1103
        IdentifierManager im = IdentifierManager.getInstance();
1104
        String localId = "";
1105
        try {
1106
            localId = im.getLocalId(guid);
1107
        } catch (McdbDocNotFoundException e) {
1108
            // TODO: Need to return the proper DataONE exception
1109
        }
1110
        
1111
        params.put("docid", new String[] { localId });
1112
        PrintWriter out = response.getWriter();
1113
        response.setStatus(200);
1114
        response.setContentType("text/xml");
1115
        handler.handleIdIsRegisteredAction(out, params, response);
1116
        out.close();
1117
    }
1118

  
1119
    /**
1120
     * Earthgrid API > Identifier Service > getAllDocIds Function : 
1121
     * calls MetacatHandler > handleGetAllDocidsAction
1122
     * @throws IOException
1123
     */
1124
    private void getAllDocIds() throws IOException {
1125
        PrintWriter out = response.getWriter();
1126
        response.setStatus(200);
1127
        response.setContentType("text/xml");
1128
        handler.handleGetAllDocidsAction(out, params, response);
1129
        out.close();
1130
    }
1131

  
1132
    /**
1133
     * Earthgrid API > Identifier Service > getNextRevision Function : 
1134
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
1135
     * @param guid
1136
     * @throws IOException
1137
     */
1138
    private void getNextRevision(String guid) throws IOException 
1139
    {
1140
        params.put("docid", new String[] { guid });
1141
        PrintWriter out = response.getWriter();
1142
        response.setStatus(200);
1143
        response.setContentType("text/xml");
1144
        //handler.handleGetRevisionAndDocTypeAction(out, params);
1145

  
1146
        try {
1147
            // Make sure there is a docid
1148
            if (guid == null || guid.equals("")) {
1149
                throw new Exception("User didn't specify docid!");
1150
            }
1151

  
1152
            // Look up the localId for this guid
1153
            IdentifierManager im = IdentifierManager.getInstance();
1154
            String localId = "";
1155
            try {
1156
                localId = im.getLocalId(guid);
1157
            } catch (McdbDocNotFoundException e) {
1158
                // TODO: Need to return the proper DataONE exception
1159
            }
1160
           
1161
            // Create a DBUtil object
1162
            DBUtil dbutil = new DBUtil();
1163
            // Get a rev and doctype
1164
            String revAndDocType = dbutil
1165
                    .getCurrentRevisionAndDocTypeForGivenDocument(localId);
1166
            int revision = Integer.parseInt(revAndDocType.split(";")[0]) + 1;
1167

  
1168
            out.println("<?xml version=\"1.0\"?>");
1169
            out.print("<next-revision>");
1170
            out.print(revision);
1171
            out.print("</next-revision>");
1172

  
1173
        } catch (Exception e) {
1174
            // Handle exception
1175
            response.setStatus(500);
1176
            out.println("<?xml version=\"1.0\"?>");
1177
            out.println("<error>");
1178
            out.println(e.getClass() + ": " + e.getMessage());
1179
            out.println("</error>");
1180
        }
1181

  
1182
        out.close();
1183
    }
1184

  
1185
    /**
1186
     * Earthgrid API > Identifier Service > getNextObject Function : 
1187
     * calls MetacatHandler > handleGetMaxDocidAction
1188
     * @throws IOException
1189
     */
1190
    private void getNextObject() throws IOException {
1191
        PrintWriter out = response.getWriter();
1192
        response.setStatus(200);
1193
        response.setContentType("text/xml");
1194
        handler.handleGetMaxDocidAction(out, params, response);
1195
        out.close();
1196
    }
1197

  
1198
    /**
1199
     * Implements REST version of DataONE CRUD API --> get
1200
     * @param guid ID of data object to be read
1201
     */
1202
    protected void getObject(String guid) {
1203
        OutputStream out = null;
1204
        try {
1205
            out = response.getOutputStream();
1206
            response.setStatus(200);
1207
            
1208
            if(guid != null)
1209
            { //get a specific document                
1210
                Identifier id = new Identifier();
1211
                id.setValue(guid);
1212
                try
1213
                {
1214
                    
1215
                    SystemMetadata sm = MNodeService.getInstance().getSystemMetadata(session, id);
1216
                    
1217
                    //set the content type
1218
                    if(sm.getObjectFormat().getFmtid().getValue().trim().equals(
1219
                    		ObjectFormatCache.getInstance().getFormat("text/csv").getFmtid().getValue()))
1220
                    {
1221
                        response.setContentType("text/csv");
1222
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".csv");
1223
                    }
1224
                    else if(sm.getObjectFormat().getFmtid().getValue().trim().equals(
1225
                    		ObjectFormatCache.getInstance().getFormat("text/plain").getFmtid().getValue()))
1226
                    {
1227
                        response.setContentType("text/plain");
1228
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".txt");
1229
                    } 
1230
                    else if(sm.getObjectFormat().getFmtid().getValue().trim().equals(
1231
                    		ObjectFormatCache.getInstance().getFormat("application/octet-stream").getFmtid().getValue()))
1232
                    {
1233
                        response.setContentType("application/octet-stream");
1234
                    }
1235
                    else
1236
                    {
1237
                        response.setContentType("text/xml");
1238
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".xml");
1239
                    }
1240
                    
1241
                    InputStream data = MNodeService.getInstance().get(session, id);
1242
                    IOUtils.copyLarge(data, response.getOutputStream());
1243
                }
1244
                catch(InvalidToken it)
1245
                {
1246
                    response.setStatus(500);
1247
                    serializeException(it, out); 
1248
                }
1249
                catch(ServiceFailure sf)
1250
                {
1251
                    response.setStatus(500);
1252
                    serializeException(sf, out); 
1253
                }
1254
                catch(NotAuthorized na)
1255
                {
1256
                    response.setStatus(500);
1257
                    serializeException(na, out); 
1258
                }
1259
                catch(NotFound nf)
1260
                {
1261
                    response.setStatus(500);
1262
                    serializeException(nf, out); 
1263
                }
1264
                catch(NotImplemented ni)
1265
                {
1266
                    response.setStatus(500);
1267
                    serializeException(ni, out); 
1268
                }
1269
                catch(Exception e)
1270
                {
1271
                    response.setStatus(500);
1272
                    System.out.println("Error with Crud.get().  " +
1273
                            "If this is an 'Exception producing data' error, " +
1274
                            "go to CrudService.get() for better debugging.  " +
1275
                            "Here's the error: " + e.getClass() + ": " + e.getMessage());
1276
                    e.printStackTrace();
1277
                    ServiceFailure sf = new ServiceFailure("1030", 
1278
                            "IO Error in D1ResourceHandler.getObject: " + e.getClass() + ": " + e.getMessage());
1279
                    serializeException(sf, out); 
1280
                }
1281
            }
1282
            else
1283
            { //call listObjects with specified params
1284
                Date startTime = null;
1285
                Date endTime = null;
1286
                ObjectFormat objectFormat = null;
1287
                boolean replicaStatus = false;
1288
                int start = 0;
1289
                //TODO: make the max count into a const
1290
                int count = 1000;
1291
                Enumeration paramlist = request.getParameterNames();
1292
                while (paramlist.hasMoreElements()) 
1293
                { //parse the params and make the crud call
1294
                    String name = (String) paramlist.nextElement();
1295
                    String[] value = (String[])request.getParameterValues(name);
1296
                    /*for(int i=0; i<value.length; i++)
1297
                    {
1298
                        System.out.println("name: " + name + " value: " + value[i]);
1299
                    }*/
1300
                    if(name.equals("startTime") && value != null)
1301
                    {
1302
                        try
1303
                        {
1304
                          //startTime = dateFormat.parse(value[0]);
1305
                            startTime = parseDateAndConvertToGMT(value[0]);
1306
                        }
1307
                        catch(Exception e)
1308
                        {  //if we can't parse it, just don't use the startTime param
1309
                            System.out.println("Could not parse startTime: " + value[0]);
1310
                            startTime = null;
1311
                        }
1312
                    }
1313
                    else if(name.equals("endTime") && value != null)
1314
                    {
1315
                        try
1316
                        {
1317
                          //endTime = dateFormat.parse(value[0]);
1318
                            endTime = parseDateAndConvertToGMT(value[0]);
1319
                        }
1320
                        catch(Exception e)
1321
                        {  //if we can't parse it, just don't use the endTime param
1322
                            System.out.println("Could not parse endTime: " + value[0]);
1323
                            endTime = null;
1324
                        }
1325
                    }
1326
                    else if(name.equals("objectFormat") && value != null) 
1327
                    {
1328
                        objectFormat = ObjectFormatCache.getInstance().getFormat(value[0]);
1329
                    }
1330
                    else if(name.equals("replicaStatus") && value != null)
1331
                    {
1332
                        if(value != null && 
1333
                           value.length > 0 && 
1334
                           (value[0].equals("true") || value[0].equals("TRUE") || value[0].equals("YES")))
1335
                        {
1336
                            replicaStatus = true;
1337
                        }
1338
                    }
1339
                    else if(name.equals("start") && value != null)
1340
                    {
1341
                        start = new Integer(value[0]).intValue();
1342
                    }
1343
                    else if(name.equals("count") && value != null)
1344
                    {
1345
                        count = new Integer(value[0]).intValue();
1346
                    }
1347
                }
1348
                //make the crud call
1349
                System.out.println("session: " + session + " startTime: " + startTime +
1350
                        " endtime: " + endTime + " objectFormat: " + 
1351
                        objectFormat + " replicaStatus: " + replicaStatus + 
1352
                        " start: " + start + " count: " + count);
1353
               
1354
                ObjectList ol = MNodeService.getInstance().listObjects(session, startTime, endTime, 
1355
                        objectFormat, replicaStatus, start, count);
1356
                
1357
                StringReader sr = new StringReader(ol.toString());                
1358
                out = response.getOutputStream();  
1359
                response.setStatus(200);
1360
                response.setContentType("text/xml");
1361
                // Serialize and write it to the output stream
1362
                
1363
                try {
1364
                    serializeServiceType(ObjectList.class, ol, out);
1365
                } catch (JiBXException e) {
1366
                    throw new ServiceFailure("1190", "Failed to serialize ObjectList: " + e.getMessage());
1367
                }
1368
            }
1369
        } catch (BaseException e) {
1370
                response.setStatus(500);
1371
                serializeException(e, out);
1372
        } catch (IOException e) {
1373
            e.printStackTrace();
1374
            response.setStatus(500);
1375
            ServiceFailure sf = new ServiceFailure("1030", 
1376
                    "IO Error in D1ResourceHandler.getObject: " + e.getMessage());
1377
            serializeException(sf, out); 
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff