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-01 17:21:55 -0700 (Fri, 01 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.Enumeration;
38
import java.util.Hashtable;
39
import java.util.List;
40
import java.util.Timer;
41
import java.util.TimerTask;
42
import java.util.Vector;
43

    
44
import javax.servlet.http.HttpServletRequest;
45

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

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

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

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

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

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

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

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

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

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

    
223
        }
224
                    
225
      }
226
        
227

    
228
    } else {
229
        
230
      // DEFAULT CASE: DATA (needs to be checked and completed)
231
      //localId = insertDataObject(object, pid, session);
232
        
233
    }
234

    
235
    // setting the resulting identifier failed
236
    if (resultPid == null ) {
237
      throw new ServiceFailure("1190", "The Node is unable to create the object. " +
238
        "The resulting identifier was null.");
239
      
240
    }
241
    
242
    return resultPid;
243
  }
244

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

    
271

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

    
285
    logMetacat.debug("fromDate: " + fromDate);
286
    logMetacat.debug("toDate: " + toDate);
287

    
288
    String report = el.getReport(null, null, null, null,
289
        new java.sql.Timestamp(fromDate.getTime()),
290
        new java.sql.Timestamp(toDate.getTime()), false);
291

    
292
    logMetacat.debug("report: " + report);
293

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

    
306
      String entryId = getLogEntryField("entryid", entry);
307
      String ipAddress = getLogEntryField("ipAddress", entry);
308
      String principal = getLogEntryField("principal", entry);
309
      String docid = getLogEntryField("docid", entry);
310
      String eventS = getLogEntryField("event", entry);
311
      String dateLogged = getLogEntryField("dateLogged", entry);
312

    
313
      LogEntry le = new LogEntry();
314

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

    
338
        // skip it if the pid can't be found
339
        continue;
340
      }
341

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

    
361
      if (event == null) {
362
        logs.add(le);
363
      }
364

    
365
      if (event != null
366
          && e.toString().toLowerCase().trim().equals(
367
              event.toString().toLowerCase().trim())) {
368
        logs.add(le);
369
      }
370
    }
371

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

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

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

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

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

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

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

    
626
    boolean allowed = false;
627
    
628
    // get the subjects from the session
629
    List<Subject> subjects = new ArrayList<Subject>();
630
    Subject subject = session.getSubject();
631
    if (subject != null) {
632
    	subjects.add(subject);
633
    }
634
    SubjectList subjectList = session.getSubjectList();
635
    if (subjectList != null) {
636
    	List<Person> personList = subjectList.getPersonList();
637
    	if (personList != null) {
638
		    for (Person p: personList) {
639
		      subjects.add(p.getSubject());
640
		    }
641
    	}
642
    	List<Group> groupList = subjectList.getGroupList();
643
    	if (groupList != null) {
644
		    for (Group g: groupList) {
645
		      subjects.add(g.getSubject());
646
		    }
647
    	}
648
    }
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
    try {
660
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
661
	    for (AccessRule accessRule: allows) {
662
	      for (Subject s: subjects) {
663
	        if (accessRule.getSubjectList().contains(s)) {
664
	          allowed = accessRule.getPermissionList().contains(permission);
665
	          if (allowed) {
666
	        	  break;
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
  protected boolean isScienceMetadata(SystemMetadata sysmeta) {
712
    
713
    ObjectFormat objectFormat = null;
714
    boolean isScienceMetadata = false;
715
    
716
    try {
717
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getObjectFormat().getFmtid());
718
      isScienceMetadata = objectFormat.isScienceMetadata();
719
      
720
    } catch (InvalidRequest e) {
721
       logMetacat.debug("There was a problem determining if the object identified by" + 
722
         sysmeta.getIdentifier().getValue() + 
723
         " is science metadata: " + e.getMessage());
724
       
725
    } catch (ServiceFailure e) {
726
      logMetacat.debug("There was a problem determining if the object identified by" + 
727
          sysmeta.getIdentifier().getValue() + 
728
          " is science metadata: " + e.getMessage());
729
    
730
    } catch (NotFound e) {
731
      logMetacat.debug("There was a problem determining if the object identified by" + 
732
          sysmeta.getIdentifier().getValue() + 
733
          " is science metadata: " + e.getMessage());
734
    
735
    } catch (InsufficientResources e) {
736
      logMetacat.debug("There was a problem determining if the object identified by" + 
737
          sysmeta.getIdentifier().getValue() + 
738
          " is science metadata: " + e.getMessage());
739
    
740
    } catch (NotImplemented e) {
741
      logMetacat.debug("There was a problem determining if the object identified by" + 
742
          sysmeta.getIdentifier().getValue() + 
743
          " is science metadata: " + e.getMessage());
744
    
745
    }
746
    
747
    return isScienceMetadata;
748

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

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

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

    
943
  /**
944
   * Insert a systemMetadata document and return its localId
945
   */
946
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
947
    throws ServiceFailure {
948
    
949
  	logMetacat.debug("Starting to insert SystemMetadata...");
950
    sysmeta.setDateSysMetadataModified(new Date());
951
    logMetacat.debug("Inserting new system metadata with modified date " + 
952
        sysmeta.getDateSysMetadataModified());
953

    
954
    //insert the system metadata
955
	try {
956
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
957
	  
958
	} catch (McdbDocNotFoundException e) {
959
      throw new ServiceFailure("1030", "Error inserting system metadata: " + 
960
      	e.getClass() + ": " + e.getMessage());
961
      
962
    }
963
      
964
  }
965

    
966
  /**
967
   * Update a systemMetadata document
968
   * 
969
   * @param sysMeta - the system metadata object in the system to update
970
   */
971
  protected void updateSystemMetadata(SystemMetadata sysMeta)
972
    throws ServiceFailure {
973
      
974
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
975
    sysMeta.setDateSysMetadataModified(new Date());
976
    try {
977
	    IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
978
	    
979
    } catch (McdbDocNotFoundException e) {
980
    	
981
      throw new ServiceFailure("1030", "Error updating system metadata: " + 
982
        e.getClass() + ": " + e.getMessage());
983
      
984
    }
985
      
986
  }
987

    
988
  /*
989
   * Write a stream to a file
990
   * 
991
   * @param dir - the directory to write to
992
   * @param fileName - the file name to write to
993
   * @param data - the object bytes as an input stream
994
   * 
995
   * @return newFile - the new file created
996
   * 
997
   * @throws ServiceFailure
998
   */
999
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1000
    throws ServiceFailure {
1001
    
1002
    File newFile = new File(dir, fileName);
1003
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1004

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

    
1026
    return newFile;
1027
  }
1028
  
1029
}
(3-3/8)