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
        HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
585
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
586
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
587
588
      } catch (Exception e) {
589
        // convert hazelcast RuntimeException to NotFound
590
        throw new NotFound("1420", "No record found for: " + pid.getValue());
591
592
      }
593 6227 cjones
594
    return systemMetadata;
595 6174 cjones
  }
596 6572 cjones
597 6227 cjones
  /**
598
   * Test if the user identified by the provided token has authorization
599
   * for operation on the specified object.
600
   *
601
   * @param session - the Session object containing the credentials for the Subject
602
   * @param pid - The identifer of the resource for which access is being checked
603
   * @param operation - The type of operation which is being requested for the given pid
604
   *
605
   * @return true if the operation is allowed
606
   *
607
   * @throws ServiceFailure
608
   * @throws InvalidToken
609
   * @throws NotFound
610
   * @throws NotAuthorized
611
   * @throws NotImplemented
612
   * @throws InvalidRequest
613
   */
614
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
615
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
616 6609 cjones
    NotImplemented {
617 6174 cjones
618 6227 cjones
    boolean allowed = false;
619
620 6816 leinfelder
    // permissions are hierarchical
621
    List<Permission> expandedPermissions = expandPermissions(permission);
622
623
    // for the "Verified" symbolic user
624
    Subject verifiedSubject = new Subject();
625
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
626
627 6227 cjones
    // get the subjects from the session
628
    List<Subject> subjects = new ArrayList<Subject>();
629 6412 leinfelder
    if (session != null) {
630
	    Subject subject = session.getSubject();
631
	    if (subject != null) {
632
	    	subjects.add(subject);
633
	    }
634 6664 leinfelder
	    SubjectInfo subjectInfo = session.getSubjectInfo();
635
	    if (subjectInfo != null) {
636 6816 leinfelder
	    	// add the equivalent identities
637 6664 leinfelder
	    	List<Person> personList = subjectInfo.getPersonList();
638 6412 leinfelder
	    	if (personList != null) {
639
			    for (Person p: personList) {
640
			      subjects.add(p.getSubject());
641 6664 leinfelder
			      if (p.getVerified()) {
642
			    	  // add the verified symbolic user
643
			    	  if (!subjects.contains(verifiedSubject)) {
644
			    		  subjects.add(verifiedSubject);
645
			    	  }
646
			      }
647 6412 leinfelder
			    }
648
	    	}
649 6816 leinfelder
	    	// add the groups
650 6664 leinfelder
	    	List<Group> groupList = subjectInfo.getGroupList();
651 6412 leinfelder
	    	if (groupList != null) {
652
			    for (Group g: groupList) {
653
			      subjects.add(g.getSubject());
654
			    }
655
	    	}
656
	    }
657 6664 leinfelder
	    // add the authenticated symbolic as a check
658
	    Subject authenticatedSubject = new Subject();
659
	    authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
660
	    subjects.add(authenticatedSubject);
661
662 6227 cjones
    }
663
664 6293 leinfelder
    // add public subject
665
    Subject publicSubject = new Subject();
666 6532 leinfelder
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
667 6293 leinfelder
    subjects.add(publicSubject);
668
669 6227 cjones
    // get the system metadata
670 6241 cjones
    String pidStr = pid.getValue();
671 6227 cjones
    SystemMetadata systemMetadata = null;
672
    try {
673 6574 cjones
        HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
674
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
675
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
676
677
    } catch (Exception e) {
678
        // convert Hazelcast RuntimeException to NotFound
679
        logMetacat.error("An error occurred while getting system metadata for identifier " +
680
            pid.getValue() + ". The error message was: " + e.getMessage());
681
        throw new NotFound("1800", "No record found for " + pidStr);
682
683
    } finally {
684
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
685
686 6227 cjones
    }
687 6596 leinfelder
688
    // throw not found if it was not found
689
    if (systemMetadata == null) {
690 6652 leinfelder
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
691 6596 leinfelder
    }
692 6245 leinfelder
693 6293 leinfelder
    // do we own it?
694
    for (Subject s: subjects) {
695 6688 leinfelder
    	allowed = systemMetadata.getRightsHolder().equals(s);
696 6293 leinfelder
    	if (allowed) {
697
    		return allowed;
698
    	}
699
    }
700
701
    // otherwise check the access rules
702 6245 leinfelder
    try {
703
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
704 6293 leinfelder
	    search: // label break
705 6245 leinfelder
	    for (AccessRule accessRule: allows) {
706
	      for (Subject s: subjects) {
707 6816 leinfelder
	        if (accessRule.getSubjectList().contains(s)) {
708
	        	for (Permission p: expandedPermissions) {
709
		          allowed = accessRule.getPermissionList().contains(p);
710 6293 leinfelder
		          if (allowed) {
711
		        	  break search; //label break
712
		          }
713 6816 leinfelder
	        	}
714
715 6245 leinfelder
	        }
716
	      }
717
	    }
718
    } catch (Exception e) {
719
    	// catch all for errors - safe side should be to deny the access
720
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
721
		allowed = false;
722
	}
723 6227 cjones
724 6245 leinfelder
    // throw or return?
725 6227 cjones
    if (!allowed) {
726 6245 leinfelder
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
727 6227 cjones
    }
728 6245 leinfelder
729 6227 cjones
    return allowed;
730 6241 cjones
731 6227 cjones
  }
