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