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
                  }
648 6874 cjones
              }
649 6865 cjones
          }
650
      }
651
652
653
      return allowed;
654
  }
655
656
  /**
657 6227 cjones
   * Test if the user identified by the provided token has authorization
658 6865 cjones
   * for the operation on the specified object.
659 6227 cjones
   *
660
   * @param session - the Session object containing the credentials for the Subject
661
   * @param pid - The identifer of the resource for which access is being checked
662
   * @param operation - The type of operation which is being requested for the given pid
663
   *
664
   * @return true if the operation is allowed
665
   *
666
   * @throws ServiceFailure
667
   * @throws InvalidToken
668
   * @throws NotFound
669
   * @throws NotAuthorized
670
   * @throws NotImplemented
671
   * @throws InvalidRequest
672
   */
673
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
674
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
675 6609 cjones
    NotImplemented {
676 6174 cjones
677 6227 cjones
    boolean allowed = false;
678
679 6816 leinfelder
    // permissions are hierarchical
680 6830 leinfelder
    List<Permission> expandedPermissions = null;
681 6816 leinfelder
682
    // for the "Verified" symbolic user
683
    Subject verifiedSubject = new Subject();
684
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
685
686 6227 cjones
    // get the subjects from the session
687
    List<Subject> subjects = new ArrayList<Subject>();
688 6412 leinfelder
    if (session != null) {
689
	    Subject subject = session.getSubject();
690
	    if (subject != null) {
691
	    	subjects.add(subject);
692
	    }
693 6664 leinfelder
	    SubjectInfo subjectInfo = session.getSubjectInfo();
694
	    if (subjectInfo != null) {
695 6816 leinfelder
	    	// add the equivalent identities
696 6664 leinfelder
	    	List<Person> personList = subjectInfo.getPersonList();
697 6412 leinfelder
	    	if (personList != null) {
698
			    for (Person p: personList) {
699
			      subjects.add(p.getSubject());
700 6664 leinfelder
			      if (p.getVerified()) {
701
			    	  // add the verified symbolic user
702
			    	  if (!subjects.contains(verifiedSubject)) {
703
			    		  subjects.add(verifiedSubject);
704
			    	  }
705
			      }
706 6412 leinfelder
			    }
707
	    	}
708 6816 leinfelder
	    	// add the groups
709 6664 leinfelder
	    	List<Group> groupList = subjectInfo.getGroupList();
710 6412 leinfelder
	    	if (groupList != null) {
711
			    for (Group g: groupList) {
712
			      subjects.add(g.getSubject());
713
			    }
714
	    	}
715
	    }
716 6664 leinfelder
	    // add the authenticated symbolic as a check
717
	    Subject authenticatedSubject = new Subject();
718
	    authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
719
	    subjects.add(authenticatedSubject);
720
721 6227 cjones
    }
722
723 6293 leinfelder
    // add public subject
724
    Subject publicSubject = new Subject();
725 6532 leinfelder
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
726 6293 leinfelder
    subjects.add(publicSubject);
727
728 6227 cjones
    // get the system metadata
729 6241 cjones
    String pidStr = pid.getValue();
730 6227 cjones
    SystemMetadata systemMetadata = null;
731
    try {
732 6574 cjones
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
733
734
    } catch (Exception e) {
735
        // convert Hazelcast RuntimeException to NotFound
736
        logMetacat.error("An error occurred while getting system metadata for identifier " +
737
            pid.getValue() + ". The error message was: " + e.getMessage());
738
        throw new NotFound("1800", "No record found for " + pidStr);
739
740 6858 cjones
    }
741 6596 leinfelder
742
    // throw not found if it was not found
743
    if (systemMetadata == null) {
744 6652 leinfelder
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
745 6596 leinfelder
    }
746 6245 leinfelder
747 6293 leinfelder
    // do we own it?
748
    for (Subject s: subjects) {
749 6688 leinfelder
    	allowed = systemMetadata.getRightsHolder().equals(s);
750 6293 leinfelder
    	if (allowed) {
751
    		return allowed;
752
    	}
753
    }
754
755
    // otherwise check the access rules
756 6245 leinfelder
    try {
757
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
758 6293 leinfelder
	    search: // label break
759 6245 leinfelder
	    for (AccessRule accessRule: allows) {
760
	      for (Subject s: subjects) {
761 6816 leinfelder
	        if (accessRule.getSubjectList().contains(s)) {
762 6830 leinfelder
	        	for (Permission p: accessRule.getPermissionList()) {
763
	        		expandedPermissions = expandPermissions(p);
764
	        		allowed = expandedPermissions.contains(permission);
765
	        		if (allowed) {
766
	        			break search; //label break
767
	        		}
768 6816 leinfelder
	        	}
769
770 6245 leinfelder
	        }
771
	      }
772
	    }
773
    } catch (Exception e) {
774
    	// catch all for errors - safe side should be to deny the access
775
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
776
		allowed = false;
777
	}
778 6227 cjones
779 6245 leinfelder
    // throw or return?
780 6227 cjones
    if (!allowed) {
781 6245 leinfelder
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
782 6227 cjones
    }
783 6245 leinfelder
784 6227 cjones
    return allowed;
785 6241 cjones
786 6227 cjones
  }
