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