Project

General

Profile

1
/**
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: cjones $'
7
 *     '$Date: 2011-11-01 06:37:59 -0700 (Tue, 01 Nov 2011) $'
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
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32
import java.sql.SQLException;
33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.Date;
36
import java.util.Hashtable;
37
import java.util.List;
38
import java.util.Timer;
39
import java.util.Vector;
40

    
41
import javax.servlet.http.HttpServletRequest;
42

    
43

    
44
import org.apache.commons.io.IOUtils;
45
import org.apache.log4j.Logger;
46
import org.dataone.client.ObjectFormatCache;
47
import org.dataone.service.util.Constants;
48
import org.dataone.service.exceptions.IdentifierNotUnique;
49
import org.dataone.service.exceptions.InsufficientResources;
50
import org.dataone.service.exceptions.InvalidRequest;
51
import org.dataone.service.exceptions.InvalidSystemMetadata;
52
import org.dataone.service.exceptions.InvalidToken;
53
import org.dataone.service.exceptions.NotAuthorized;
54
import org.dataone.service.exceptions.NotFound;
55
import org.dataone.service.exceptions.NotImplemented;
56
import org.dataone.service.exceptions.ServiceFailure;
57
import org.dataone.service.exceptions.UnsupportedType;
58
import org.dataone.service.types.v1.AccessPolicy;
59
import org.dataone.service.types.v1.AccessRule;
60
import org.dataone.service.types.v1.Event;
61
import org.dataone.service.types.v1.Identifier;
62
import org.dataone.service.types.v1.Group;
63
import org.dataone.service.types.v1.Log;
64
import org.dataone.service.types.v1.LogEntry;
65
import org.dataone.service.types.v1.NodeReference;
66
import org.dataone.service.types.v1.ObjectFormat;
67
import org.dataone.service.types.v1.Permission;
68
import org.dataone.service.types.v1.Person;
69
import org.dataone.service.types.v1.Session;
70
import org.dataone.service.types.v1.Subject;
71
import org.dataone.service.types.v1.SubjectInfo;
72
import org.dataone.service.types.v1.SubjectList;
73
import org.dataone.service.types.v1.SystemMetadata;
74
import org.dataone.service.types.v1.util.ChecksumUtil;
75

    
76
import edu.ucsb.nceas.metacat.AccessionNumberException;
77
import edu.ucsb.nceas.metacat.DocumentImpl;
78
import edu.ucsb.nceas.metacat.EventLog;
79
import edu.ucsb.nceas.metacat.IdentifierManager;
80
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
81
import edu.ucsb.nceas.metacat.MetacatHandler;
82
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
83
import edu.ucsb.nceas.metacat.properties.PropertyService;
84
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
85
import edu.ucsb.nceas.metacat.util.SystemUtil;
86
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
87

    
88
public abstract class D1NodeService {
89
  
90
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
91

    
92
  /** For logging the operations */
93
  protected HttpServletRequest request;
94
  
95
  /* reference to the metacat handler */
96
  protected MetacatHandler handler;
97
  
98
  /* parameters set in the incoming request */
99
  private Hashtable<String, String[]> params;
100

    
101
  /**
102
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
103
   * 
104
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
105
   */
106
  public D1NodeService(HttpServletRequest request) {
107
		this.request = request;
108
	}
109
  
110
  /**
111
   * Adds a new object to the Node, where the object is either a data 
112
   * object or a science metadata object. This method is called by clients 
113
   * to create new data objects on Member Nodes or internally for Coordinating
114
   * Nodes
115
   * 
116
   * @param session - the Session object containing the credentials for the Subject
117
   * @param pid - The object identifier to be created
118
   * @param object - the object bytes
119
   * @param sysmeta - the system metadata that describes the object  
120
   * 
121
   * @return pid - the object identifier created
122
   * 
123
   * @throws InvalidToken
124
   * @throws ServiceFailure
125
   * @throws NotAuthorized
126
   * @throws IdentifierNotUnique
127
   * @throws UnsupportedType
128
   * @throws InsufficientResources
129
   * @throws InvalidSystemMetadata
130
   * @throws NotImplemented
131
   * @throws InvalidRequest
132
   */
