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-07-06 12:09:55 -0700 (Wed, 06 Jul 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.FileInputStream;
28
import java.io.FileNotFoundException;
29
import java.io.FileOutputStream;
30
import java.io.IOException;
31
import java.io.InputStream;
32
import java.io.OutputStream;
33
import java.sql.SQLException;
34
import java.util.ArrayList;
35
import java.util.Calendar;
36
import java.util.Date;
37
import java.util.Hashtable;
38
import java.util.List;
39
import java.util.Timer;
40
import java.util.TimerTask;
41
import java.util.Vector;
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.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.AccessPolicy;
59
import org.dataone.service.types.AccessRule;
60
import org.dataone.service.types.Event;
61
import org.dataone.service.types.Identifier;
62
import org.dataone.service.types.Group;
63
import org.dataone.service.types.Log;
64
import org.dataone.service.types.LogEntry;
65
import org.dataone.service.types.NodeReference;
66
import org.dataone.service.types.ObjectFormat;
67
import org.dataone.service.types.Permission;
68
import org.dataone.service.types.Person;
69
import org.dataone.service.types.Session;
70
import org.dataone.service.types.Subject;
71
import org.dataone.service.types.SubjectList;
72
import org.dataone.service.types.SystemMetadata;
73

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

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

    
91
  /* the metacat URL as a string (including ending /d1 service)*/
92
  protected String metacatUrl;
93
  
94
  /* reference to the metacat handler */
95
  private MetacatHandler handler;
96
  
97
  /* parameters set in the incoming request */
98
  private Hashtable<String, String[]> params;
99

    
100
  /**
101
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
102
   * 
103
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
104
   */
105
  public D1NodeService() {
106
  	this.metacatUrl = "";
107
  	
108
    try {
109
	    this.metacatUrl = SystemUtil.getContextURL() + 
110
	    PropertyService.getProperty("dataone.serviceName");
111
    } catch (PropertyNotFoundException e) {
112
      throw new RuntimeException("Error getting the servlet url in D1NodeService: " + 
113
        	e.getMessage());
114

    
115
    }
116
    
117
  }
118
  
119
  /**
120
   * Adds a new object to the Node, where the object is either a data 
121
   * object or a science metadata object. This method is called by clients 
122
   * to create new data objects on Member Nodes or internally for Coordinating
123
   * Nodes
124
   * 
125
   * @param session - the Session object containing the credentials for the Subject
126
   * @param pid - The object identifier to be created
127
   * @param object - the object bytes
128
   * @param sysmeta - the system metadata that describes the object  
129
   * 
130
   * @return pid - the object identifier created
131
   * 
132
   * @throws InvalidToken
133
   * @throws ServiceFailure
134
   * @throws NotAuthorized
135
   * @throws IdentifierNotUnique
136
   * @throws UnsupportedType
137
   * @throws InsufficientResources
138
   * @throws InvalidSystemMetadata
139
   * @throws NotImplemented
140
   * @throws InvalidRequest
141
   */
142
  public Identifier create(Session session, Identifier pid, InputStream object,
143
    SystemMetadata sysmeta) 
144
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
145
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
146
    NotImplemented, InvalidRequest {
147

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

    
173
    logMetacat.debug("Checking if identifier exists...");
174
    // Check that the identifier does not already exist
175
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
176
    	// check if we reserved the id
177
    	boolean reserved = IdentifierManager.getInstance().hasReservation(pid, session);
178
    	// throw an exception if not
179
    	if (!reserved) {
180
	    	throw new IdentifierNotUnique("1120", 
181
			          "The requested identifier " + pid.getValue() +
182
			          " is already used by another object and" +
183
			          "therefore can not be used for this object. Clients should choose" +
184
			          "a new identifier that is unique and retry the operation or " +
185
			          "use CN_crud.reserveIdentifier() to reserve one.");
186
    	}
187
    }
188

    
189
    // check for permission
190
    try {
191
      allowed = isAuthorized(session, pid, Permission.WRITE);
192
            
193
    } catch (NotFound e) {
194
      // The identifier doesn't exist, writing should be fine.
195
      allowed = true;
196
      
197
    }
198
    
199
    // we have the go ahead
200
    if ( allowed ) {
201
      
202
      // Science metadata (XML) or science data object?
203
      // TODO: there are cases where certain object formats are science metadata
204
      // but are not XML (netCDF ...).  Handle this.
205
      if ( isScienceMetadata(sysmeta) ) {
206
        
207
        // CASE METADATA:
208
      	String objectAsXML = "";
209
        try {
210
	        objectAsXML = IOUtils.toString(object, "UTF-8");
211
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
212
	        //localId = im.getLocalId(pid.getValue());
213

    
214
        } catch (IOException e) {
215
        	String msg = "The Node is unable to create the object. " +
216
          "There was a problem converting the object to XML";
217
        	logMetacat.info(msg);
218
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
219

    
220
        }
221
                    
222
      } else {
223
	        
224
	      // DEFAULT CASE: DATA (needs to be checked and completed)
225
	      localId = insertDataObject(object, pid, session);
226
      }   
227
    
228
    }
229
    
230
    // setting the resulting identifier failed
231
    if (localId == null ) {
232
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
233
    }
234
    
235
    resultPid = pid;
236
    
237
    return resultPid;
238
  }
