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: leinfelder $'
7
 *     '$Date: 2011-10-27 17:51:48 -0700 (Thu, 27 Oct 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
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
257
    } catch (Exception e) {
258
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
259
        throw new ServiceFailure("1190", e.getMessage());
260
	}
261
    
262
    // setting the resulting identifier failed
263
    if (localId == null ) {
264
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
265
    }
266

    
267
    resultPid = pid;
268
    
269
    return resultPid;
270
  }
271

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

    
298

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

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

    
322
    logMetacat.debug("fromDate: " + fromDate);
323
    logMetacat.debug("toDate: " + toDate);
324

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

    
329
    logMetacat.debug("report: " + report);
330

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

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

    
351
      LogEntry le = new LogEntry();
352

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

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

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

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

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

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

    
493
  /**
494
   * Return the system metadata for a given object
495
   * 
496
   * @param session - the Session object containing the credentials for the Subject
497
   * @param pid - the object identifier for the given object
498
   * 
499
   * @return inputStream - the input stream of the given system metadata object
500
   * 
501
   * @throws InvalidToken
502
   * @throws ServiceFailure
503
   * @throws NotAuthorized
504
   * @throws NotFound
505
   * @throws InvalidRequest
506
   * @throws NotImplemented
507
   */
508
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
509
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
510
    InvalidRequest, NotImplemented {
511

    
512
    if (!isAuthorized(session, pid, Permission.READ)) {
513
      throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
514
    }
515
    SystemMetadata systemMetadata = null;
516
    try {
517
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
518
    } catch (McdbDocNotFoundException e) {
519
      throw new NotFound("1420", "No record found for: " + pid.getValue());
520
    }
521
    
522
    return systemMetadata;
523
  }
524
   
525
  /**
526
   * Set access for a given object using the object identifier and a Subject
527
   * under a given Session.
528
   * 
529
   * @param session - the Session object containing the credentials for the Subject
530
   * @param pid - the object identifier for the given object to apply the policy
531
   * @param policy - the access policy to be applied
532
   * 
533
   * @return true if the application of the policy succeeds
534
   * @throws InvalidToken
535
   * @throws ServiceFailure
536
   * @throws NotFound
537
   * @throws NotAuthorized
538
   * @throws NotImplemented
539
   * @throws InvalidRequest
540
   */
541
  public boolean setAccessPolicy(Session session, Identifier pid, 
542
    AccessPolicy accessPolicy) 
543
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
544
    NotImplemented, InvalidRequest {
545

    
546
    boolean success = false;
547
    
548
    // get the subject
549
    Subject subject = session.getSubject();
550
    // get the system metadata
551
    String pidStr = pid.getValue();
552
    
553
    // are we allowed to do this?
554
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
555
      throw new NotAuthorized("4420", "not allowed by " + subject.getValue() + " on " + pidStr);  
556
    }
557
    
558
    SystemMetadata systemMetadata = null;
559
    try {
560
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
561
    } catch (McdbDocNotFoundException e) {
562
      throw new NotFound("4400", "No record found for: " + pid);
563
    }
564
        
565
    // set the access policy
566
    systemMetadata.setAccessPolicy(accessPolicy);
567
    
568
    // update the metadata
569
    try {
570
    	HazelcastService.getInstance().getSystemMetadataMap().lock(systemMetadata.getIdentifier());
571
    	HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
572
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
573
	} catch (Exception e) {
574
		throw new ServiceFailure("4430", e.getMessage());
575
	} finally {
576
		HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
577
	}
578
    
579
    // TODO: how do we know if the map was persisted?
580
    success = true;
581
    
582
    return success;
583
  }
584
  
585
  /**
586
   * Test if the user identified by the provided token has authorization 
587
   * for operation on the specified object.
588
   * 
589
   * @param session - the Session object containing the credentials for the Subject
590
   * @param pid - The identifer of the resource for which access is being checked
591
   * @param operation - The type of operation which is being requested for the given pid
592
   *
593
   * @return true if the operation is allowed
594
   * 
595
   * @throws ServiceFailure
596
   * @throws InvalidToken
597
   * @throws NotFound
598
   * @throws NotAuthorized
599
   * @throws NotImplemented
600
   * @throws InvalidRequest
601
   */