133
  public Identifier create(Session session, Identifier pid, InputStream object,
134
    SystemMetadata sysmeta) 
135
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
136
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
137
    NotImplemented, InvalidRequest {
138

    
139
    Identifier resultPid = null;
140
    String localId = null;
141
    boolean allowed = false;
142
    
143
    // check for null session
144
    if (session == null) {
145
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
146
    }
147
    Subject subject = session.getSubject();
148

    
149
    // be sure the user is authenticated for create()
150
    if (subject == null || subject.getValue() == null || 
151
        subject.getValue().toLowerCase().equals(Constants.SUBJECT_PUBLIC) ) {
152
      throw new NotAuthorized("1100", "The provided identity does not have " +
153
        "permission to WRITE to the Node.");
154
      
155
    }
156
    
157
    // verify that pid == SystemMetadata.getIdentifier()
158
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
159
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
160
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
161
        throw new InvalidSystemMetadata("1180", 
162
            "The supplied system metadata is invalid. " +
163
            "The identifier " + pid.getValue() + " does not match identifier" +
164
            "in the system metadata identified by " +
165
            sysmeta.getIdentifier().getValue() + ".");
166
        
167
    }
168

    
169
    logMetacat.debug("Checking if identifier exists...");
170
    // Check that the identifier does not already exist
171
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
172
	    	throw new IdentifierNotUnique("1120", 
173
			          "The requested identifier " + pid.getValue() +
174
			          " is already used by another object and" +
175
			          "therefore can not be used for this object. Clients should choose" +
176
			          "a new identifier that is unique and retry the operation or " +
177
			          "use CN.reserveIdentifier() to reserve one.");
178
    	
179
    }
180
    
181
    // check that we are not attempting to subvert versioning
182
    if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
183
    	throw new InvalidSystemMetadata("1180", 
184
    			"The supplied system metadata is invalid. " +
185
    			"The obsoletes field cannot have a value when creating entries.");
186
    }
187
    if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
188
    	throw new InvalidSystemMetadata("1180", 
189
    			"The supplied system metadata is invalid. " +
190
    			"The obsoletedBy field cannot have a value when creating entries.");
191
	}
192
    
193
    // check for permission
194
    try {
195
      allowed = isAuthorized(session, pid, Permission.WRITE);
196
            
197
    } catch (NotFound e) {
198
      // The identifier doesn't exist, writing should be fine.
199
      allowed = true;
200
      
201
    }
202
    
203
    // verify checksum, only if we can reset the inputstream
204
    if (object.markSupported()) {
205
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
206
	    String checksumValue = sysmeta.getChecksum().getValue();
207
	    try {
208
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
209
			// it's very important that we don't consume the stream
210
			object.reset();
211
			if (!computedChecksumValue.equals(checksumValue)) {
212
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
213
			}
214
		} catch (Exception e) {
215
			String msg = "Error verifying checksum values";
216
	      	logMetacat.error(msg, e);
217
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
218
		}
219
    } else {
220
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
221
    }
222
    	
223
    // we have the go ahead
224
    if ( allowed ) {
225
      
226
      // Science metadata (XML) or science data object?
227
      // TODO: there are cases where certain object formats are science metadata
228
      // but are not XML (netCDF ...).  Handle this.
229
      if ( isScienceMetadata(sysmeta) ) {
230
        
231
        // CASE METADATA:
232
      	String objectAsXML = "";
233
        try {
234
	        objectAsXML = IOUtils.toString(object, "UTF-8");
235
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
236
	        //localId = im.getLocalId(pid.getValue());
237

    
238
        } catch (IOException e) {
239
        	String msg = "The Node is unable to create the object. " +
240
          "There was a problem converting the object to XML";
241
        	logMetacat.info(msg);
242
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
243

    
244
        }
245
                    
246
      } else {
247
	        
248
	      // DEFAULT CASE: DATA (needs to be checked and completed)
249
	      localId = insertDataObject(object, pid, session);
250
      }   
251
    
252
    }