239

    
240
  /**
241
   * Return the log records associated with a given event between the start and 
242
   * end dates listed given a particular Subject listed in the Session
243
   * 
244
   * @param session - the Session object containing the credentials for the Subject
245
   * @param fromDate - the start date of the desired log records
246
   * @param toDate - the end date of the desired log records
247
   * @param event - restrict log records of a specific event type
248
   * @param start - zero based offset from the first record in the 
249
   *                set of matching log records. Used to assist with 
250
   *                paging the response.
251
   * @param count - maximum number of log records to return in the response. 
252
   *                Used to assist with paging the response.
253
   * 
254
   * @return the desired log records
255
   * 
256
   * @throws InvalidToken
257
   * @throws ServiceFailure
258
   * @throws NotAuthorized
259
   * @throws InvalidRequest
260
   * @throws NotImplemented
261
   */
262
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
263
      Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
264
      NotAuthorized, InvalidRequest, NotImplemented {
265

    
266

    
267
    Log log = new Log();
268
    Vector<LogEntry> logs = new Vector<LogEntry>();
269
    IdentifierManager im = IdentifierManager.getInstance();
270
    EventLog el = EventLog.getInstance();
271
    if (fromDate == null) {
272
      logMetacat.debug("setting fromdate from null");
273
      fromDate = new Date(1);
274
    }
275
    if (toDate == null) {
276
      logMetacat.debug("setting todate from null");
277
      toDate = new Date();
278
    }
279

    
280
    logMetacat.debug("fromDate: " + fromDate);
281
    logMetacat.debug("toDate: " + toDate);
282

    
283
    String report = el.getReport(null, null, null, null,
284
        new java.sql.Timestamp(fromDate.getTime()),
285
        new java.sql.Timestamp(toDate.getTime()), false);
286

    
287
    logMetacat.debug("report: " + report);
288

    
289
    String logEntry = "<logEntry>";
290
    String endLogEntry = "</logEntry>";
291
    int startIndex = 0;
292
    int foundIndex = report.indexOf(logEntry, startIndex);
293
    while (foundIndex != -1) {
294
      // parse out each entry
295
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
296
      String entry = report.substring(foundIndex, endEntryIndex);
297
      logMetacat.debug("entry: " + entry);
298
      startIndex = endEntryIndex + endLogEntry.length();
299
      foundIndex = report.indexOf(logEntry, startIndex);
300

    
301
      String entryId = getLogEntryField("entryid", entry);
302
      String ipAddress = getLogEntryField("ipAddress", entry);
303
      String principal = getLogEntryField("principal", entry);
304
      String docid = getLogEntryField("docid", entry);
305
      String eventS = getLogEntryField("event", entry);
306
      String dateLogged = getLogEntryField("dateLogged", entry);
307

    
308
      LogEntry le = new LogEntry();
309

    
310
      Event e = Event.convert(eventS);
311
      if (e == null) { // skip any events that are not Dataone Crud events
312
        continue;
313
      }
314
      le.setEvent(e);
315
      Identifier entryid = new Identifier();
316
      entryid.setValue(entryId);
317
      le.setEntryId(entryid);
318
      Identifier identifier = new Identifier();
319
      try {
320
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
321
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
322
          continue;
323
        }
324
        docid = docid.substring(0, docid.lastIndexOf("."));
325
        identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
326
      } catch (Exception ex) { 
327
        // try to get the pid, if that doesn't
328
        // work, just use the local id
329
        // throw new ServiceFailure("1030",
330
        // "Error getting pid for localId " +
331
        // docid + ": " + ex.getMessage());\
332

    
333
        // skip it if the pid can't be found
334
        continue;
335
      }
336

    
337
      le.setIdentifier(identifier);
338
      le.setIpAddress(ipAddress);
339
      Calendar c = Calendar.getInstance();
340
      String year = dateLogged.substring(0, 4);
341
      String month = dateLogged.substring(5, 7);
342
      String date = dateLogged.substring(8, 10);
343
      logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
344
      c.set(new Integer(year).intValue(), new Integer(month).intValue(),
345
          new Integer(date).intValue());
346
      Date logDate = c.getTime();
347
      le.setDateLogged(logDate);
348
      NodeReference memberNode = new NodeReference();
349
      memberNode.setValue(ipAddress);
350
      le.setMemberNode(memberNode);
351
      Subject princ = new Subject();
352
      princ.setValue(principal);
353
      le.setSubject(princ);
354
      le.setUserAgent("metacat/RESTService");
355

    
356
      if (event == null) {
357
        logs.add(le);
358
      }
359

    
360
      if (event != null
361
          && e.toString().toLowerCase().trim().equals(
362
              event.toString().toLowerCase().trim())) {
363
        logs.add(le);
364
      }
365
    }