787
788 6256 cjones
  /*
789 6227 cjones
   * parse a logEntry and get the relevant field from it
790
   *
791
   * @param fieldname
792
   * @param entry
793
   * @return
794
   */
795
  private String getLogEntryField(String fieldname, String entry) {
796
    String begin = "<" + fieldname + ">";
797
    String end = "</" + fieldname + ">";
798
    // logMetacat.debug("looking for " + begin + " and " + end +
799
    // " in entry " + entry);
800
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
801
        .indexOf(end));
802
    logMetacat.debug("entry " + fieldname + " : " + s);
803
    return s;
804
  }
805 6174 cjones
806 6257 cjones
  /**
807 6241 cjones
   * Determine if a given object should be treated as an XML science metadata
808
   * object.
809
   *
810
   * @param sysmeta - the SystemMetadata describing the object
811
   * @return true if the object should be treated as science metadata
812
   */
813 6433 leinfelder
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
814 6241 cjones
815
    ObjectFormat objectFormat = null;
816
    boolean isScienceMetadata = false;
817
818
    try {
819 6561 leinfelder
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
820 6433 leinfelder
      if ( objectFormat.getFormatType().equals("METADATA") ) {
821 6402 cjones
      	isScienceMetadata = true;
822
823
      }
824 6241 cjones
825
    } catch (InvalidRequest e) {
826
       logMetacat.debug("There was a problem determining if the object identified by" +
827
         sysmeta.getIdentifier().getValue() +
828
         " is science metadata: " + e.getMessage());
829
830
    } catch (ServiceFailure e) {
831
      logMetacat.debug("There was a problem determining if the object identified by" +
832
          sysmeta.getIdentifier().getValue() +
833
          " is science metadata: " + e.getMessage());
834
835
    } catch (NotFound e) {
836
      logMetacat.debug("There was a problem determining if the object identified by" +
837
          sysmeta.getIdentifier().getValue() +
838
          " is science metadata: " + e.getMessage());
839
840
    } catch (InsufficientResources e) {
841
      logMetacat.debug("There was a problem determining if the object identified by" +
842
          sysmeta.getIdentifier().getValue() +
843
          " is science metadata: " + e.getMessage());
844
845
    } catch (NotImplemented e) {
846
      logMetacat.debug("There was a problem determining if the object identified by" +
847
          sysmeta.getIdentifier().getValue() +
848
          " is science metadata: " + e.getMessage());
849
850
    }
851
852
    return isScienceMetadata;
853 6226 cjones
854 6241 cjones
  }
855
856
  /**
857
   * Insert or update an XML document into Metacat
858
   *
859
   * @param xml - the XML document to insert or update
860
   * @param pid - the identifier to be used for the resulting object
861
   *
862
   * @return localId - the resulting docid of the document created or updated
863
   *
864
   */
865 6807 leinfelder
  public String insertOrUpdateDocument(String xml, Identifier pid,
866 6241 cjones
    Session session, String insertOrUpdate)
867
    throws ServiceFailure {
868
869
  	logMetacat.debug("Starting to insert xml document...");
870
    IdentifierManager im = IdentifierManager.getInstance();
871
872
    // generate pid/localId pair for sysmeta
873
    String localId = null;
874
875
    if(insertOrUpdate.equals("insert")) {
876
      localId = im.generateLocalId(pid.getValue(), 1);
877
878
    } else {
879
      //localid should already exist in the identifier table, so just find it
880
      try {
881
        logMetacat.debug("Updating pid " + pid.getValue());
882
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
883
884
        localId = im.getLocalId(pid.getValue());
885
886
        logMetacat.debug("localId: " + localId);
887
        //increment the revision
888
        String docid = localId.substring(0, localId.lastIndexOf("."));
889
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
890
        int rev = new Integer(revS).intValue();
891
        rev++;
892
        docid = docid + "." + rev;
893
        localId = docid;
894
        logMetacat.debug("incremented localId: " + localId);
895
896
      } catch(McdbDocNotFoundException e) {
897
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
898
            "pid " + pid.getValue() +
899
            " should have been in the identifier table, but it wasn't: " +
900
            e.getMessage());
901
902
      }
903
904
    }
905
906 6443 leinfelder
    params = new Hashtable<String, String[]>();