253

    
254
    // save the sysmeta
255
    try {
256
      // lock and unlock of the pid happens in the subclass
257
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
258
    	
259
    } catch (Exception e) {
260
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
261
        throw new ServiceFailure("1190", e.getMessage());
262
	}
263
    
264
    // setting the resulting identifier failed
265
    if (localId == null ) {
266
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
267
    }
268

    
269
    resultPid = pid;
270
    
271
    return resultPid;
272
  }
273

    
274
  /**
275
   * Return the log records associated with a given event between the start and 
276
   * end dates listed given a particular Subject listed in the Session
277
   * 
278
   * @param session - the Session object containing the credentials for the Subject
279
   * @param fromDate - the start date of the desired log records
280
   * @param toDate - the end date of the desired log records
281
   * @param event - restrict log records of a specific event type
282
   * @param start - zero based offset from the first record in the 
283
   *                set of matching log records. Used to assist with 
284
   *                paging the response.
285
   * @param count - maximum number of log records to return in the response. 
286
   *                Used to assist with paging the response.
287
   * 
288
   * @return the desired log records
289
   * 
290
   * @throws InvalidToken
291
   * @throws ServiceFailure
292
   * @throws NotAuthorized
293
   * @throws InvalidRequest
294
   * @throws NotImplemented
295
   */
296
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
297
      Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
298
      NotAuthorized, InvalidRequest, NotImplemented {
299

    
300

    
301
    Log log = new Log();
302
    List<LogEntry> logs = new Vector<LogEntry>();
303
    IdentifierManager im = IdentifierManager.getInstance();
304
    EventLog el = EventLog.getInstance();
305
    if ( fromDate == null ) {
306
      logMetacat.debug("setting fromdate from null");
307
      fromDate = new Date(1);
308
    }
309
    if ( toDate == null ) {
310
      logMetacat.debug("setting todate from null");
311
      toDate = new Date();
312
    }
313

    
314
    if ( start == null ) {
315
    	start = 0;
316
    	
317
    }
318
    
319
    if ( count == null ) {
320
    	count = 1000;
321
    	
322
    }
323

    
324
    logMetacat.debug("fromDate: " + fromDate);
325
    logMetacat.debug("toDate: " + toDate);
326

    
327
    String report = el.getReport(null, null, null, null,
328
        new java.sql.Timestamp(fromDate.getTime()),
329
        new java.sql.Timestamp(toDate.getTime()), false);
330

    
331
    logMetacat.debug("report: " + report);
332

    
333
    String logEntry = "<logEntry>";
334
    String endLogEntry = "</logEntry>";
335
    int startIndex = 0;
336
    int foundIndex = report.indexOf(logEntry, startIndex);
337
    while (foundIndex != -1) {
338
      // parse out each entry
339
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
340
      String entry = report.substring(foundIndex, endEntryIndex);
341
      logMetacat.debug("entry: " + entry);
342
      startIndex = endEntryIndex + endLogEntry.length();
343
      foundIndex = report.indexOf(logEntry, startIndex);
344

    
345
      String entryId = getLogEntryField("entryid", entry);
346
      String ipAddress = getLogEntryField("ipAddress", entry);
347
      String principal = getLogEntryField("principal", entry);
348
      String userAgent = getLogEntryField("userAgent", entry);
349
      String docid = getLogEntryField("docid", entry);
350
      String eventS = getLogEntryField("event", entry);
351
      String dateLogged = getLogEntryField("dateLogged", entry);
352

    
353
      LogEntry le = new LogEntry();
354

    
355
      Event e = Event.convert(eventS);
356
      if (e == null) { // skip any events that are not Dataone Crud events
357
        continue;
358
      }
359
      le.setEvent(e);
360
      Identifier entryid = new Identifier();
361
      entryid.setValue(entryId);
362
      le.setEntryId(entryid);
363
      Identifier identifier = new Identifier();
364
      try {
365
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
366
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
367
          continue;
368
        }
369
        docid = docid.substring(0, docid.lastIndexOf("."));
370
        identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
371
      } catch (Exception ex) { 
372
        // try to get the pid, if that doesn't
373
        // work, just use the local id
374
        // throw new ServiceFailure("1030",
375
        // "Error getting pid for localId " +
376
        // docid + ": " + ex.getMessage());\
377

    
378
        // skip it if the pid can't be found
379
        continue;
380
      }
381

    
382
      le.setIdentifier(identifier);
383
      le.setIpAddress(ipAddress);
384
      Calendar c = Calendar.getInstance();
385
      String year = dateLogged.substring(0, 4);
386
      String month = dateLogged.substring(5, 7);
387
      String date = dateLogged.substring(8, 10);
388
      logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
389
      c.set(new Integer(year).intValue(), new Integer(month).intValue(),
390
          new Integer(date).intValue());
391
      Date logDate = c.getTime();
392
      le.setDateLogged(logDate);
393
      NodeReference memberNode = new NodeReference();
394
      memberNode.setValue(ipAddress);
395
      le.setMemberNode(memberNode);
396
      Subject princ = new Subject();
397
      princ.setValue(principal);
398
      le.setSubject(princ);
399
      le.setUserAgent(userAgent);
400

    
401
      // event filtering?
402
      if (event == null) {
403
    	  logs.add(le);
404
      } else if (le.getEvent().equals(event)) {
405
    	  logs.add(le);
406
      }
407
    }
