Project

General

Profile

1 6174 cjones
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000-2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author$'
7
 *     '$Date$'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23
24
package edu.ucsb.nceas.metacat.dataone;
25
26 6226 cjones
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30 6174 cjones
import java.io.InputStream;
31 6241 cjones
import java.io.OutputStream;
32 6226 cjones
import java.sql.SQLException;
33 6225 leinfelder
import java.util.ArrayList;
34 6186 leinfelder
import java.util.Calendar;
35 6174 cjones
import java.util.Date;
36 6226 cjones
import java.util.Hashtable;
37 6194 leinfelder
import java.util.List;
38 6226 cjones
import java.util.Timer;
39 6186 leinfelder
import java.util.Vector;
40 6174 cjones
41 6542 leinfelder
import javax.servlet.http.HttpServletRequest;
42 6226 cjones
43 6542 leinfelder
44 6241 cjones
import org.apache.commons.io.IOUtils;
45 6186 leinfelder
import org.apache.log4j.Logger;
46 6865 cjones
import org.dataone.client.CNode;
47
import org.dataone.client.D1Client;
48 6241 cjones
import org.dataone.client.ObjectFormatCache;
49 6371 leinfelder
import org.dataone.service.util.Constants;
50 6944 leinfelder
import org.dataone.service.util.DateTimeMarshaller;
51 6241 cjones
import org.dataone.service.exceptions.IdentifierNotUnique;
52
import org.dataone.service.exceptions.InsufficientResources;
53 6174 cjones
import org.dataone.service.exceptions.InvalidRequest;
54 6241 cjones
import org.dataone.service.exceptions.InvalidSystemMetadata;
55 6174 cjones
import org.dataone.service.exceptions.InvalidToken;
56
import org.dataone.service.exceptions.NotAuthorized;
57
import org.dataone.service.exceptions.NotFound;
58
import org.dataone.service.exceptions.NotImplemented;
59
import org.dataone.service.exceptions.ServiceFailure;
60 6241 cjones
import org.dataone.service.exceptions.UnsupportedType;
61 6366 leinfelder
import org.dataone.service.types.v1.AccessPolicy;
62
import org.dataone.service.types.v1.AccessRule;
63 6803 leinfelder
import org.dataone.service.types.v1.DescribeResponse;
64 6366 leinfelder
import org.dataone.service.types.v1.Event;
65
import org.dataone.service.types.v1.Identifier;
66
import org.dataone.service.types.v1.Group;
67
import org.dataone.service.types.v1.Log;
68
import org.dataone.service.types.v1.LogEntry;
69 6865 cjones
import org.dataone.service.types.v1.Node;
70 6366 leinfelder
import org.dataone.service.types.v1.NodeReference;
71 6865 cjones
import org.dataone.service.types.v1.NodeType;
72 6366 leinfelder
import org.dataone.service.types.v1.ObjectFormat;
73
import org.dataone.service.types.v1.Permission;
74
import org.dataone.service.types.v1.Person;
75
import org.dataone.service.types.v1.Session;
76
import org.dataone.service.types.v1.Subject;
77 6532 leinfelder
import org.dataone.service.types.v1.SubjectInfo;
78 6366 leinfelder
import org.dataone.service.types.v1.SubjectList;
79
import org.dataone.service.types.v1.SystemMetadata;
80 6445 leinfelder
import org.dataone.service.types.v1.util.ChecksumUtil;
81 6174 cjones
82 6241 cjones
import edu.ucsb.nceas.metacat.AccessionNumberException;
83
import edu.ucsb.nceas.metacat.DocumentImpl;
84 6186 leinfelder
import edu.ucsb.nceas.metacat.EventLog;
85
import edu.ucsb.nceas.metacat.IdentifierManager;
86 6194 leinfelder
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
87 6226 cjones
import edu.ucsb.nceas.metacat.MetacatHandler;
88 6803 leinfelder
import edu.ucsb.nceas.metacat.database.DBConnection;
89
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
90 6447 leinfelder
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
91 6226 cjones
import edu.ucsb.nceas.metacat.properties.PropertyService;
92 6241 cjones
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
93 6254 cjones
import edu.ucsb.nceas.metacat.util.SystemUtil;
94 6226 cjones
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
95 6186 leinfelder
96 6174 cjones
public abstract class D1NodeService {
97 6227 cjones
98 6226 cjones
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
99 6186 leinfelder
100 6542 leinfelder
  /** For logging the operations */
101
  protected HttpServletRequest request;
102 6241 cjones
103 6226 cjones
  /* reference to the metacat handler */
104 6389 leinfelder
  protected MetacatHandler handler;
105 6174 cjones
106 6226 cjones
  /* parameters set in the incoming request */
107
  private Hashtable<String, String[]> params;
108
109 6241 cjones
  /**
110
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
111
   *
112
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
113
   */
114 6542 leinfelder
  public D1NodeService(HttpServletRequest request) {
115
		this.request = request;
116
	}
117 6241 cjones
118
  /**
119 6803 leinfelder
   * This method provides a lighter weight mechanism than
120
   * getSystemMetadata() for a client to determine basic
121
   * properties of the referenced object.
122
   *
123
   * @param session - the Session object containing the credentials for the Subject
124
   * @param pid - the identifier of the object to be described
125
   *
126
   * @return describeResponse - A set of values providing a basic description
127
   *                            of the object.
128
   *
129
   * @throws InvalidToken
130
   * @throws ServiceFailure
131
   * @throws NotAuthorized
132
   * @throws NotFound
133
   * @throws NotImplemented
134
   * @throws InvalidRequest
135
   */
136
  public DescribeResponse describe(Session session, Identifier pid)
137
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
138
139
    // get system metadata and construct the describe response
140
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
141
      DescribeResponse describeResponse =
142
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(),
143
      			sysmeta.getDateSysMetadataModified(),
144
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
145
146
      return describeResponse;
147
148
  }