732
733 6256 cjones
  /*
734 6227 cjones
   * parse a logEntry and get the relevant field from it
735
   *
736
   * @param fieldname
737
   * @param entry
738
   * @return
739
   */
740
  private String getLogEntryField(String fieldname, String entry) {
741
    String begin = "<" + fieldname + ">";
742
    String end = "</" + fieldname + ">";
743
    // logMetacat.debug("looking for " + begin + " and " + end +
744
    // " in entry " + entry);
745
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
746
        .indexOf(end));
747
    logMetacat.debug("entry " + fieldname + " : " + s);
748
    return s;
749
  }
750 6174 cjones
751 6257 cjones
  /**
752 6241 cjones
   * Determine if a given object should be treated as an XML science metadata
753
   * object.
754
   *
755
   * @param sysmeta - the SystemMetadata describing the object
756
   * @return true if the object should be treated as science metadata
757
   */
758 6433 leinfelder
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
759 6241 cjones
760
    ObjectFormat objectFormat = null;
761
    boolean isScienceMetadata = false;
762
763
    try {
764 6561 leinfelder
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
765 6433 leinfelder
      if ( objectFormat.getFormatType().equals("METADATA") ) {
766 6402 cjones
      	isScienceMetadata = true;
767
768
      }
769 6241 cjones
770
    } catch (InvalidRequest e) {
771
       logMetacat.debug("There was a problem determining if the object identified by" +
772
         sysmeta.getIdentifier().getValue() +
773
         " is science metadata: " + e.getMessage());
774
775
    } catch (ServiceFailure e) {
776
      logMetacat.debug("There was a problem determining if the object identified by" +
777
          sysmeta.getIdentifier().getValue() +
778
          " is science metadata: " + e.getMessage());
779
780
    } catch (NotFound e) {
781
      logMetacat.debug("There was a problem determining if the object identified by" +
782
          sysmeta.getIdentifier().getValue() +
783
          " is science metadata: " + e.getMessage());
784
785
    } catch (InsufficientResources e) {
786
      logMetacat.debug("There was a problem determining if the object identified by" +
787
          sysmeta.getIdentifier().getValue() +
788
          " is science metadata: " + e.getMessage());
789
790
    } catch (NotImplemented e) {
791
      logMetacat.debug("There was a problem determining if the object identified by" +
792
          sysmeta.getIdentifier().getValue() +
793
          " is science metadata: " + e.getMessage());
794
795
    }
796
797
    return isScienceMetadata;
798 6226 cjones
799 6241 cjones
  }
800
801
  /**
802
   * Insert or update an XML document into Metacat
803
   *
804
   * @param xml - the XML document to insert or update
805
   * @param pid - the identifier to be used for the resulting object
806
   *
807
   * @return localId - the resulting docid of the document created or updated
808
   *
809
   */
810 6807 leinfelder
  public String insertOrUpdateDocument(String xml, Identifier pid,
811 6241 cjones
    Session session, String insertOrUpdate)
812
    throws ServiceFailure {
813
814
  	logMetacat.debug("Starting to insert xml document...");
815
    IdentifierManager im = IdentifierManager.getInstance();
816
817
    // generate pid/localId pair for sysmeta
818
    String localId = null;
819
820
    if(insertOrUpdate.equals("insert")) {
821
      localId = im.generateLocalId(pid.getValue(), 1);
822
823
    } else {
824
      //localid should already exist in the identifier table, so just find it
825
      try {
826
        logMetacat.debug("Updating pid " + pid.getValue());
827
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
828
829
        localId = im.getLocalId(pid.getValue());
830
831
        logMetacat.debug("localId: " + localId);
832
        //increment the revision
833
        String docid = localId.substring(0, localId.lastIndexOf("."));
834
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
835
        int rev = new Integer(revS).intValue();
836
        rev++;
837
        docid = docid + "." + rev;
838
        localId = docid;
839
        logMetacat.debug("incremented localId: " + localId);
840
841
      } catch(McdbDocNotFoundException e) {
842
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
843
            "pid " + pid.getValue() +
844
            " should have been in the identifier table, but it wasn't: " +
845
            e.getMessage());
846
847
      }
848
849
    }