907 6241 cjones
    String[] action = new String[1];
908
    action[0] = insertOrUpdate;
909
    params.put("action", action);
910
    String[] docid = new String[1];
911
    docid[0] = localId;
912
    params.put("docid", docid);
913
    String[] doctext = new String[1];
914
    doctext[0] = xml;
915
    params.put("doctext", doctext);
916
917 6532 leinfelder
    String username = Constants.SUBJECT_PUBLIC;
918 6241 cjones
    String[] groupnames = null;
919 6302 leinfelder
    if (session != null ) {
920
    	username = session.getSubject().getValue();
921 6532 leinfelder
    	if (session.getSubjectInfo() != null) {
922
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
923 6302 leinfelder
    		if (groupList != null) {
924
    			groupnames = new String[groupList.size()];
925
    			for (int i = 0; i > groupList.size(); i++ ) {
926
    				groupnames[i] = groupList.get(i).getGroupName();
927
    			}
928
    		}
929
    	}
930 6241 cjones
    }
931
932
    // do the insert or update action
933 6443 leinfelder
    handler = new MetacatHandler(new Timer());
934 6542 leinfelder
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null,
935 6241 cjones
                        null, params, username, groupnames);
936
937
    if(result.indexOf("<error>") != -1) {
938
    	String detailCode = "";
939
    	if ( insertOrUpdate.equals("insert") ) {
940
    		detailCode = "1190";
941
942
    	} else if ( insertOrUpdate.equals("update") ) {
943
    		detailCode = "1310";
944
945
    	}
946
        throw new ServiceFailure(detailCode,
947
          "Error inserting or updating document: " + result);
948
    }
949
    logMetacat.debug("Finsished inserting xml document with id " + localId);
950
951
    return localId;
952
  }
953
954
  /**
955
   * Insert a data document
956
   *
957
   * @param object
958
   * @param pid
959
   * @param sessionData
960
   * @throws ServiceFailure
961
   * @returns localId of the data object inserted
962
   */
963 6807 leinfelder
  public String insertDataObject(InputStream object, Identifier pid,
964 6241 cjones
          Session session) throws ServiceFailure {
965
966 6532 leinfelder
    String username = Constants.SUBJECT_PUBLIC;
967 6241 cjones
    String[] groupnames = null;
968 6302 leinfelder
    if (session != null ) {
969
    	username = session.getSubject().getValue();
970 6532 leinfelder
    	if (session.getSubjectInfo() != null) {
971
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
972 6302 leinfelder
    		if (groupList != null) {
973
    			groupnames = new String[groupList.size()];
974
    			for (int i = 0; i > groupList.size(); i++ ) {
975
    				groupnames[i] = groupList.get(i).getGroupName();
976
    			}
977
    		}
978
    	}
979 6241 cjones
    }
980
981
    // generate pid/localId pair for object
982
    logMetacat.debug("Generating a pid/localId mapping");
983
    IdentifierManager im = IdentifierManager.getInstance();
984
    String localId = im.generateLocalId(pid.getValue(), 1);
985 6719 leinfelder
986
    // Save the data file to disk using "localId" as the name
987
    String datafilepath = null;
988
	try {
989
		datafilepath = PropertyService.getProperty("application.datafilepath");
990
	} catch (PropertyNotFoundException e) {
991
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
992
		sf.initCause(e);
993
		throw sf;
994
	}
995
    boolean locked = false;
996
	try {
997
		locked = DocumentImpl.getDataFileLockGrant(localId);
998
	} catch (Exception e) {
999
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1000
		sf.initCause(e);
1001
		throw sf;
1002
	}
1003
1004
    logMetacat.debug("Case DATA: starting to write to disk.");
1005
	if (locked) {
1006
1007 6241 cjones
          File dataDirectory = new File(datafilepath);
1008
          dataDirectory.mkdirs();
1009
1010
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1011
1012
          // TODO: Check that the file size matches SystemMetadata
1013
          // long size = newFile.length();
1014
          // if (size == 0) {
1015
          //     throw new IOException("Uploaded file is 0 bytes!");
1016
          // }
1017
1018
          // Register the file in the database (which generates an exception
1019
          // if the localId is not acceptable or other untoward things happen
1020
          try {
1021
            logMetacat.debug("Registering document...");
1022
            DocumentImpl.registerDocument(localId, "BIN", localId,
1023
                    username, groupnames);
1024
            logMetacat.debug("Registration step completed.");
1025
1026
          } catch (SQLException e) {
1027
            //newFile.delete();
1028
            logMetacat.debug("SQLE: " + e.getMessage());
1029
            e.printStackTrace(System.out);
1030
            throw new ServiceFailure("1190", "Registration failed: " +
1031
            		e.getMessage());
1032
1033
          } catch (AccessionNumberException e) {
1034
            //newFile.delete();
1035
            logMetacat.debug("ANE: " + e.getMessage());
1036
            e.printStackTrace(System.out);
1037
            throw new ServiceFailure("1190", "Registration failed: " +
1038
            	e.getMessage());
1039
1040
          } catch (Exception e) {
1041
            //newFile.delete();
1042
            logMetacat.debug("Exception: " + e.getMessage());
1043
            e.printStackTrace(System.out);
1044
            throw new ServiceFailure("1190", "Registration failed: " +
1045
            	e.getMessage());
1046
          }
1047
1048
          logMetacat.debug("Logging the creation event.");
1049 6542 leinfelder
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1050 6241 cjones
1051
          // Schedule replication for this data file
1052
          logMetacat.debug("Scheduling replication.");
1053
          ForceReplicationHandler frh = new ForceReplicationHandler(
1054
            localId, "create", false, null);
1055 6719 leinfelder
      }
1056
1057
      return localId;
1058 6241 cjones
1059
  }
