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