149
150
  /**
151
   * Low level, "are you alive" operation. A valid ping response is
152
   * indicated by a HTTP status of 200.
153
   *
154
   * @return true if the service is alive
155
   *
156
   * @throws NotImplemented
157
   * @throws ServiceFailure
158
   * @throws InsufficientResources
159
   */
160
  public Date ping()
161
      throws NotImplemented, ServiceFailure, InsufficientResources {
162
163
      // test if we can get a database connection
164
      int serialNumber = -1;
165
      DBConnection dbConn = null;
166
      try {
167
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
168
          serialNumber = dbConn.getCheckOutSerialNumber();
169
      } catch (SQLException e) {
170
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
171
      	sf.initCause(e);
172
          throw sf;
173
      } finally {
174
          // Return the database connection
175
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
176
      }
177
178
      return Calendar.getInstance().getTime();
179
  }
180
181
  /**
182 6241 cjones
   * Adds a new object to the Node, where the object is either a data
183
   * object or a science metadata object. This method is called by clients
184
   * to create new data objects on Member Nodes or internally for Coordinating
185
   * Nodes
186
   *
187
   * @param session - the Session object containing the credentials for the Subject
188
   * @param pid - The object identifier to be created
189
   * @param object - the object bytes
190
   * @param sysmeta - the system metadata that describes the object
191
   *
192
   * @return pid - the object identifier created
193
   *
194
   * @throws InvalidToken
195
   * @throws ServiceFailure
196
   * @throws NotAuthorized
197
   * @throws IdentifierNotUnique
198
   * @throws UnsupportedType
199
   * @throws InsufficientResources
200
   * @throws InvalidSystemMetadata
201
   * @throws NotImplemented
202
   * @throws InvalidRequest
203
   */
204
  public Identifier create(Session session, Identifier pid, InputStream object,
205
    SystemMetadata sysmeta)
206
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
207
    UnsupportedType, InsufficientResources, InvalidSystemMetadata,
208
    NotImplemented, InvalidRequest {
209 6174 cjones
210 6241 cjones
    Identifier resultPid = null;
211
    String localId = null;
212
    boolean allowed = false;
213
214 6530 leinfelder
    // check for null session
215
    if (session == null) {
216
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
217
    }
218
    Subject subject = session.getSubject();
219
220 6688 leinfelder
    Subject publicSubject = new Subject();
221
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
222
	// be sure the user is authenticated for create()
223 6518 leinfelder
    if (subject == null || subject.getValue() == null ||
224 6688 leinfelder
        subject.equals(publicSubject) ) {
225 6241 cjones
      throw new NotAuthorized("1100", "The provided identity does not have " +
226 6518 leinfelder
        "permission to WRITE to the Node.");
227 6241 cjones
228
    }
229
230
    // verify that pid == SystemMetadata.getIdentifier()
231
    logMetacat.debug("Comparing pid|sysmeta_pid: " +
232
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
233
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
234
        throw new InvalidSystemMetadata("1180",
235
            "The supplied system metadata is invalid. " +
236
            "The identifier " + pid.getValue() + " does not match identifier" +
237
            "in the system metadata identified by " +
238
            sysmeta.getIdentifier().getValue() + ".");
239
240
    }
241
242
    logMetacat.debug("Checking if identifier exists...");
243
    // Check that the identifier does not already exist
244 6278 leinfelder
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
245
	    	throw new IdentifierNotUnique("1120",
246
			          "The requested identifier " + pid.getValue() +
247
			          " is already used by another object and" +
248
			          "therefore can not be used for this object. Clients should choose" +
249
			          "a new identifier that is unique and retry the operation or " +
250 6518 leinfelder
			          "use CN.reserveIdentifier() to reserve one.");
251 6337 leinfelder
252 6241 cjones
    }
253 6518 leinfelder
254 6522 leinfelder
    // check that we are not attempting to subvert versioning
255
    if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
256
    	throw new InvalidSystemMetadata("1180",
257
    			"The supplied system metadata is invalid. " +
258
    			"The obsoletes field cannot have a value when creating entries.");
259
    }
260
    if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
261
    	throw new InvalidSystemMetadata("1180",
262
    			"The supplied system metadata is invalid. " +
263
    			"The obsoletedBy field cannot have a value when creating entries.");
264
	}
265
266 6596 leinfelder
    // TODO: this probably needs to be refined more
267 6241 cjones
    try {
268
      allowed = isAuthorized(session, pid, Permission.WRITE);
269
270
    } catch (NotFound e) {
271
      // The identifier doesn't exist, writing should be fine.
272
      allowed = true;
273
    }
274
275 6445 leinfelder
    // verify checksum, only if we can reset the inputstream