602
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
603
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
604
    NotImplemented, InvalidRequest {
605

    
606
    boolean allowed = false;
607
    
608
    // get the subjects from the session
609
    List<Subject> subjects = new ArrayList<Subject>();
610
    if (session != null) {
611
	    Subject subject = session.getSubject();
612
	    if (subject != null) {
613
	    	subjects.add(subject);
614
	    }
615
	    SubjectInfo subjecInfo = session.getSubjectInfo();
616
	    if (subjecInfo != null) {
617
	    	List<Person> personList = subjecInfo.getPersonList();
618
	    	if (personList != null) {
619
			    for (Person p: personList) {
620
			      subjects.add(p.getSubject());
621
			    }
622
	    	}
623
	    	List<Group> groupList = subjecInfo.getGroupList();
624
	    	if (groupList != null) {
625
			    for (Group g: groupList) {
626
			      subjects.add(g.getSubject());
627
			    }
628
	    	}
629
	    }
630
    }
631
    
632
    // add public subject
633
    Subject publicSubject = new Subject();
634
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
635
    subjects.add(publicSubject);
636
    
637
    // get the system metadata
638
    String pidStr = pid.getValue();
639
    SystemMetadata systemMetadata = null;
640
    try {
641
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
642
    } catch (McdbDocNotFoundException e) {
643
      throw new NotFound("1800", "No record found for " + pidStr);
644
    }
645
	    
646
    // do we own it?
647
    for (Subject s: subjects) {
648
    	allowed = systemMetadata.getRightsHolder().getValue().equals(s.getValue());
649
    	if (allowed) {
650
    		return allowed;
651
    	}
652
    }    
653
    
654
    // otherwise check the access rules
655
    try {
656
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
657
	    search: // label break
658
	    for (AccessRule accessRule: allows) {
659
	      for (Subject s: subjects) {
660
	        //if (accessRule.getSubjectList().contains(s)) {
661
        	for (Subject ruleSubject: accessRule.getSubjectList()) {
662
        		if (ruleSubject.getValue().equals(s.getValue())) {
663
		          allowed = accessRule.getPermissionList().contains(permission);
664
		          if (allowed) {
665
		        	  break search; //label break
666
		          }
667
        		}
668
	        }
669
	      }
670
	    }
671
    } catch (Exception e) {
672
    	// catch all for errors - safe side should be to deny the access
673
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
674
		allowed = false;
675
	}
676
    
677
    // throw or return?
678
    if (!allowed) {
679
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
680
    }
681
    
682
    return allowed;
683
    
684
  }
685
  
686
  /*
687
   * parse a logEntry and get the relevant field from it
688
   * 
689
   * @param fieldname
690
   * @param entry
691
   * @return
692
   */
693
  private String getLogEntryField(String fieldname, String entry) {
694
    String begin = "<" + fieldname + ">";
695
    String end = "</" + fieldname + ">";
696
    // logMetacat.debug("looking for " + begin + " and " + end +
697
    // " in entry " + entry);
698
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
699
        .indexOf(end));
700
    logMetacat.debug("entry " + fieldname + " : " + s);
701
    return s;
702
  }
703

    
704
  /** 
705
   * Determine if a given object should be treated as an XML science metadata
706
   * object. 
707
   * 
708
   * @param sysmeta - the SystemMetadata describing the object
709
   * @return true if the object should be treated as science metadata
710
   */
711
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
712
    
713
    ObjectFormat objectFormat = null;
714
    boolean isScienceMetadata = false;
715
    
716
    try {
717
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
718
      if ( objectFormat.getFormatType().equals("METADATA") ) {
719
      	isScienceMetadata = true;
720
      	
721
      }
722
      
723
    } catch (InvalidRequest e) {
724
       logMetacat.debug("There was a problem determining if the object identified by" + 
725
         sysmeta.getIdentifier().getValue() + 
726
         " is science metadata: " + e.getMessage());
727
       
728
    } catch (ServiceFailure e) {
729
      logMetacat.debug("There was a problem determining if the object identified by" + 
730
          sysmeta.getIdentifier().getValue() + 
731
          " is science metadata: " + e.getMessage());
732
    
733
    } catch (NotFound e) {
734
      logMetacat.debug("There was a problem determining if the object identified by" + 
735
          sysmeta.getIdentifier().getValue() + 
736
          " is science metadata: " + e.getMessage());
737
    
738
    } catch (InsufficientResources e) {
739
      logMetacat.debug("There was a problem determining if the object identified by" + 
740
          sysmeta.getIdentifier().getValue() + 
741
          " is science metadata: " + e.getMessage());
742
    
743
    } catch (NotImplemented e) {
744
      logMetacat.debug("There was a problem determining if the object identified by" + 
745
          sysmeta.getIdentifier().getValue() + 
746
          " is science metadata: " + e.getMessage());
747
    
748
    }
749
    
750
    return isScienceMetadata;
751

    
752
  }
753
  
754
  /**
755
   * Insert or update an XML document into Metacat
756
   * 
757
   * @param xml - the XML document to insert or update
758
   * @param pid - the identifier to be used for the resulting object
759
   * 
760
   * @return localId - the resulting docid of the document created or updated
761
   * 
762
   */