850
851 6443 leinfelder
    params = new Hashtable<String, String[]>();
852 6241 cjones
    String[] action = new String[1];
853
    action[0] = insertOrUpdate;
854
    params.put("action", action);
855
    String[] docid = new String[1];
856
    docid[0] = localId;
857
    params.put("docid", docid);
858
    String[] doctext = new String[1];
859
    doctext[0] = xml;
860
    params.put("doctext", doctext);
861
862 6532 leinfelder
    String username = Constants.SUBJECT_PUBLIC;
863 6241 cjones
    String[] groupnames = null;
864 6302 leinfelder
    if (session != null ) {
865
    	username = session.getSubject().getValue();
866 6532 leinfelder
    	if (session.getSubjectInfo() != null) {
867
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
868 6302 leinfelder
    		if (groupList != null) {
869
    			groupnames = new String[groupList.size()];
870
    			for (int i = 0; i > groupList.size(); i++ ) {
871
    				groupnames[i] = groupList.get(i).getGroupName();
872
    			}
873
    		}
874
    	}
875 6241 cjones
    }
876
877
    // do the insert or update action
878 6443 leinfelder
    handler = new MetacatHandler(new Timer());
879 6542 leinfelder
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null,
880 6241 cjones
                        null, params, username, groupnames);
881
882
    if(result.indexOf("<error>") != -1) {
883
    	String detailCode = "";
884
    	if ( insertOrUpdate.equals("insert") ) {
885
    		detailCode = "1190";
886
887
    	} else if ( insertOrUpdate.equals("update") ) {
888
    		detailCode = "1310";
889
890
    	}
891
        throw new ServiceFailure(detailCode,
892
          "Error inserting or updating document: " + result);
893
    }
894
    logMetacat.debug("Finsished inserting xml document with id " + localId);
895
896
    return localId;
897
  }
898
899
  /**
900
   * Insert a data document
901
   *
902
   * @param object
903
   * @param pid
904
   * @param sessionData
905
   * @throws ServiceFailure
906
   * @returns localId of the data object inserted
907
   */
908 6807 leinfelder
  public String insertDataObject(InputStream object, Identifier pid,
909 6241 cjones
          Session session) throws ServiceFailure {
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
    // generate pid/localId pair for object
927
    logMetacat.debug("Generating a pid/localId mapping");
928
    IdentifierManager im = IdentifierManager.getInstance();
929
    String localId = im.generateLocalId(pid.getValue(), 1);
930 6719 leinfelder
931
    // Save the data file to disk using "localId" as the name
932
    String datafilepath = null;
933
	try {
934
		datafilepath = PropertyService.getProperty("application.datafilepath");
935
	} catch (PropertyNotFoundException e) {
936
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
937
		sf.initCause(e);
938
		throw sf;
939
	}
940
    boolean locked = false;
941
	try {
942
		locked = DocumentImpl.getDataFileLockGrant(localId);
943
	} catch (Exception e) {
944
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
945
		sf.initCause(e);
946
		throw sf;
947
	}
948
949
    logMetacat.debug("Case DATA: starting to write to disk.");
950
	if (locked) {
951
952 6241 cjones
          File dataDirectory = new File(datafilepath);
953
          dataDirectory.mkdirs();
954
955
          File newFile = writeStreamToFile(dataDirectory, localId, object);
956
957
          // TODO: Check that the file size matches SystemMetadata
958
          // long size = newFile.length();
959
          // if (size == 0) {
960
          //     throw new IOException("Uploaded file is 0 bytes!");
961
          // }
962
963
          // Register the file in the database (which generates an exception
964
          // if the localId is not acceptable or other untoward things happen
965
          try {
966
            logMetacat.debug("Registering document...");
967
            DocumentImpl.registerDocument(localId, "BIN", localId,
968
                    username, groupnames);
969
            logMetacat.debug("Registration step completed.");
970
971
          } catch (SQLException e) {
972
            //newFile.delete();
973
            logMetacat.debug("SQLE: " + e.getMessage());
974
            e.printStackTrace(System.out);
975
            throw new ServiceFailure("1190", "Registration failed: " +
976
            		e.getMessage());
977
978
          } catch (AccessionNumberException e) {
979
            //newFile.delete();
980
            logMetacat.debug("ANE: " + e.getMessage());
981
            e.printStackTrace(System.out);
982
            throw new ServiceFailure("1190", "Registration failed: " +
983
            	e.getMessage());
984
985
          } catch (Exception e) {
986
            //newFile.delete();
987
            logMetacat.debug("Exception: " + e.getMessage());
988
            e.printStackTrace(System.out);
989
            throw new ServiceFailure("1190", "Registration failed: " +
990
            	e.getMessage());
991
          }
992
993
          logMetacat.debug("Logging the creation event.");
994 6542 leinfelder
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
995 6241 cjones
996
          // Schedule replication for this data file
997
          logMetacat.debug("Scheduling replication.");
998
          ForceReplicationHandler frh = new ForceReplicationHandler(
999
            localId, "create", false, null);
1000 6719 leinfelder
      }
1001
1002
      return localId;
1003 6241 cjones
1004
  }