408
    
409
    // d1 paging
410
    int total = logs.size();
411
    if (start != null && count != null) {
412
    	int toIndex = start + count;
413
    	if (toIndex <= total) {
414
    		logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
415
    	}
416
    }
417

    
418
    log.setLogEntryList(logs);
419
    log.setStart(start);
420
    log.setCount(logs.size());
421
    log.setTotal(total);
422
    logMetacat.info("getLogRecords");
423
    return log;
424
  }
425
    
426
  /**
427
   * Return the object identified by the given object identifier
428
   * 
429
   * @param session - the Session object containing the credentials for the Subject
430
   * @param pid - the object identifier for the given object
431
   * 
432
   * TODO: The D1 Authorization API doesn't provide information on which 
433
   * authentication system the Subject belongs to, and so it's not possible to
434
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
435
   * 
436
   * @return inputStream - the input stream of the given object
437
   * 
438
   * @throws InvalidToken
439
   * @throws ServiceFailure
440
   * @throws NotAuthorized
441
   * @throws InvalidRequest
442
   * @throws NotImplemented
443
   */
444
  public InputStream get(Session session, Identifier pid) 
445
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
446
    NotImplemented, InvalidRequest {
447
    
448
    InputStream inputStream = null; // bytes to be returned
449
    handler = new MetacatHandler(new Timer());
450
    boolean allowed = false;
451
    String localId; // the metacat docid for the pid
452
    
453
    // get the local docid from Metacat
454
    try {
455
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
456
    
457
    } catch (McdbDocNotFoundException e) {
458
      throw new NotFound("1020", "The object specified by " + 
459
                         pid.getValue() +
460
                         " does not exist at this node.");
461
    }
462
    
463
    // check for authorization
464
    allowed = isAuthorized(session, pid, Permission.READ);
465
    
466
    // if the person is authorized, perform the read
467
    if (allowed) {
468
      try {
469
        inputStream = handler.read(localId);
470
      } catch (Exception e) {
471
        throw new ServiceFailure("1020", "The object specified by " + 
472
            pid.getValue() +
473
            "could not be returned due to error: " +
474
            e.getMessage());
475
      }
476
    }
477

    
478
    // if we fail to set the input stream
479
    if ( inputStream == null ) {
480
      throw new NotFound("1020", "The object specified by " + 
481
                         pid.getValue() +
482
                         "does not exist at this node.");
483
    }
484
    
485
	// log the read event
486
    String principal = Constants.SUBJECT_PUBLIC;
487
    if (session != null && session.getSubject() != null) {
488
    	principal = session.getSubject().getValue();
489
    }
490
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
491
    
492
    return inputStream;
493
  }