276
    if (object.markSupported()) {
277
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
278
	    String checksumValue = sysmeta.getChecksum().getValue();
279
	    try {
280
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
281
			// it's very important that we don't consume the stream
282
			object.reset();
283
			if (!computedChecksumValue.equals(checksumValue)) {
284
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
285
			}
286
		} catch (Exception e) {
287
			String msg = "Error verifying checksum values";
288
	      	logMetacat.error(msg, e);
289
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
290
		}
291
    } else {
292
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
293
    }
294
295 6241 cjones
    // we have the go ahead
296
    if ( allowed ) {
297
298
      // Science metadata (XML) or science data object?
299
      // TODO: there are cases where certain object formats are science metadata
300
      // but are not XML (netCDF ...).  Handle this.
301
      if ( isScienceMetadata(sysmeta) ) {
302
303
        // CASE METADATA:
304
      	String objectAsXML = "";
305
        try {
306
	        objectAsXML = IOUtils.toString(object, "UTF-8");
307
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
308
	        //localId = im.getLocalId(pid.getValue());
309
310
        } catch (IOException e) {
311
        	String msg = "The Node is unable to create the object. " +
312
          "There was a problem converting the object to XML";
313
        	logMetacat.info(msg);
314
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
315
316
        }
317
318 6302 leinfelder
      } else {
319
320
	      // DEFAULT CASE: DATA (needs to be checked and completed)
321
	      localId = insertDataObject(object, pid, session);
322
      }
323
324 6241 cjones
    }
325 6313 leinfelder
326
    // save the sysmeta
327 6468 leinfelder
    try {
328 6572 cjones
      // lock and unlock of the pid happens in the subclass
329 6468 leinfelder
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
330 6572 cjones
331 6468 leinfelder
    } catch (Exception e) {
332 6495 leinfelder
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
333 6468 leinfelder
        throw new ServiceFailure("1190", e.getMessage());
334
	}
335 6302 leinfelder
336 6241 cjones
    // setting the resulting identifier failed
337 6302 leinfelder
    if (localId == null ) {
338
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
339 6241 cjones
    }
340 6313 leinfelder
341 6302 leinfelder
    resultPid = pid;
342
343 6241 cjones
    return resultPid;
344
  }
345
346 6227 cjones
  /**
347
   * Return the log records associated with a given event between the start and
348
   * end dates listed given a particular Subject listed in the Session
349
   *
350
   * @param session - the Session object containing the credentials for the Subject
351
   * @param fromDate - the start date of the desired log records
352
   * @param toDate - the end date of the desired log records
353
   * @param event - restrict log records of a specific event type
354
   * @param start - zero based offset from the first record in the
355
   *                set of matching log records. Used to assist with
356
   *                paging the response.
357
   * @param count - maximum number of log records to return in the response.
358
   *                Used to assist with paging the response.
359
   *
360
   * @return the desired log records
361
   *
362
   * @throws InvalidToken
363
   * @throws ServiceFailure
364
   * @throws NotAuthorized
365
   * @throws InvalidRequest
366
   * @throws NotImplemented
367
   */
