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