494

    
495
  /**
496
   * Return the system metadata for a given object
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
   * @return inputStream - the input stream of the given system metadata object
502
   * 
503
   * @throws InvalidToken
504
   * @throws ServiceFailure
505
   * @throws NotAuthorized
506
   * @throws NotFound
507
   * @throws InvalidRequest
508
   * @throws NotImplemented
509
   */
510
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
511
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
512
      InvalidRequest, NotImplemented {
513
      
514
      if (!isAuthorized(session, pid, Permission.READ)) {
515
        throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
516
      }
517
      SystemMetadata systemMetadata = null;
518
      try {
519
        HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
520
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
521
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
522
        
523
      } catch (Exception e) {
524
        // convert hazelcast RuntimeException to NotFound
525
        throw new NotFound("1420", "No record found for: " + pid.getValue());
526
        
527
      }
528
    
529
    return systemMetadata;
530
  }
531
     
532
  /**
533
   * Test if the user identified by the provided token has authorization 
534
   * for operation on the specified object.
535
   * 
536
   * @param session - the Session object containing the credentials for the Subject
537
   * @param pid - The identifer of the resource for which access is being checked
538
   * @param operation - The type of operation which is being requested for the given pid
539
   *
540
   * @return true if the operation is allowed
541
   * 
542
   * @throws ServiceFailure
543
   * @throws InvalidToken
544
   * @throws NotFound
545
   * @throws NotAuthorized
546
   * @throws NotImplemented
547
   * @throws InvalidRequest
548
   */
549
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
550
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
551
    NotImplemented, InvalidRequest {
552

    
553
    boolean allowed = false;
554
    
555
    // get the subjects from the session
556
    List<Subject> subjects = new ArrayList<Subject>();
557
    if (session != null) {
558
	    Subject subject = session.getSubject();
559
	    if (subject != null) {
560
	    	subjects.add(subject);
561
	    }
562
	    SubjectInfo subjecInfo = session.getSubjectInfo();
563
	    if (subjecInfo != null) {
564
	    	List<Person> personList = subjecInfo.getPersonList();
565
	    	if (personList != null) {
566
			    for (Person p: personList) {
567
			      subjects.add(p.getSubject());
568
			    }
569
	    	}
570
	    	List<Group> groupList = subjecInfo.getGroupList();
571
	    	if (groupList != null) {
572
			    for (Group g: groupList) {
573
			      subjects.add(g.getSubject());
574
			    }
575
	    	}
576
	    }
577
    }
578
    
579
    // add public subject
580
    Subject publicSubject = new Subject();
581
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
582
    subjects.add(publicSubject);
583
    
584
    // get the system metadata
585
    String pidStr = pid.getValue();
586
    SystemMetadata systemMetadata = null;
587
    try {
588
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
589
    } catch (McdbDocNotFoundException e) {
590
      throw new NotFound("1800", "No record found for " + pidStr);
591
    }
592
	    
593
    // do we own it?
594
    for (Subject s: subjects) {
595
    	allowed = systemMetadata.getRightsHolder().getValue().equals(s.getValue());
596
    	if (allowed) {
597
    		return allowed;
598
    	}
599
    }    
600
    
601
    // otherwise check the access rules
602
    try {
603
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
604
	    search: // label break
605
	    for (AccessRule accessRule: allows) {
606
	      for (Subject s: subjects) {
607
	        //if (accessRule.getSubjectList().contains(s)) {
608
        	for (Subject ruleSubject: accessRule.getSubjectList()) {
609
        		if (ruleSubject.getValue().equals(s.getValue())) {
610
		          allowed = accessRule.getPermissionList().contains(permission);
611
		          if (allowed) {
612
		        	  break search; //label break
613
		          }
614
        		}
615
	        }
616
	      }
617
	    }
618
    } catch (Exception e) {
619
    	// catch all for errors - safe side should be to deny the access
620
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
621
		allowed = false;
622
	}
623
    
624
    // throw or return?
625
    if (!allowed) {
626
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
627
    }
628
    
629
    return allowed;
630
    
631
  }