368
  public Log getLogRecords(Session session, Date fromDate, Date toDate,
369 6179 cjones
      Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
370 6227 cjones
      NotAuthorized, InvalidRequest, NotImplemented {
371 6174 cjones
372 6186 leinfelder
373 6227 cjones
    Log log = new Log();
374 6321 leinfelder
    List<LogEntry> logs = new Vector<LogEntry>();
375 6227 cjones
    IdentifierManager im = IdentifierManager.getInstance();
376
    EventLog el = EventLog.getInstance();
377 6353 cjones
    if ( fromDate == null ) {
378 6227 cjones
      logMetacat.debug("setting fromdate from null");
379
      fromDate = new Date(1);
380
    }
381 6353 cjones
    if ( toDate == null ) {
382 6227 cjones
      logMetacat.debug("setting todate from null");
383
      toDate = new Date();
384
    }
385 6186 leinfelder
386 6353 cjones
    if ( start == null ) {
387
    	start = 0;
388
389
    }
390
391
    if ( count == null ) {
392
    	count = 1000;
393
394
    }
395
396 6227 cjones
    logMetacat.debug("fromDate: " + fromDate);
397
    logMetacat.debug("toDate: " + toDate);
398 6186 leinfelder
399 6227 cjones
    String report = el.getReport(null, null, null, null,
400
        new java.sql.Timestamp(fromDate.getTime()),
401
        new java.sql.Timestamp(toDate.getTime()), false);
402 6186 leinfelder
403 6227 cjones
    logMetacat.debug("report: " + report);
404 6186 leinfelder
405 6227 cjones
    String logEntry = "<logEntry>";
406
    String endLogEntry = "</logEntry>";
407
    int startIndex = 0;
408
    int foundIndex = report.indexOf(logEntry, startIndex);
409
    while (foundIndex != -1) {
410
      // parse out each entry
411
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
412
      String entry = report.substring(foundIndex, endEntryIndex);
413
      logMetacat.debug("entry: " + entry);
414
      startIndex = endEntryIndex + endLogEntry.length();
415
      foundIndex = report.indexOf(logEntry, startIndex);
416 6186 leinfelder
417 6227 cjones
      String entryId = getLogEntryField("entryid", entry);
418
      String ipAddress = getLogEntryField("ipAddress", entry);
419
      String principal = getLogEntryField("principal", entry);
420 6542 leinfelder
      String userAgent = getLogEntryField("userAgent", entry);
421 6227 cjones
      String docid = getLogEntryField("docid", entry);
422
      String eventS = getLogEntryField("event", entry);
423
      String dateLogged = getLogEntryField("dateLogged", entry);
424 6186 leinfelder
425 6227 cjones
      LogEntry le = new LogEntry();
426 6186 leinfelder
427 6227 cjones
      Event e = Event.convert(eventS);
428
      if (e == null) { // skip any events that are not Dataone Crud events
429
        continue;
430
      }
431
      le.setEvent(e);
432 6754 leinfelder
      le.setEntryId(entryId);
433 6227 cjones
      Identifier identifier = new Identifier();
434
      try {
435 6241 cjones
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
436 6227 cjones
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
437
          continue;
438
        }
439
        docid = docid.substring(0, docid.lastIndexOf("."));
440
        identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
441
      } catch (Exception ex) {
442 6241 cjones
        // try to get the pid, if that doesn't
443 6227 cjones
        // work, just use the local id
444
        // throw new ServiceFailure("1030",
445 6241 cjones
        // "Error getting pid for localId " +
446 6227 cjones
        // docid + ": " + ex.getMessage());\
447 6186 leinfelder
448 6241 cjones
        // skip it if the pid can't be found
449 6227 cjones
        continue;
450
      }
451 6186 leinfelder
452 6227 cjones
      le.setIdentifier(identifier);
453
      le.setIpAddress(ipAddress);
454 6944 leinfelder
      Date logDate = DateTimeMarshaller.deserializeDateToUTC(dateLogged);
455 6227 cjones
      le.setDateLogged(logDate);
456
      NodeReference memberNode = new NodeReference();
457
      memberNode.setValue(ipAddress);
458 6754 leinfelder
      le.setNodeIdentifier(memberNode);
459 6227 cjones
      Subject princ = new Subject();
460
      princ.setValue(principal);
461
      le.setSubject(princ);
462 6542 leinfelder
      le.setUserAgent(userAgent);
463 6186 leinfelder
464 6321 leinfelder
      // event filtering?
465 6227 cjones
      if (event == null) {
466 6321 leinfelder
    	  logs.add(le);
467
      } else if (le.getEvent().equals(event)) {
468
    	  logs.add(le);
469 6227 cjones
      }
470
    }
471 6321 leinfelder
472
    // d1 paging
473
    int total = logs.size();
474
    if (start != null && count != null) {
475
    	int toIndex = start + count;
476
    	if (toIndex <= total) {
477
    		logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
478
    	}
479
    }
480 6186 leinfelder
481 6227 cjones
    log.setLogEntryList(logs);
482 6321 leinfelder
    log.setStart(start);
483
    log.setCount(logs.size());
484
    log.setTotal(total);
485 6227 cjones
    logMetacat.info("getLogRecords");
486
    return log;
487
  }
488 6241 cjones
489 6227 cjones
  /**
490
   * Return the object identified by the given object identifier
491
   *
492
   * @param session - the Session object containing the credentials for the Subject
493
   * @param pid - the object identifier for the given object
494
   *
495
   * TODO: The D1 Authorization API doesn't provide information on which
496
   * authentication system the Subject belongs to, and so it's not possible to
497
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
498
   *
499
   * @return inputStream - the input stream of the given object
500
   *
501
   * @throws InvalidToken
502
   * @throws ServiceFailure
503
   * @throws NotAuthorized
504
   * @throws InvalidRequest
505
   * @throws NotImplemented
506
   */
507
  public InputStream get(Session session, Identifier pid)
508
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
509 6609 cjones
    NotImplemented {
510 6226 cjones
511 6227 cjones
    InputStream inputStream = null; // bytes to be returned
512 6226 cjones
    handler = new MetacatHandler(new Timer());
513 6227 cjones
    boolean allowed = false;
514
    String localId; // the metacat docid for the pid
515 6226 cjones
516 6227 cjones
    // get the local docid from Metacat
517
    try {
518
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
519
520 6226 cjones
    } catch (McdbDocNotFoundException e) {
521
      throw new NotFound("1020", "The object specified by " +
522 6227 cjones
                         pid.getValue() +
523 6283 leinfelder
                         " does not exist at this node.");
524 6226 cjones
    }
525
526
    // check for authorization
527 6227 cjones
    allowed = isAuthorized(session, pid, Permission.READ);
528
529
    // if the person is authorized, perform the read
530 6323 leinfelder
    if (allowed) {
531 6226 cjones
      try {
532 6323 leinfelder
        inputStream = handler.read(localId);
533
      } catch (Exception e) {
534 6226 cjones
        throw new ServiceFailure("1020", "The object specified by " +
535
            pid.getValue() +
536 6323 leinfelder
            "could not be returned due to error: " +
537 6226 cjones
            e.getMessage());
538
      }
539 6227 cjones
    }
540 6226 cjones
541 6227 cjones
    // if we fail to set the input stream
542
    if ( inputStream == null ) {
543 6226 cjones
      throw new NotFound("1020", "The object specified by " +
544
                         pid.getValue() +
545
                         "does not exist at this node.");
546 6227 cjones
    }
547
548 6389 leinfelder
	// log the read event
549 6532 leinfelder
    String principal = Constants.SUBJECT_PUBLIC;
550 6421 leinfelder
    if (session != null && session.getSubject() != null) {
551 6389 leinfelder
    	principal = session.getSubject().getValue();
552
    }
553 6542 leinfelder
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
554 6389 leinfelder
555 6227 cjones
    return inputStream;
556
  }