366

    
367
    log.setLogEntryList(logs);
368
    logMetacat.info("getLogRecords");
369
    return log;
370
  }
371
    
372
  /**
373
   * Return the object identified by the given object identifier
374
   * 
375
   * @param session - the Session object containing the credentials for the Subject
376
   * @param pid - the object identifier for the given object
377
   * 
378
   * TODO: The D1 Authorization API doesn't provide information on which 
379
   * authentication system the Subject belongs to, and so it's not possible to
380
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
381
   * 
382
   * @return inputStream - the input stream of the given object
383
   * 
384
   * @throws InvalidToken
385
   * @throws ServiceFailure
386
   * @throws NotAuthorized
387
   * @throws InvalidRequest
388
   * @throws NotImplemented
389
   */
390
  public InputStream get(Session session, Identifier pid) 
391
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
392
    NotImplemented, InvalidRequest {
393
    
394
    InputStream inputStream = null; // bytes to be returned
395
    handler = new MetacatHandler(new Timer());
396
    boolean allowed = false;
397
    String localId; // the metacat docid for the pid
398
    
399
    // get the local docid from Metacat
400
    try {
401
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
402
    
403
    } catch (McdbDocNotFoundException e) {
404
      throw new NotFound("1020", "The object specified by " + 
405
                         pid.getValue() +
406
                         " does not exist at this node.");
407
    }
408
    
409
    // check for authorization
410
    allowed = isAuthorized(session, pid, Permission.READ);
411
    
412
    // if the person is authorized, perform the read
413
    if ( allowed ) {
414
      
415
      // get the object bytes
416
      // TODO: stream to file to stream conversion throughout Metacat needs to
417
      // be resolved
418
      File tmpDir;
419
      try
420
      {
421
          tmpDir = new File(PropertyService.getProperty("application.tempDir"));
422
      }
423
      catch(PropertyNotFoundException pnfe)
424
      {
425
          logMetacat.error("D1NodeService.get(): " +
426
                  "application.tmpDir not found.  Using /tmp instead.");
427
          tmpDir = new File("/tmp");
428
      }
429
      
430
      Date d = new Date();
431
      final File outputFile = new File(tmpDir, "metacat.output." + d.getTime());
432
      FileOutputStream dataSink;
433
      try {
434
        dataSink = new FileOutputStream(outputFile);
435
        handler.read(localId);
436

    
437
      } catch (FileNotFoundException e) {
438
        throw new ServiceFailure("1020", "The object specified by " + 
439
            pid.getValue() +
440
            "could not be returned due to a file read error: " +
441
            e.getMessage());
442
        
443
      } catch (PropertyNotFoundException e) {
444
        throw new ServiceFailure("1020", "The object specified by " + 
445
            pid.getValue() +
446
            "could not be returned due to an internal error: " +
447
            e.getMessage());
448
        
449
      } catch (ClassNotFoundException e) {
450
        throw new ServiceFailure("1020", "The object specified by " + 
451
            pid.getValue() +
452
            "could not be returned due to an internal error: " +
453
            e.getMessage());
454
        
455
      } catch (IOException e) {
456
        throw new ServiceFailure("1020", "The object specified by " + 
457
            pid.getValue() +
458
            "could not be returned due to a file read error: " +
459
            e.getMessage());
460
        
461
      } catch (SQLException e) {
462
        throw new ServiceFailure("1020", "The object specified by " + 
463
            pid.getValue() +
464
            "could not be returned due to a database error: " +
465
            e.getMessage());
466
        
467
      } catch (McdbException e) {
468
        throw new ServiceFailure("1020", "The object specified by " + 
469
            pid.getValue() +
470
            "could not be returned due to database error: " +
471
            e.getMessage());
472
        
473
      } catch (ParseLSIDException e) {
474
        throw new ServiceFailure("1020", "The object specified by " + 
475
            pid.getValue() +
476
            "could not be returned due to a parse error: " +
477
            e.getMessage());
478
        
479
      }
480
      
481
      //set a timer to clean up the temp files
482
      Timer t = new Timer();
483
      TimerTask tt = new TimerTask() {
484
          @Override
485
          public void run()
486
          {
487
              outputFile.delete();
488
          }
489
      };
490
      t.schedule(tt, 20000); //schedule after 20 secs
491
      
492
      try {
493
        inputStream = new FileInputStream(outputFile);
494
      } catch (FileNotFoundException e) {
495
        throw new ServiceFailure("1020", "The object specified by " + 
496
          pid.getValue() +
497
          "could not be returned due to a file read error: " +
498
          e.getMessage());
499
        
500
      }      
501
      
502
    }
503

    
504
    // if we fail to set the input stream
505
    if ( inputStream == null ) {
506
      throw new NotFound("1020", "The object specified by " + 
507
                         pid.getValue() +
508
                         "does not exist at this node.");
509
    }
510
    
511
    return inputStream;
512
  }
