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