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-11-02 21:58:31 -0700 (Wed, 02 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
    // TODO: this probably needs to be refined more
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
    // verify checksum, only if we can reset the inputstream
203
    if (object.markSupported()) {
204
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
205
	    String checksumValue = sysmeta.getChecksum().getValue();
206
	    try {
207
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
208
			// it's very important that we don't consume the stream
209
			object.reset();
210
			if (!computedChecksumValue.equals(checksumValue)) {
211
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
212
			}
213
		} catch (Exception e) {
214
			String msg = "Error verifying checksum values";
215
	      	logMetacat.error(msg, e);
216
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
217
		}
218
    } else {
219
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
220
    }
221
    	
222
    // we have the go ahead
223
    if ( allowed ) {
224
      
225
      // Science metadata (XML) or science data object?
226
      // TODO: there are cases where certain object formats are science metadata
227
      // but are not XML (netCDF ...).  Handle this.
228
      if ( isScienceMetadata(sysmeta) ) {
229
        
230
        // CASE METADATA:
231
      	String objectAsXML = "";
232
        try {
233
	        objectAsXML = IOUtils.toString(object, "UTF-8");
234
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
235
	        //localId = im.getLocalId(pid.getValue());
236

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

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

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

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

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

    
299

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

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

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

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

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

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

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

    
352
      LogEntry le = new LogEntry();
353

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

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

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

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

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

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

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

    
552
    boolean allowed = false;
553
    
554
    // get the subjects from the session
555
    List<Subject> subjects = new ArrayList<Subject>();
556
    if (session != null) {
557
	    Subject subject = session.getSubject();
558
	    if (subject != null) {
559
	    	subjects.add(subject);
560
	    }
561
	    SubjectInfo subjecInfo = session.getSubjectInfo();
562
	    if (subjecInfo != null) {
563
	    	List<Person> personList = subjecInfo.getPersonList();
564
	    	if (personList != null) {
565
			    for (Person p: personList) {
566
			      subjects.add(p.getSubject());
567
			    }
568
	    	}
569
	    	List<Group> groupList = subjecInfo.getGroupList();
570
	    	if (groupList != null) {
571
			    for (Group g: groupList) {
572
			      subjects.add(g.getSubject());
573
			    }
574
	    	}
575
	    }
576
    }
577
    
578
    // add public subject
579
    Subject publicSubject = new Subject();
580
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
581
    subjects.add(publicSubject);
582
    
583
    // get the system metadata
584
    String pidStr = pid.getValue();
585
    SystemMetadata systemMetadata = null;
586
    try {
587
        HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
588
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
589
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
590

    
591
    } catch (Exception e) {
592
        // convert Hazelcast RuntimeException to NotFound
593
        logMetacat.error("An error occurred while getting system metadata for identifier " +
594
            pid.getValue() + ". The error message was: " + e.getMessage());
595
        throw new NotFound("1800", "No record found for " + pidStr);
596
        
597
    } finally {
598
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
599
        
600
    }
601
    
602
    // throw not found if it was not found
603
    if (systemMetadata == null) {
604
    	throw new NotFound("1800", "No system metadata could be founnd for given PID: " + pid);
605
    }
606
	    
607
    // do we own it?
608
    for (Subject s: subjects) {
609
    	allowed = systemMetadata.getRightsHolder().getValue().equals(s.getValue());
610
    	if (allowed) {
611
    		return allowed;
612
    	}
613
    }    
614
    
615
    // otherwise check the access rules
616
    try {
617
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
618
	    search: // label break
619
	    for (AccessRule accessRule: allows) {
620
	      for (Subject s: subjects) {
621
	        //if (accessRule.getSubjectList().contains(s)) {
622
        	for (Subject ruleSubject: accessRule.getSubjectList()) {
623
        		if (ruleSubject.getValue().equals(s.getValue())) {
624
		          allowed = accessRule.getPermissionList().contains(permission);
625
		          if (allowed) {
626
		        	  break search; //label break
627
		          }
628
        		}
629
	        }
630
	      }
631
	    }
632
    } catch (Exception e) {
633
    	// catch all for errors - safe side should be to deny the access
634
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
635
		allowed = false;
636
	}
637
    
638
    // throw or return?
639
    if (!allowed) {
640
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
641
    }
642
    
643
    return allowed;
644
    
645
  }
646
  
647
  /*
648
   * parse a logEntry and get the relevant field from it
649
   * 
650
   * @param fieldname
651
   * @param entry
652
   * @return
653
   */
654
  private String getLogEntryField(String fieldname, String entry) {
655
    String begin = "<" + fieldname + ">";
656
    String end = "</" + fieldname + ">";
657
    // logMetacat.debug("looking for " + begin + " and " + end +
658
    // " in entry " + entry);
659
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
660
        .indexOf(end));
661
    logMetacat.debug("entry " + fieldname + " : " + s);
662
    return s;
663
  }
664

    
665
  /** 
666
   * Determine if a given object should be treated as an XML science metadata
667
   * object. 
668
   * 
669
   * @param sysmeta - the SystemMetadata describing the object
670
   * @return true if the object should be treated as science metadata
671
   */
672
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
673
    
674
    ObjectFormat objectFormat = null;
675
    boolean isScienceMetadata = false;
676
    
677
    try {
678
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
679
      if ( objectFormat.getFormatType().equals("METADATA") ) {
680
      	isScienceMetadata = true;
681
      	
682
      }
683
      
684
    } catch (InvalidRequest e) {
685
       logMetacat.debug("There was a problem determining if the object identified by" + 
686
         sysmeta.getIdentifier().getValue() + 
687
         " is science metadata: " + e.getMessage());
688
       
689
    } catch (ServiceFailure e) {
690
      logMetacat.debug("There was a problem determining if the object identified by" + 
691
          sysmeta.getIdentifier().getValue() + 
692
          " is science metadata: " + e.getMessage());
693
    
694
    } catch (NotFound e) {
695
      logMetacat.debug("There was a problem determining if the object identified by" + 
696
          sysmeta.getIdentifier().getValue() + 
697
          " is science metadata: " + e.getMessage());
698
    
699
    } catch (InsufficientResources e) {
700
      logMetacat.debug("There was a problem determining if the object identified by" + 
701
          sysmeta.getIdentifier().getValue() + 
702
          " is science metadata: " + e.getMessage());
703
    
704
    } catch (NotImplemented e) {
705
      logMetacat.debug("There was a problem determining if the object identified by" + 
706
          sysmeta.getIdentifier().getValue() + 
707
          " is science metadata: " + e.getMessage());
708
    
709
    }
710
    
711
    return isScienceMetadata;
712

    
713
  }
714
  
715
  /**
716
   * Insert or update an XML document into Metacat
717
   * 
718
   * @param xml - the XML document to insert or update
719
   * @param pid - the identifier to be used for the resulting object
720
   * 
721
   * @return localId - the resulting docid of the document created or updated
722
   * 
723
   */
724
  protected String insertOrUpdateDocument(String xml, Identifier pid, 
725
    Session session, String insertOrUpdate) 
726
    throws ServiceFailure {
727
    
728
  	logMetacat.debug("Starting to insert xml document...");
729
    IdentifierManager im = IdentifierManager.getInstance();
730

    
731
    // generate pid/localId pair for sysmeta
732
    String localId = null;
733
    
734
    if(insertOrUpdate.equals("insert")) {
735
      localId = im.generateLocalId(pid.getValue(), 1);
736
      
737
    } else {
738
      //localid should already exist in the identifier table, so just find it
739
      try {
740
        logMetacat.debug("Updating pid " + pid.getValue());
741
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
742
        
743
        localId = im.getLocalId(pid.getValue());
744
        
745
        logMetacat.debug("localId: " + localId);
746
        //increment the revision
747
        String docid = localId.substring(0, localId.lastIndexOf("."));
748
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
749
        int rev = new Integer(revS).intValue();
750
        rev++;
751
        docid = docid + "." + rev;
752
        localId = docid;
753
        logMetacat.debug("incremented localId: " + localId);
754
      
755
      } catch(McdbDocNotFoundException e) {
756
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
757
            "pid " + pid.getValue() + 
758
            " should have been in the identifier table, but it wasn't: " + 
759
            e.getMessage());
760
      
761
      }
762
      
763
    }
764

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

    
916
  /**
917
   * Insert a systemMetadata document and return its localId
918
   */
919
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
920
      throws ServiceFailure {
921
      
922
  	  logMetacat.debug("Starting to insert SystemMetadata...");
923
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
924
      logMetacat.debug("Inserting new system metadata with modified date " + 
925
          sysmeta.getDateSysMetadataModified());
926
      
927
      //insert the system metadata
928
      try {
929
        // note: the calling subclass handles the map hazelcast lock/unlock
930
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
931
      	
932
      } catch (Exception e) {
933
          throw new ServiceFailure("1190", e.getMessage());
934
          
935
	    }  
936
  }
937

    
938
  /**
939
   * Update a systemMetadata document
940
   * 
941
   * @param sysMeta - the system metadata object in the system to update
942
   */
943
  protected void updateSystemMetadata(SystemMetadata sysMeta)
944
    throws ServiceFailure {
945
      
946
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
947
    sysMeta.setDateSysMetadataModified(new Date());
948
    try {
949
    	HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
950
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
951
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
952
	} catch (Exception e) {
953
		throw new ServiceFailure("4862", e.getMessage());
954
	} finally {
955
		HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
956
	}
957
      
958
  }
959

    
960
  /*
961
   * Write a stream to a file
962
   * 
963
   * @param dir - the directory to write to
964
   * @param fileName - the file name to write to
965
   * @param data - the object bytes as an input stream
966
   * 
967
   * @return newFile - the new file created
968
   * 
969
   * @throws ServiceFailure
970
   */
971
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
972
    throws ServiceFailure {
973
    
974
    File newFile = new File(dir, fileName);
975
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
976

    
977
    try {
978
        if (newFile.createNewFile()) {
979
          // write data stream to desired file
980
          OutputStream os = new FileOutputStream(newFile);
981
          long length = IOUtils.copyLarge(data, os);
982
          os.flush();
983
          os.close();
984
        } else {
985
          logMetacat.debug("File creation failed, or file already exists.");
986
          throw new ServiceFailure("1190", "File already exists: " + fileName);
987
        }
988
    } catch (FileNotFoundException e) {
989
      logMetacat.debug("FNF: " + e.getMessage());
990
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
991
                + e.getMessage());
992
    } catch (IOException e) {
993
      logMetacat.debug("IOE: " + e.getMessage());
994
      throw new ServiceFailure("1190", "File was not written: " + fileName 
995
                + " " + e.getMessage());
996
    }
997

    
998
    return newFile;
999
  }
1000
  
1001
}
(2-2/4)