513

    
514
  /**
515
   * Return the system metadata for a given object
516
   * 
517
   * @param session - the Session object containing the credentials for the Subject
518
   * @param pid - the object identifier for the given object
519
   * 
520
   * @return inputStream - the input stream of the given system metadata object
521
   * 
522
   * @throws InvalidToken
523
   * @throws ServiceFailure
524
   * @throws NotAuthorized
525
   * @throws NotFound
526
   * @throws InvalidRequest
527
   * @throws NotImplemented
528
   */
529
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
530
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
531
    InvalidRequest, NotImplemented {
532

    
533
    if (!isAuthorized(session, pid, Permission.READ)) {
534
      throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
535
    }
536
    SystemMetadata systemMetadata = null;
537
    try {
538
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
539
    } catch (McdbDocNotFoundException e) {
540
      throw new NotFound("1420", "No record found for: " + pid.getValue());
541
    }
542
    
543
    return systemMetadata;
544
  }
545
   
546
  /**
547
   * Set access for a given object using the object identifier and a Subject
548
   * under a given Session.
549
   * 
550
   * @param session - the Session object containing the credentials for the Subject
551
   * @param pid - the object identifier for the given object to apply the policy
552
   * @param policy - the access policy to be applied
553
   * 
554
   * @return true if the application of the policy succeeds
555
   * @throws InvalidToken
556
   * @throws ServiceFailure
557
   * @throws NotFound
558
   * @throws NotAuthorized
559
   * @throws NotImplemented
560
   * @throws InvalidRequest
561
   */
562
  public boolean setAccessPolicy(Session session, Identifier pid, 
563
    AccessPolicy accessPolicy) 
564
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
565
    NotImplemented, InvalidRequest {
566

    
567
    boolean success = false;
568
    
569
    // get the subject
570
    Subject subject = session.getSubject();
571
    // get the system metadata
572
    String pidStr = pid.getValue();
573
    
574
    // are we allowed to do this?
575
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
576
      throw new NotAuthorized("4420", "not allowed by " + subject.getValue() + " on " + pidStr);  
577
    }
578
    
579
    SystemMetadata systemMetadata = null;
580
    try {
581
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
582
    } catch (McdbDocNotFoundException e) {
583
      throw new NotFound("4400", "No record found for: " + pid);
584
    }
585
        
586
    // set the access policy
587
    systemMetadata.setAccessPolicy(accessPolicy);
588
    
589
    // update the metadata
590
    try {
591
      IdentifierManager.getInstance().updateSystemMetadata(systemMetadata);
592
      success = true;
593
    } catch (McdbDocNotFoundException e) {
594
      throw new ServiceFailure("4430", e.getMessage());
595
    }
596

    
597
    return success;
598
  }
599
  
600
  /**
601
   * Test if the user identified by the provided token has authorization 
602
   * for operation on the specified object.
603
   * 
604
   * @param session - the Session object containing the credentials for the Subject
605
   * @param pid - The identifer of the resource for which access is being checked
606
   * @param operation - The type of operation which is being requested for the given pid
607
   *
608
   * @return true if the operation is allowed
609
   * 
610
   * @throws ServiceFailure
611
   * @throws InvalidToken
612
   * @throws NotFound
613
   * @throws NotAuthorized
614
   * @throws NotImplemented
615
   * @throws InvalidRequest
616
   */