557 6174 cjones
558 6227 cjones
  /**
559
   * Return the system metadata for a given object
560
   *
561
   * @param session - the Session object containing the credentials for the Subject
562
   * @param pid - the object identifier for the given object
563
   *
564
   * @return inputStream - the input stream of the given system metadata object
565
   *
566
   * @throws InvalidToken
567
   * @throws ServiceFailure
568
   * @throws NotAuthorized
569
   * @throws NotFound
570
   * @throws InvalidRequest
571
   * @throws NotImplemented
572
   */
573
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
574 6572 cjones
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
575 6609 cjones
      NotImplemented {
576 6572 cjones
577
      if (!isAuthorized(session, pid, Permission.READ)) {
578
        throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());
579
      }
580
      SystemMetadata systemMetadata = null;
581
      try {
582
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
583
584
      } catch (Exception e) {
585
        // convert hazelcast RuntimeException to NotFound
586
        throw new NotFound("1420", "No record found for: " + pid.getValue());
587
588
      }
589 6227 cjones
590
    return systemMetadata;
591 6174 cjones
  }
592 6572 cjones
593 6227 cjones
  /**
594 6865 cjones
   * Test if the user identified by the provided token has administrative authorization
595
   * for the operation on the specified object.
596
   *
597
   * @param session - the Session object containing the credentials for the Subject
598
   * @param pid - The identifer of the resource for which access is being checked
599
   * @param operation - The type of operation which is being requested for the given pid
600
   *
601
   * @return true if the operation is allowed
602
   *
603
   * @throws ServiceFailure
604
   * @throws InvalidToken
605
   * @throws NotFound
606
   * @throws NotAuthorized
607
   * @throws NotImplemented
608
   */
609
  protected boolean isAdminAuthorized(Session session, Identifier pid,
610
      Permission permission)
611
      throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
612
      NotImplemented {
613
614
      boolean allowed = false;
615
      // are we allowed to do this? only CNs and target MNs are allowed
616
      CNode cn = D1Client.getCN();
617
      List<Node> nodes = cn.listNodes().getNodeList();
618
619
      if ( nodes == null ) {
620
          throw new ServiceFailure("4852", "Couldn't get node list.");
621
622
      }
623
624
      // find the node in the node list
625
      for ( Node node : nodes ) {
626
627
          NodeReference nodeReference = node.getIdentifier();
628
          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
629
630
          Subject subject = session.getSubject();
631
632
          if (node.getType() == NodeType.CN) {
633
              List<Subject> nodeSubjects = node.getSubjectList();
634
635
              // check if the session subject is in the node subject list
636
              for (Subject nodeSubject : nodeSubjects) {
637
                  if ( nodeSubject.equals(subject) ) {
638
                      allowed = true; // subject of session == target node subject
639
                      break;
640
641
                  }
642 6874 cjones
              }
643 6865 cjones
          }
644
      }
645
646
647
      return allowed;
648
  }
649
650
  /**
651 6227 cjones
   * Test if the user identified by the provided token has authorization
652 6865 cjones
   * for the operation on the specified object.
653 6227 cjones
   *
654
   * @param session - the Session object containing the credentials for the Subject
655
   * @param pid - The identifer of the resource for which access is being checked
656
   * @param operation - The type of operation which is being requested for the given pid
657
   *
658
   * @return true if the operation is allowed
659
   *
660
   * @throws ServiceFailure
661
   * @throws InvalidToken
662
   * @throws NotFound
663
   * @throws NotAuthorized
664
   * @throws NotImplemented
665
   * @throws InvalidRequest
666
   */
