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