617
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
618
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
619
    NotImplemented, InvalidRequest {
620

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

    
717
  /** 
718
   * Determine if a given object should be treated as an XML science metadata
719
   * object. 
720
   * 
721
   * @param sysmeta - the SystemMetadata describing the object
722
   * @return true if the object should be treated as science metadata
723
   */
724
  protected boolean isScienceMetadata(SystemMetadata sysmeta) {
725
    
726
    ObjectFormat objectFormat = null;
727
    boolean isScienceMetadata = false;
728
    
729
    try {
730
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getObjectFormat().getFmtid());
731
      isScienceMetadata = objectFormat.isScienceMetadata();
732
      
733
    } catch (InvalidRequest 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 (ServiceFailure 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 (NotFound 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
    } catch (InsufficientResources e) {
749
      logMetacat.debug("There was a problem determining if the object identified by" + 
750
          sysmeta.getIdentifier().getValue() + 
751
          " is science metadata: " + e.getMessage());
752
    
753
    } catch (NotImplemented e) {
754
      logMetacat.debug("There was a problem determining if the object identified by" + 
755
          sysmeta.getIdentifier().getValue() + 
756
          " is science metadata: " + e.getMessage());
757
    
758
    }
759
    
760
    return isScienceMetadata;
761

    
762
  }
763
  
764
  /**
765
   * Insert or update an XML document into Metacat
766
   * 
767
   * @param xml - the XML document to insert or update
768
   * @param pid - the identifier to be used for the resulting object
769
   * 
770
   * @return localId - the resulting docid of the document created or updated
771
   * 
772
   */
773
  protected String insertOrUpdateDocument(String xml, Identifier pid, 
774
    Session session, String insertOrUpdate) 
775
    throws ServiceFailure {
776
    
777
  	logMetacat.debug("Starting to insert xml document...");
778
    IdentifierManager im = IdentifierManager.getInstance();
779

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

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

    
963
  /**
964
   * Insert a systemMetadata document and return its localId
965
   */
966
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
967
    throws ServiceFailure {
968
    
969
  	logMetacat.debug("Starting to insert SystemMetadata...");
970
    sysmeta.setDateSysMetadataModified(new Date());
971
    logMetacat.debug("Inserting new system metadata with modified date " + 
972
        sysmeta.getDateSysMetadataModified());
973

    
974
    //insert the system metadata
975
	try {
976
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
977
	  
978
	} catch (McdbDocNotFoundException e) {
979
      throw new ServiceFailure("1030", "Error inserting system metadata: " + 
980
      	e.getClass() + ": " + e.getMessage());
981
      
982
    }
983
      
984
  }
985

    
986
  /**
987
   * Update a systemMetadata document
988
   * 
989
   * @param sysMeta - the system metadata object in the system to update
990
   */
991
  protected void updateSystemMetadata(SystemMetadata sysMeta)
992
    throws ServiceFailure {
993
      
994
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
995
    sysMeta.setDateSysMetadataModified(new Date());
996
    try {
997
	    IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
998
	    
999
    } catch (McdbDocNotFoundException e) {
1000
    	
1001
      throw new ServiceFailure("1030", "Error updating system metadata: " + 
1002
        e.getClass() + ": " + e.getMessage());
1003
      
1004
    }
1005
      
1006
  }
1007

    
1008
  /*
1009
   * Write a stream to a file
1010
   * 
1011
   * @param dir - the directory to write to
1012
   * @param fileName - the file name to write to
1013
   * @param data - the object bytes as an input stream
1014
   * 
1015
   * @return newFile - the new file created
1016
   * 
1017
   * @throws ServiceFailure
1018
   */
1019
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1020
    throws ServiceFailure {
1021
    
1022
    File newFile = new File(dir, fileName);
1023
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1024

    
1025
    try {
1026
        if (newFile.createNewFile()) {
1027
          // write data stream to desired file
1028
          OutputStream os = new FileOutputStream(newFile);
1029
          long length = IOUtils.copyLarge(data, os);
1030
          os.flush();
1031
          os.close();
1032
        } else {
1033
          logMetacat.debug("File creation failed, or file already exists.");
1034
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1035
        }
1036
    } catch (FileNotFoundException e) {
1037
      logMetacat.debug("FNF: " + e.getMessage());
1038
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1039
                + e.getMessage());
1040
    } catch (IOException e) {
1041
      logMetacat.debug("IOE: " + e.getMessage());
1042
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1043
                + " " + e.getMessage());
1044
    }
1045

    
1046
    return newFile;
1047
  }
1048
  
1049
}
(3-3/8)