667
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
668
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
669 6609 cjones
    NotImplemented {
670 6174 cjones
671 6227 cjones
    boolean allowed = false;
672
673 6816 leinfelder
    // permissions are hierarchical
674 6830 leinfelder
    List<Permission> expandedPermissions = null;
675 6816 leinfelder
676
    // for the "Verified" symbolic user
677
    Subject verifiedSubject = new Subject();
678
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
679
680 6227 cjones
    // get the subjects from the session
681
    List<Subject> subjects = new ArrayList<Subject>();
682 6412 leinfelder
    if (session != null) {
683
	    Subject subject = session.getSubject();
684
	    if (subject != null) {
685
	    	subjects.add(subject);
686
	    }
687 6664 leinfelder
	    SubjectInfo subjectInfo = session.getSubjectInfo();
688
	    if (subjectInfo != null) {
689 6816 leinfelder
	    	// add the equivalent identities
690 6664 leinfelder
	    	List<Person> personList = subjectInfo.getPersonList();
691 6412 leinfelder
	    	if (personList != null) {
692
			    for (Person p: personList) {
693
			      subjects.add(p.getSubject());
694 6664 leinfelder
			      if (p.getVerified()) {
695
			    	  // add the verified symbolic user
696
			    	  if (!subjects.contains(verifiedSubject)) {
697
			    		  subjects.add(verifiedSubject);
698
			    	  }
699
			      }
700 6412 leinfelder
			    }
701
	    	}
702 6816 leinfelder
	    	// add the groups
703 6664 leinfelder
	    	List<Group> groupList = subjectInfo.getGroupList();
704 6412 leinfelder
	    	if (groupList != null) {
705
			    for (Group g: groupList) {
706
			      subjects.add(g.getSubject());
707
			    }
708
	    	}
709
	    }
710 6664 leinfelder
	    // add the authenticated symbolic as a check
711
	    Subject authenticatedSubject = new Subject();
712
	    authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
713
	    subjects.add(authenticatedSubject);
714
715 6227 cjones
    }
716
717 6293 leinfelder
    // add public subject
718
    Subject publicSubject = new Subject();
719 6532 leinfelder
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
720 6293 leinfelder
    subjects.add(publicSubject);
721
722 6227 cjones
    // get the system metadata
723 6241 cjones
    String pidStr = pid.getValue();
724 6227 cjones
    SystemMetadata systemMetadata = null;
725
    try {
726 6574 cjones
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
727
728
    } catch (Exception e) {
729
        // convert Hazelcast RuntimeException to NotFound
730
        logMetacat.error("An error occurred while getting system metadata for identifier " +
731
            pid.getValue() + ". The error message was: " + e.getMessage());
732
        throw new NotFound("1800", "No record found for " + pidStr);
733
734 6858 cjones
    }
735 6596 leinfelder
736
    // throw not found if it was not found
737
    if (systemMetadata == null) {
738 6652 leinfelder
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
739 6596 leinfelder
    }
740 6245 leinfelder
741 6293 leinfelder
    // do we own it?
742
    for (Subject s: subjects) {
743 6688 leinfelder
    	allowed = systemMetadata.getRightsHolder().equals(s);
744 6293 leinfelder
    	if (allowed) {
745
    		return allowed;
746
    	}
747
    }
748
749
    // otherwise check the access rules
750 6245 leinfelder
    try {
751
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
752 6293 leinfelder
	    search: // label break
753 6245 leinfelder
	    for (AccessRule accessRule: allows) {
754
	      for (Subject s: subjects) {
755 6816 leinfelder
	        if (accessRule.getSubjectList().contains(s)) {
756 6830 leinfelder
	        	for (Permission p: accessRule.getPermissionList()) {
757
	        		expandedPermissions = expandPermissions(p);
758
	        		allowed = expandedPermissions.contains(permission);
759
	        		if (allowed) {
760
	        			break search; //label break
761
	        		}
762 6816 leinfelder
	        	}
763
764 6245 leinfelder
	        }
765
	      }
766
	    }
767
    } catch (Exception e) {
768
    	// catch all for errors - safe side should be to deny the access
769
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
770
		allowed = false;
771
	}
772 6227 cjones
773 6245 leinfelder
    // throw or return?
774 6227 cjones
    if (!allowed) {
775 6245 leinfelder
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
776 6227 cjones
    }
777 6245 leinfelder
778 6227 cjones
    return allowed;
779 6241 cjones
780 6227 cjones
  }
781
782 6256 cjones
  /*
783 6227 cjones
   * parse a logEntry and get the relevant field from it
784
   *
785
   * @param fieldname
786
   * @param entry
787
   * @return
788
   */
789
  private String getLogEntryField(String fieldname, String entry) {
790
    String begin = "<" + fieldname + ">";
791
    String end = "</" + fieldname + ">";
792
    // logMetacat.debug("looking for " + begin + " and " + end +
793
    // " in entry " + entry);
794
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
795
        .indexOf(end));
796
    logMetacat.debug("entry " + fieldname + " : " + s);
797
    return s;
798
  }
799 6174 cjones
800 6257 cjones
  /**
801 6241 cjones
   * Determine if a given object should be treated as an XML science metadata
802
   * object.
803
   *
804
   * @param sysmeta - the SystemMetadata describing the object
805
   * @return true if the object should be treated as science metadata
806
   */
807 6433 leinfelder
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
808 6241 cjones
809
    ObjectFormat objectFormat = null;
810
    boolean isScienceMetadata = false;
811
812
    try {
813 6561 leinfelder
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
814 6433 leinfelder
      if ( objectFormat.getFormatType().equals("METADATA") ) {
815 6402 cjones
      	isScienceMetadata = true;
816
817
      }
818 6241 cjones
819
    } catch (InvalidRequest e) {
820
       logMetacat.debug("There was a problem determining if the object identified by" +
821
         sysmeta.getIdentifier().getValue() +
822
         " is science metadata: " + e.getMessage());
823
824
    } catch (ServiceFailure e) {
825
      logMetacat.debug("There was a problem determining if the object identified by" +
826
          sysmeta.getIdentifier().getValue() +
827
          " is science metadata: " + e.getMessage());
828
829
    } catch (NotFound e) {
830
      logMetacat.debug("There was a problem determining if the object identified by" +
831
          sysmeta.getIdentifier().getValue() +
832
          " is science metadata: " + e.getMessage());
833
834
    } catch (InsufficientResources e) {
835
      logMetacat.debug("There was a problem determining if the object identified by" +
836
          sysmeta.getIdentifier().getValue() +
837
          " is science metadata: " + e.getMessage());
838
839
    } catch (NotImplemented e) {
840
      logMetacat.debug("There was a problem determining if the object identified by" +
841
          sysmeta.getIdentifier().getValue() +
842
          " is science metadata: " + e.getMessage());
843
844
    }
845
846
    return isScienceMetadata;
847 6226 cjones
848 6241 cjones
  }
849
850
  /**
851
   * Insert or update an XML document into Metacat
852
   *
853
   * @param xml - the XML document to insert or update
854
   * @param pid - the identifier to be used for the resulting object
855
   *
856
   * @return localId - the resulting docid of the document created or updated
857
   *
858
   */