1005 6255 cjones
1006 6256 cjones
  /**
1007
   * Insert a systemMetadata document and return its localId
1008
   */
1009 6807 leinfelder
  public void insertSystemMetadata(SystemMetadata sysmeta)
1010 6572 cjones
      throws ServiceFailure {
1011
1012
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1013
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1014
      logMetacat.debug("Inserting new system metadata with modified date " +
1015
          sysmeta.getDateSysMetadataModified());
1016
1017
      //insert the system metadata
1018
      try {
1019
        // note: the calling subclass handles the map hazelcast lock/unlock
1020
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1021
1022
      } catch (Exception e) {
1023
          throw new ServiceFailure("1190", e.getMessage());
1024
1025
	    }
1026 6256 cjones
  }
1027
1028
  /**
1029 6255 cjones
   * Update a systemMetadata document
1030
   *
1031
   * @param sysMeta - the system metadata object in the system to update
1032
   */
1033
  protected void updateSystemMetadata(SystemMetadata sysMeta)
1034
    throws ServiceFailure {
1035
1036
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1037
    sysMeta.setDateSysMetadataModified(new Date());
1038 6468 leinfelder
    try {
1039
    	HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1040
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1041
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1042
	} catch (Exception e) {
1043
		throw new ServiceFailure("4862", e.getMessage());
1044
	} finally {
1045
		HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1046
	}
1047 6255 cjones
1048
  }
1049 6816 leinfelder
1050
  /**
1051
   * Given a Permission, returns a list of all permissions that it encompasses
1052
   * Permissions are hierarchical so that WRITE also allows READ.
1053
   * @param permission
1054
   * @return list of included Permissions for the given permission
1055
   */
1056
  protected List<Permission> expandPermissions(Permission permission) {
1057
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1058
	    if (permission.equals(Permission.READ)) {
1059
	    	expandedPermissions.add(Permission.READ);
1060
	    }
1061
	    if (permission.equals(Permission.WRITE)) {
1062
	    	expandedPermissions.add(Permission.READ);
1063
	    	expandedPermissions.add(Permission.WRITE);
1064
	    }
1065
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1066
	    	expandedPermissions.add(Permission.READ);
1067
	    	expandedPermissions.add(Permission.WRITE);
1068
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1069
	    }
1070
	    return expandedPermissions;
1071
  }
1072 6255 cjones
1073
  /*
1074 6241 cjones
   * Write a stream to a file
1075
   *
1076
   * @param dir - the directory to write to
1077
   * @param fileName - the file name to write to
1078
   * @param data - the object bytes as an input stream
1079
   *
1080
   * @return newFile - the new file created
1081
   *
1082
   * @throws ServiceFailure
1083
   */
1084
  private File writeStreamToFile(File dir, String fileName, InputStream data)
1085
    throws ServiceFailure {
1086
1087
    File newFile = new File(dir, fileName);
1088
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1089
1090
    try {
1091
        if (newFile.createNewFile()) {
1092
          // write data stream to desired file
1093
          OutputStream os = new FileOutputStream(newFile);
1094
          long length = IOUtils.copyLarge(data, os);
1095
          os.flush();
1096
          os.close();
1097
        } else {
1098
          logMetacat.debug("File creation failed, or file already exists.");
1099
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1100
        }
1101
    } catch (FileNotFoundException e) {
1102
      logMetacat.debug("FNF: " + e.getMessage());
1103
      throw new ServiceFailure("1190", "File not found: " + fileName + " "
1104
                + e.getMessage());
1105
    } catch (IOException e) {
1106
      logMetacat.debug("IOE: " + e.getMessage());
1107
      throw new ServiceFailure("1190", "File was not written: " + fileName
1108
                + " " + e.getMessage());
1109
    }
1110
1111
    return newFile;
1112
  }
1113
1114
}