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