632
  
633
  /*
634
   * parse a logEntry and get the relevant field from it
635
   * 
636
   * @param fieldname
637
   * @param entry
638
   * @return
639
   */
640
  private String getLogEntryField(String fieldname, String entry) {
641
    String begin = "<" + fieldname + ">";
642
    String end = "</" + fieldname + ">";
643
    // logMetacat.debug("looking for " + begin + " and " + end +
644
    // " in entry " + entry);
645
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
646
        .indexOf(end));
647
    logMetacat.debug("entry " + fieldname + " : " + s);
648
    return s;
649
  }
650

    
651
  /** 
652
   * Determine if a given object should be treated as an XML science metadata
653
   * object. 
654
   * 
655
   * @param sysmeta - the SystemMetadata describing the object
656
   * @return true if the object should be treated as science metadata
657
   */
658
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
659
    
660
    ObjectFormat objectFormat = null;
661
    boolean isScienceMetadata = false;
662
    
663
    try {
664
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
665
      if ( objectFormat.getFormatType().equals("METADATA") ) {
666
      	isScienceMetadata = true;
667
      	
668
      }
669
      
670
    } catch (InvalidRequest e) {
671
       logMetacat.debug("There was a problem determining if the object identified by" + 
672
         sysmeta.getIdentifier().getValue() + 
673
         " is science metadata: " + e.getMessage());
674
       
675
    } catch (ServiceFailure e) {
676
      logMetacat.debug("There was a problem determining if the object identified by" + 
677
          sysmeta.getIdentifier().getValue() + 
678
          " is science metadata: " + e.getMessage());
679
    
680
    } catch (NotFound e) {
681
      logMetacat.debug("There was a problem determining if the object identified by" + 
682
          sysmeta.getIdentifier().getValue() + 
683
          " is science metadata: " + e.getMessage());
684
    
685
    } catch (InsufficientResources e) {
686
      logMetacat.debug("There was a problem determining if the object identified by" + 
687
          sysmeta.getIdentifier().getValue() + 
688
          " is science metadata: " + e.getMessage());
689
    
690
    } catch (NotImplemented e) {
691
      logMetacat.debug("There was a problem determining if the object identified by" + 
692
          sysmeta.getIdentifier().getValue() + 
693
          " is science metadata: " + e.getMessage());
694
    
695
    }
696
    
697
    return isScienceMetadata;
698

    
699
  }
700
  
701
  /**
702
   * Insert or update an XML document into Metacat
703
   * 
704
   * @param xml - the XML document to insert or update
705
   * @param pid - the identifier to be used for the resulting object
706
   * 
707
   * @return localId - the resulting docid of the document created or updated
708
   * 
709
   */
710
  protected String insertOrUpdateDocument(String xml, Identifier pid, 
711
    Session session, String insertOrUpdate) 
712
    throws ServiceFailure {
713
    
714
  	logMetacat.debug("Starting to insert xml document...");
715
    IdentifierManager im = IdentifierManager.getInstance();
716

    
717
    // generate pid/localId pair for sysmeta
718
    String localId = null;
719
    
720
    if(insertOrUpdate.equals("insert")) {
721
      localId = im.generateLocalId(pid.getValue(), 1);
722
      
723
    } else {
724
      //localid should already exist in the identifier table, so just find it
725
      try {
726
        logMetacat.debug("Updating pid " + pid.getValue());
727
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
728
        
729
        localId = im.getLocalId(pid.getValue());
730
        
731
        logMetacat.debug("localId: " + localId);
732
        //increment the revision
733
        String docid = localId.substring(0, localId.lastIndexOf("."));
734
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
735
        int rev = new Integer(revS).intValue();
736
        rev++;
737
        docid = docid + "." + rev;
738
        localId = docid;
739
        logMetacat.debug("incremented localId: " + localId);
740
      
741
      } catch(McdbDocNotFoundException e) {
742
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
743
            "pid " + pid.getValue() + 
744
            " should have been in the identifier table, but it wasn't: " + 
745
            e.getMessage());
746
      
747
      }
748
      
749
    }