763
  protected String insertOrUpdateDocument(String xml, Identifier pid, 
764
    Session session, String insertOrUpdate) 
765
    throws ServiceFailure {
766
    
767
  	logMetacat.debug("Starting to insert xml document...");
768
    IdentifierManager im = IdentifierManager.getInstance();
769

    
770
    // generate pid/localId pair for sysmeta
771
    String localId = null;
772
    
773
    if(insertOrUpdate.equals("insert")) {
774
      localId = im.generateLocalId(pid.getValue(), 1);
775
      
776
    } else {
777
      //localid should already exist in the identifier table, so just find it
778
      try {
779
        logMetacat.debug("Updating pid " + pid.getValue());
780
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
781
        
782
        localId = im.getLocalId(pid.getValue());
783
        
784
        logMetacat.debug("localId: " + localId);
785
        //increment the revision
786
        String docid = localId.substring(0, localId.lastIndexOf("."));
787
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
788
        int rev = new Integer(revS).intValue();
789
        rev++;
790
        docid = docid + "." + rev;
791
        localId = docid;
792
        logMetacat.debug("incremented localId: " + localId);
793
      
794
      } catch(McdbDocNotFoundException e) {
795
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
796
            "pid " + pid.getValue() + 
797
            " should have been in the identifier table, but it wasn't: " + 
798
            e.getMessage());
799
      
800
      }
801
      
802
    }
803

    
804
    params = new Hashtable<String, String[]>();
805
    String[] action = new String[1];
806
    action[0] = insertOrUpdate;
807
    params.put("action", action);
808
    String[] docid = new String[1];
809
    docid[0] = localId;
810
    params.put("docid", docid);
811
    String[] doctext = new String[1];
812
    doctext[0] = xml;
813
    params.put("doctext", doctext);
814
    
815
    String username = Constants.SUBJECT_PUBLIC;
816
    String[] groupnames = null;
817
    if (session != null ) {
818
    	username = session.getSubject().getValue();
819
    	if (session.getSubjectInfo() != null) {
820
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
821
    		if (groupList != null) {
822
    			groupnames = new String[groupList.size()];
823
    			for (int i = 0; i > groupList.size(); i++ ) {
824
    				groupnames[i] = groupList.get(i).getGroupName();
825
    			}
826
    		}
827
    	}
828
    }
829
    
830
    // do the insert or update action
831
    handler = new MetacatHandler(new Timer());
832
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
833
                        null, params, username, groupnames);
834
    
835
    if(result.indexOf("<error>") != -1) {
836
    	String detailCode = "";
837
    	if ( insertOrUpdate.equals("insert") ) {
838
    		detailCode = "1190";
839
    		
840
    	} else if ( insertOrUpdate.equals("update") ) {
841
    		detailCode = "1310";
842
    		
843
    	}
844
        throw new ServiceFailure(detailCode, 
845
          "Error inserting or updating document: " + result);
846
    }
847
    logMetacat.debug("Finsished inserting xml document with id " + localId);
848
    
849
    return localId;
850
  }
851
  
852
  /**
853
   * Insert a data document
854
   * 
855
   * @param object
856
   * @param pid
857
   * @param sessionData
858
   * @throws ServiceFailure
859
   * @returns localId of the data object inserted
860
   */