859 6807 leinfelder
  public String insertOrUpdateDocument(String xml, Identifier pid,
860 6241 cjones
    Session session, String insertOrUpdate)
861
    throws ServiceFailure {
862
863
  	logMetacat.debug("Starting to insert xml document...");
864
    IdentifierManager im = IdentifierManager.getInstance();
865
866
    // generate pid/localId pair for sysmeta
867
    String localId = null;
868
869
    if(insertOrUpdate.equals("insert")) {
870
      localId = im.generateLocalId(pid.getValue(), 1);
871
872
    } else {
873
      //localid should already exist in the identifier table, so just find it
874
      try {
875
        logMetacat.debug("Updating pid " + pid.getValue());
876
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
877
878
        localId = im.getLocalId(pid.getValue());
879
880
        logMetacat.debug("localId: " + localId);
881
        //increment the revision
882
        String docid = localId.substring(0, localId.lastIndexOf("."));
883
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
884
        int rev = new Integer(revS).intValue();
885
        rev++;
886
        docid = docid + "." + rev;
887
        localId = docid;
888
        logMetacat.debug("incremented localId: " + localId);
889
890
      } catch(McdbDocNotFoundException e) {
891
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
892
            "pid " + pid.getValue() +
893
            " should have been in the identifier table, but it wasn't: " +
894
            e.getMessage());
895
896
      }
897
898
    }
899
900 6443 leinfelder
    params = new Hashtable<String, String[]>();
901 6241 cjones
    String[] action = new String[1];
902
    action[0] = insertOrUpdate;
903
    params.put("action", action);
904
    String[] docid = new String[1];
905
    docid[0] = localId;
906
    params.put("docid", docid);
907
    String[] doctext = new String[1];
908
    doctext[0] = xml;
909
    params.put("doctext", doctext);
910
911 6532 leinfelder
    String username = Constants.SUBJECT_PUBLIC;
912 6241 cjones
    String[] groupnames = null;
913 6302 leinfelder
    if (session != null ) {
914
    	username = session.getSubject().getValue();
915 6532 leinfelder
    	if (session.getSubjectInfo() != null) {
916
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
917 6302 leinfelder
    		if (groupList != null) {
918
    			groupnames = new String[groupList.size()];
919
    			for (int i = 0; i > groupList.size(); i++ ) {
920
    				groupnames[i] = groupList.get(i).getGroupName();
921
    			}
922
    		}
923
    	}
924 6241 cjones
    }
925
926
    // do the insert or update action
927 6443 leinfelder
    handler = new MetacatHandler(new Timer());
928 6542 leinfelder
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null,
929 6241 cjones
                        null, params, username, groupnames);
930
931
    if(result.indexOf("<error>") != -1) {
932
    	String detailCode = "";
933
    	if ( insertOrUpdate.equals("insert") ) {
934
    		detailCode = "1190";
935
936
    	} else if ( insertOrUpdate.equals("update") ) {
937
    		detailCode = "1310";
938
939
    	}
940
        throw new ServiceFailure(detailCode,
941
          "Error inserting or updating document: " + result);
942
    }
943
    logMetacat.debug("Finsished inserting xml document with id " + localId);
944
945
    return localId;
946
  }
947
948
  /**
949
   * Insert a data document
950
   *
951
   * @param object
952
   * @param pid
953
   * @param sessionData
954
   * @throws ServiceFailure
955
   * @returns localId of the data object inserted
956
   */
957 6807 leinfelder
  public String insertDataObject(InputStream object, Identifier pid,
958 6241 cjones
          Session session) throws ServiceFailure {
959
960 6532 leinfelder
    String username = Constants.SUBJECT_PUBLIC;
961 6241 cjones
    String[] groupnames = null;
962 6302 leinfelder
    if (session != null ) {
963
    	username = session.getSubject().getValue();
964 6532 leinfelder
    	if (session.getSubjectInfo() != null) {
965
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
966 6302 leinfelder
    		if (groupList != null) {
967
    			groupnames = new String[groupList.size()];
968
    			for (int i = 0; i > groupList.size(); i++ ) {
969
    				groupnames[i] = groupList.get(i).getGroupName();
970
    			}
971
    		}
972
    	}
973 6241 cjones
    }
974
975
    // generate pid/localId pair for object
976
    logMetacat.debug("Generating a pid/localId mapping");
977
    IdentifierManager im = IdentifierManager.getInstance();
978
    String localId = im.generateLocalId(pid.getValue(), 1);
979 6719 leinfelder
980
    // Save the data file to disk using "localId" as the name
981
    String datafilepath = null;
982
	try {
983
		datafilepath = PropertyService.getProperty("application.datafilepath");
984
	} catch (PropertyNotFoundException e) {
985
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
986
		sf.initCause(e);
987
		throw sf;
988
	}
989
    boolean locked = false;
990
	try {
991
		locked = DocumentImpl.getDataFileLockGrant(localId);
992
	} catch (Exception e) {
993
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
994
		sf.initCause(e);
995
		throw sf;
996
	}
997
998
    logMetacat.debug("Case DATA: starting to write to disk.");
999
	if (locked) {
1000
1001 6241 cjones
          File dataDirectory = new File(datafilepath);
1002
          dataDirectory.mkdirs();
1003
1004
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1005
1006
          // TODO: Check that the file size matches SystemMetadata
1007
          // long size = newFile.length();
1008
          // if (size == 0) {
1009
          //     throw new IOException("Uploaded file is 0 bytes!");
1010
          // }
1011
1012
          // Register the file in the database (which generates an exception
1013
          // if the localId is not acceptable or other untoward things happen
1014
          try {
1015
            logMetacat.debug("Registering document...");
1016
            DocumentImpl.registerDocument(localId, "BIN", localId,
1017
                    username, groupnames);
1018
            logMetacat.debug("Registration step completed.");
1019
1020
          } catch (SQLException e) {
1021
            //newFile.delete();
1022
            logMetacat.debug("SQLE: " + e.getMessage());
1023
            e.printStackTrace(System.out);
1024
            throw new ServiceFailure("1190", "Registration failed: " +
1025
            		e.getMessage());
1026
1027
          } catch (AccessionNumberException e) {
1028
            //newFile.delete();
1029
            logMetacat.debug("ANE: " + e.getMessage());
1030
            e.printStackTrace(System.out);
1031
            throw new ServiceFailure("1190", "Registration failed: " +
1032
            	e.getMessage());
1033
1034
          } catch (Exception e) {
1035
            //newFile.delete();
1036
            logMetacat.debug("Exception: " + e.getMessage());
1037
            e.printStackTrace(System.out);
1038
            throw new ServiceFailure("1190", "Registration failed: " +
1039
            	e.getMessage());
1040
          }
1041
1042
          logMetacat.debug("Logging the creation event.");
1043 6542 leinfelder
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1044 6241 cjones
1045
          // Schedule replication for this data file
1046
          logMetacat.debug("Scheduling replication.");
1047
          ForceReplicationHandler frh = new ForceReplicationHandler(
1048
            localId, "create", false, null);
1049 6719 leinfelder
      }
1050
1051
      return localId;
1052 6241 cjones
1053
  }