750

    
751
    params = new Hashtable<String, String[]>();
752
    String[] action = new String[1];
753
    action[0] = insertOrUpdate;
754
    params.put("action", action);
755
    String[] docid = new String[1];
756
    docid[0] = localId;
757
    params.put("docid", docid);
758
    String[] doctext = new String[1];
759
    doctext[0] = xml;
760
    params.put("doctext", doctext);
761
    
762
    String username = Constants.SUBJECT_PUBLIC;
763
    String[] groupnames = null;
764
    if (session != null ) {
765
    	username = session.getSubject().getValue();
766
    	if (session.getSubjectInfo() != null) {
767
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
768
    		if (groupList != null) {
769
    			groupnames = new String[groupList.size()];
770
    			for (int i = 0; i > groupList.size(); i++ ) {
771
    				groupnames[i] = groupList.get(i).getGroupName();
772
    			}
773
    		}
774
    	}
775
    }
776
    
777
    // do the insert or update action
778
    handler = new MetacatHandler(new Timer());
779
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
780
                        null, params, username, groupnames);
781
    
782
    if(result.indexOf("<error>") != -1) {
783
    	String detailCode = "";
784
    	if ( insertOrUpdate.equals("insert") ) {
785
    		detailCode = "1190";
786
    		
787
    	} else if ( insertOrUpdate.equals("update") ) {
788
    		detailCode = "1310";
789
    		
790
    	}
791
        throw new ServiceFailure(detailCode, 
792
          "Error inserting or updating document: " + result);
793
    }
794
    logMetacat.debug("Finsished inserting xml document with id " + localId);
795
    
796
    return localId;
797
  }
798
  
799
  /**
800
   * Insert a data document
801
   * 
802
   * @param object
803
   * @param pid
804
   * @param sessionData
805
   * @throws ServiceFailure
806
   * @returns localId of the data object inserted
807
   */
808
  protected String insertDataObject(InputStream object, Identifier pid, 
809
          Session session) throws ServiceFailure {
810
      
811
    String username = Constants.SUBJECT_PUBLIC;
812
    String[] groupnames = null;
813
    if (session != null ) {
814
    	username = session.getSubject().getValue();
815
    	if (session.getSubjectInfo() != null) {
816
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
817
    		if (groupList != null) {
818
    			groupnames = new String[groupList.size()];
819
    			for (int i = 0; i > groupList.size(); i++ ) {
820
    				groupnames[i] = groupList.get(i).getGroupName();
821
    			}
822
    		}
823
    	}
824
    }
825
  
826
    // generate pid/localId pair for object
827
    logMetacat.debug("Generating a pid/localId mapping");
828
    IdentifierManager im = IdentifierManager.getInstance();
829
    String localId = im.generateLocalId(pid.getValue(), 1);
830
  
831
    try {
832
      logMetacat.debug("Case DATA: starting to write to disk.");
833
      if (DocumentImpl.getDataFileLockGrant(localId)) {
834
  
835
        // Save the data file to disk using "localId" as the name
836
        try {
837
          String datafilepath = PropertyService.getProperty("application.datafilepath");
838
  
839
          File dataDirectory = new File(datafilepath);
840
          dataDirectory.mkdirs();
841
  
842
          File newFile = writeStreamToFile(dataDirectory, localId, object);
843
  
844
          // TODO: Check that the file size matches SystemMetadata
845
          // long size = newFile.length();
846
          // if (size == 0) {
847
          //     throw new IOException("Uploaded file is 0 bytes!");
848
          // }
849
  
850
          // Register the file in the database (which generates an exception
851
          // if the localId is not acceptable or other untoward things happen
852
          try {
853
            logMetacat.debug("Registering document...");
854
            DocumentImpl.registerDocument(localId, "BIN", localId,
855
                    username, groupnames);
856
            logMetacat.debug("Registration step completed.");
857
            
858
          } catch (SQLException e) {
859
            //newFile.delete();
860
            logMetacat.debug("SQLE: " + e.getMessage());
861
            e.printStackTrace(System.out);
862
            throw new ServiceFailure("1190", "Registration failed: " + 
863
            		e.getMessage());
864
            
865
          } catch (AccessionNumberException e) {
866
            //newFile.delete();
867
            logMetacat.debug("ANE: " + e.getMessage());
868
            e.printStackTrace(System.out);
869
            throw new ServiceFailure("1190", "Registration failed: " + 
870
            	e.getMessage());
871
            
872
          } catch (Exception e) {
873
            //newFile.delete();
874
            logMetacat.debug("Exception: " + e.getMessage());
875
            e.printStackTrace(System.out);
876
            throw new ServiceFailure("1190", "Registration failed: " + 
877
            	e.getMessage());
878
          }
879
  
880
          logMetacat.debug("Logging the creation event.");
881
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
882
  
883
          // Schedule replication for this data file
884
          logMetacat.debug("Scheduling replication.");
885
          ForceReplicationHandler frh = new ForceReplicationHandler(
886
            localId, "create", false, null);
887
  
888
        } catch (PropertyNotFoundException e) {
889
          throw new ServiceFailure("1190", "Could not lock file for writing:" + 
890
          	e.getMessage());
891
          
892
        }
893
      }
894
      return localId;
895
    } catch (Exception e) {
896
        // Could not get a lock on the document, so we can not update the file now
897
        throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
898
    }
899
    
900
  }