861
  protected String insertDataObject(InputStream object, Identifier pid, 
862
          Session session) throws ServiceFailure {
863
      
864
    String username = Constants.SUBJECT_PUBLIC;
865
    String[] groupnames = null;
866
    if (session != null ) {
867
    	username = session.getSubject().getValue();
868
    	if (session.getSubjectInfo() != null) {
869
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
870
    		if (groupList != null) {
871
    			groupnames = new String[groupList.size()];
872
    			for (int i = 0; i > groupList.size(); i++ ) {
873
    				groupnames[i] = groupList.get(i).getGroupName();
874
    			}
875
    		}
876
    	}
877
    }
878
  
879
    // generate pid/localId pair for object
880
    logMetacat.debug("Generating a pid/localId mapping");
881
    IdentifierManager im = IdentifierManager.getInstance();
882
    String localId = im.generateLocalId(pid.getValue(), 1);
883
  
884
    try {
885
      logMetacat.debug("Case DATA: starting to write to disk.");
886
      if (DocumentImpl.getDataFileLockGrant(localId)) {
887
  
888
        // Save the data file to disk using "localId" as the name
889
        try {
890
          String datafilepath = PropertyService.getProperty("application.datafilepath");
891
  
892
          File dataDirectory = new File(datafilepath);
893
          dataDirectory.mkdirs();
894
  
895
          File newFile = writeStreamToFile(dataDirectory, localId, object);
896
  
897
          // TODO: Check that the file size matches SystemMetadata
898
          // long size = newFile.length();
899
          // if (size == 0) {
900
          //     throw new IOException("Uploaded file is 0 bytes!");
901
          // }
902
  
903
          // Register the file in the database (which generates an exception
904
          // if the localId is not acceptable or other untoward things happen
905
          try {
906
            logMetacat.debug("Registering document...");
907
            DocumentImpl.registerDocument(localId, "BIN", localId,
908
                    username, groupnames);
909
            logMetacat.debug("Registration step completed.");
910
            
911
          } catch (SQLException e) {
912
            //newFile.delete();
913
            logMetacat.debug("SQLE: " + e.getMessage());
914
            e.printStackTrace(System.out);
915
            throw new ServiceFailure("1190", "Registration failed: " + 
916
            		e.getMessage());
917
            
918
          } catch (AccessionNumberException e) {
919
            //newFile.delete();
920
            logMetacat.debug("ANE: " + e.getMessage());
921
            e.printStackTrace(System.out);
922
            throw new ServiceFailure("1190", "Registration failed: " + 
923
            	e.getMessage());
924
            
925
          } catch (Exception e) {
926
            //newFile.delete();
927
            logMetacat.debug("Exception: " + e.getMessage());
928
            e.printStackTrace(System.out);
929
            throw new ServiceFailure("1190", "Registration failed: " + 
930
            	e.getMessage());
931
          }
932
  
933
          logMetacat.debug("Logging the creation event.");
934
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
935
  
936
          // Schedule replication for this data file
937
          logMetacat.debug("Scheduling replication.");
938
          ForceReplicationHandler frh = new ForceReplicationHandler(
939
            localId, "create", false, null);
940
  
941
        } catch (PropertyNotFoundException e) {
942
          throw new ServiceFailure("1190", "Could not lock file for writing:" + 
943
          	e.getMessage());
944
          
945
        }
946
      }
947
      return localId;
948
    } catch (Exception e) {
949
        // Could not get a lock on the document, so we can not update the file now
950
        throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
951
    }
952
    
953
  }
954

    
955
  /**
956
   * Insert a systemMetadata document and return its localId
957
   */
958
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
959
    throws ServiceFailure {
960
    
961
  	logMetacat.debug("Starting to insert SystemMetadata...");
962
    sysmeta.setDateSysMetadataModified(new Date());
963
    logMetacat.debug("Inserting new system metadata with modified date " + 
964
        sysmeta.getDateSysMetadataModified());
965

    
966
    //insert the system metadata
967
    try {
968
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
969
    } catch (Exception e) {
970
        throw new ServiceFailure("1190", e.getMessage());
971
	}  
972
  }
973

    
974
  /**
975
   * Update a systemMetadata document
976
   * 
977
   * @param sysMeta - the system metadata object in the system to update
978
   */
979
  protected void updateSystemMetadata(SystemMetadata sysMeta)
980
    throws ServiceFailure {
981
      
982
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
983
    sysMeta.setDateSysMetadataModified(new Date());
984
    try {
985
    	HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
986
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
987
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
988
	} catch (Exception e) {
989
		throw new ServiceFailure("4862", e.getMessage());
990
	} finally {
991
		HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
992
	}
993
      
994
  }
995

    
996
  /*
997
   * Write a stream to a file
998
   * 
999
   * @param dir - the directory to write to
1000
   * @param fileName - the file name to write to
1001
   * @param data - the object bytes as an input stream
1002
   * 
1003
   * @return newFile - the new file created
1004
   * 
1005
   * @throws ServiceFailure
1006
   */
1007
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1008
    throws ServiceFailure {
1009
    
1010
    File newFile = new File(dir, fileName);
1011
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1012

    
1013
    try {
1014
        if (newFile.createNewFile()) {
1015
          // write data stream to desired file
1016
          OutputStream os = new FileOutputStream(newFile);
1017
          long length = IOUtils.copyLarge(data, os);
1018
          os.flush();
1019
          os.close();
1020
        } else {
1021
          logMetacat.debug("File creation failed, or file already exists.");
1022
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1023
        }
1024
    } catch (FileNotFoundException e) {
1025
      logMetacat.debug("FNF: " + e.getMessage());
1026
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1027
                + e.getMessage());
1028
    } catch (IOException e) {
1029
      logMetacat.debug("IOE: " + e.getMessage());
1030
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1031
                + " " + e.getMessage());
1032
    }
1033

    
1034
    return newFile;
1035
  }
1036
  
1037
}
(2-2/4)