1054 6255 cjones
1055 6256 cjones
  /**
1056
   * Insert a systemMetadata document and return its localId
1057
   */
1058 6807 leinfelder
  public void insertSystemMetadata(SystemMetadata sysmeta)
1059 6572 cjones
      throws ServiceFailure {
1060
1061
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1062
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1063
      logMetacat.debug("Inserting new system metadata with modified date " +
1064
          sysmeta.getDateSysMetadataModified());
1065
1066
      //insert the system metadata
1067
      try {
1068
        // note: the calling subclass handles the map hazelcast lock/unlock
1069
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1070
1071
      } catch (Exception e) {
1072
          throw new ServiceFailure("1190", e.getMessage());
1073
1074
	    }
1075 6256 cjones
  }
1076
1077
  /**
1078 6255 cjones
   * Update a systemMetadata document
1079
   *
1080
   * @param sysMeta - the system metadata object in the system to update
1081
   */
1082 6858 cjones
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1083
        throws ServiceFailure {
1084
1085
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1086
        sysMeta.setDateSysMetadataModified(new Date());
1087
        try {
1088
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1089
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1090
1091
        } catch (Exception e) {
1092
            throw new ServiceFailure("4862", e.getMessage());
1093
1094
        } finally {
1095
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1096
1097
        }
1098
1099
    }
1100 6816 leinfelder
1101
  /**
1102
   * Given a Permission, returns a list of all permissions that it encompasses
1103
   * Permissions are hierarchical so that WRITE also allows READ.
1104
   * @param permission
1105
   * @return list of included Permissions for the given permission
1106
   */
1107
  protected List<Permission> expandPermissions(Permission permission) {
1108
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1109
	    if (permission.equals(Permission.READ)) {
1110
	    	expandedPermissions.add(Permission.READ);
1111
	    }
1112
	    if (permission.equals(Permission.WRITE)) {
1113
	    	expandedPermissions.add(Permission.READ);
1114
	    	expandedPermissions.add(Permission.WRITE);
1115
	    }
1116
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1117
	    	expandedPermissions.add(Permission.READ);
1118
	    	expandedPermissions.add(Permission.WRITE);
1119
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1120
	    }
1121
	    return expandedPermissions;
1122
  }
1123 6255 cjones
1124
  /*
1125 6241 cjones
   * Write a stream to a file
1126
   *
1127
   * @param dir - the directory to write to
1128
   * @param fileName - the file name to write to
1129
   * @param data - the object bytes as an input stream
1130
   *
1131
   * @return newFile - the new file created
1132
   *
1133
   * @throws ServiceFailure
1134
   */
1135
  private File writeStreamToFile(File dir, String fileName, InputStream data)
1136
    throws ServiceFailure {
1137
1138
    File newFile = new File(dir, fileName);
1139
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1140
1141
    try {
1142
        if (newFile.createNewFile()) {
1143
          // write data stream to desired file
1144
          OutputStream os = new FileOutputStream(newFile);
1145
          long length = IOUtils.copyLarge(data, os);
1146
          os.flush();
1147
          os.close();
1148
        } else {
1149
          logMetacat.debug("File creation failed, or file already exists.");
1150
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1151
        }
1152
    } catch (FileNotFoundException e) {
1153
      logMetacat.debug("FNF: " + e.getMessage());
1154
      throw new ServiceFailure("1190", "File not found: " + fileName + " "
1155
                + e.getMessage());
1156
    } catch (IOException e) {
1157
      logMetacat.debug("IOE: " + e.getMessage());
1158
      throw new ServiceFailure("1190", "File was not written: " + fileName
1159
                + " " + e.getMessage());
1160
    }
1161
1162
    return newFile;
1163
  }
1164
1165
}