901

    
902
  /**
903
   * Insert a systemMetadata document and return its localId
904
   */
905
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
906
      throws ServiceFailure {
907
      
908
  	  logMetacat.debug("Starting to insert SystemMetadata...");
909
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
910
      logMetacat.debug("Inserting new system metadata with modified date " + 
911
          sysmeta.getDateSysMetadataModified());
912
      
913
      //insert the system metadata
914
      try {
915
        // note: the calling subclass handles the map hazelcast lock/unlock
916
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
917
      	
918
      } catch (Exception e) {
919
          throw new ServiceFailure("1190", e.getMessage());
920
          
921
	    }  
922
  }
923

    
924
  /**
925
   * Update a systemMetadata document
926
   * 
927
   * @param sysMeta - the system metadata object in the system to update
928
   */
929
  protected void updateSystemMetadata(SystemMetadata sysMeta)
930
    throws ServiceFailure {
931
      
932
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
933
    sysMeta.setDateSysMetadataModified(new Date());
934
    try {
935
    	HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
936
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
937
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
938
	} catch (Exception e) {
939
		throw new ServiceFailure("4862", e.getMessage());
940
	} finally {
941
		HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
942
	}
943
      
944
  }
945

    
946
  /*
947
   * Write a stream to a file
948
   * 
949
   * @param dir - the directory to write to
950
   * @param fileName - the file name to write to
951
   * @param data - the object bytes as an input stream
952
   * 
953
   * @return newFile - the new file created
954
   * 
955
   * @throws ServiceFailure
956
   */
957
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
958
    throws ServiceFailure {
959
    
960
    File newFile = new File(dir, fileName);
961
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
962

    
963
    try {
964
        if (newFile.createNewFile()) {
965
          // write data stream to desired file
966
          OutputStream os = new FileOutputStream(newFile);
967
          long length = IOUtils.copyLarge(data, os);
968
          os.flush();
969
          os.close();
970
        } else {
971
          logMetacat.debug("File creation failed, or file already exists.");
972
          throw new ServiceFailure("1190", "File already exists: " + fileName);
973
        }
974
    } catch (FileNotFoundException e) {
975
      logMetacat.debug("FNF: " + e.getMessage());
976
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
977
                + e.getMessage());
978
    } catch (IOException e) {
979
      logMetacat.debug("IOE: " + e.getMessage());
980
      throw new ServiceFailure("1190", "File was not written: " + fileName 
981
                + " " + e.getMessage());
982
    }
983

    
984
    return newFile;
985
  }
986
  
987
}
(2-2/4)