1060 6255 cjones
1061 6256 cjones
  /**
1062
   * Insert a systemMetadata document and return its localId
1063
   */
1064 6807 leinfelder
  public void insertSystemMetadata(SystemMetadata sysmeta)
1065 6572 cjones
      throws ServiceFailure {
1066
1067
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1068
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1069
      logMetacat.debug("Inserting new system metadata with modified date " +
1070
          sysmeta.getDateSysMetadataModified());
1071
1072
      //insert the system metadata
1073
      try {
1074
        // note: the calling subclass handles the map hazelcast lock/unlock
1075
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1076
1077
      } catch (Exception e) {
1078
          throw new ServiceFailure("1190", e.getMessage());
1079
1080
	    }
1081 6256 cjones
  }
1082
1083
  /**
1084 6255 cjones
   * Update a systemMetadata document
1085
   *
1086
   * @param sysMeta - the system metadata object in the system to update
1087
   */
1088 6858 cjones
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1089
        throws ServiceFailure {
1090
1091
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1092
        sysMeta.setDateSysMetadataModified(new Date());
1093
        try {
1094
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1095
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1096
1097
        } catch (Exception e) {
1098
            throw new ServiceFailure("4862", e.getMessage());
1099
1100
        } finally {
1101
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1102
1103
        }
1104
1105
    }
1106 6816 leinfelder
1107
  /**
1108
   * Given a Permission, returns a list of all permissions that it encompasses
1109
   * Permissions are hierarchical so that WRITE also allows READ.
1110
   * @param permission
1111
   * @return list of included Permissions for the given permission
1112
   */
1113
  protected List<Permission> expandPermissions(Permission permission) {
1114
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1115
	    if (permission.equals(Permission.READ)) {
1116
	    	expandedPermissions.add(Permission.READ);
1117
	    }
1118
	    if (permission.equals(Permission.WRITE)) {
1119
	    	expandedPermissions.add(Permission.READ);
1120
	    	expandedPermissions.add(Permission.WRITE);
1121
	    }
1122
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1123
	    	expandedPermissions.add(Permission.READ);
1124
	    	expandedPermissions.add(Permission.WRITE);
1125
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1126
	    }
1127
	    return expandedPermissions;
1128
  }
1129 6255 cjones
1130
  /*
1131 6241 cjones
   * Write a stream to a file
1132
   *
1133
   * @param dir - the directory to write to
1134
   * @param fileName - the file name to write to
1135
   * @param data - the object bytes as an input stream
1136
   *
1137
   * @return newFile - the new file created
1138
   *
1139
   * @throws ServiceFailure
1140
   */
1141
  private File writeStreamToFile(File dir, String fileName, InputStream data)
1142
    throws ServiceFailure {
1143
1144
    File newFile = new File(dir, fileName);
1145
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1146
1147
    try {
1148
        if (newFile.createNewFile()) {
1149
          // write data stream to desired file
1150
          OutputStream os = new FileOutputStream(newFile);
1151
          long length = IOUtils.copyLarge(data, os);
1152
          os.flush();
1153
          os.close();
1154
        } else {
1155
          logMetacat.debug("File creation failed, or file already exists.");
1156
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1157
        }
1158
    } catch (FileNotFoundException e) {
1159
      logMetacat.debug("FNF: " + e.getMessage());
1160
      throw new ServiceFailure("1190", "File not found: " + fileName + " "
1161
                + e.getMessage());
1162
    } catch (IOException e) {
1163
      logMetacat.debug("IOE: " + e.getMessage());
1164
      throw new ServiceFailure("1190", "File was not written: " + fileName
1165
                + " " + e.getMessage());
1166
    }
1167
1168
    return newFile;
1169
  }
1170
1171
}