Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000-2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: cjones $'
7
 *     '$Date: 2011-07-15 07:11:55 -0700 (Fri, 15 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
	    	throw new IdentifierNotUnique("1120", 
177
			          "The requested identifier " + pid.getValue() +
178
			          " is already used by another object and" +
179
			          "therefore can not be used for this object. Clients should choose" +
180
			          "a new identifier that is unique and retry the operation or " +
181
			          "use CN_crud.reserveIdentifier() to reserve one.");
182
    	
183
    }
184

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

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

    
216
        }
217
                    
218
      } else {
219
	        
220
	      // DEFAULT CASE: DATA (needs to be checked and completed)
221
	      localId = insertDataObject(object, pid, session);
222
      }   
223
    
224
    }
225

    
226
    // save the sysmeta
227
    try {
228
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
229
	} catch (McdbDocNotFoundException e) {
230
	    throw new ServiceFailure("1190", "Unable to save System Metadata for the object. ");
231
	}
232
    
233
    // setting the resulting identifier failed
234
    if (localId == null ) {
235
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
236
    }
237

    
238
    
239
    resultPid = pid;
240
    
241
    return resultPid;
242
  }
243

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

    
270

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

    
284
    if ( start == null ) {
285
    	start = 0;
286
    	
287
    }
288
    
289
    if ( count == null ) {
290
    	count = 1000;
291
    	
292
    }
293

    
294
    logMetacat.debug("fromDate: " + fromDate);
295
    logMetacat.debug("toDate: " + toDate);
296

    
297
    String report = el.getReport(null, null, null, null,
298
        new java.sql.Timestamp(fromDate.getTime()),
299
        new java.sql.Timestamp(toDate.getTime()), false);
300

    
301
    logMetacat.debug("report: " + report);
302

    
303
    String logEntry = "<logEntry>";
304
    String endLogEntry = "</logEntry>";
305
    int startIndex = 0;
306
    int foundIndex = report.indexOf(logEntry, startIndex);
307
    while (foundIndex != -1) {
308
      // parse out each entry
309
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
310
      String entry = report.substring(foundIndex, endEntryIndex);
311
      logMetacat.debug("entry: " + entry);
312
      startIndex = endEntryIndex + endLogEntry.length();
313
      foundIndex = report.indexOf(logEntry, startIndex);
314

    
315
      String entryId = getLogEntryField("entryid", entry);
316
      String ipAddress = getLogEntryField("ipAddress", entry);
317
      String principal = getLogEntryField("principal", entry);
318
      String docid = getLogEntryField("docid", entry);
319
      String eventS = getLogEntryField("event", entry);
320
      String dateLogged = getLogEntryField("dateLogged", entry);
321

    
322
      LogEntry le = new LogEntry();
323

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

    
347
        // skip it if the pid can't be found
348
        continue;
349
      }
350

    
351
      le.setIdentifier(identifier);
352
      le.setIpAddress(ipAddress);
353
      Calendar c = Calendar.getInstance();
354
      String year = dateLogged.substring(0, 4);
355
      String month = dateLogged.substring(5, 7);
356
      String date = dateLogged.substring(8, 10);
357
      logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
358
      c.set(new Integer(year).intValue(), new Integer(month).intValue(),
359
          new Integer(date).intValue());
360
      Date logDate = c.getTime();
361
      le.setDateLogged(logDate);
362
      NodeReference memberNode = new NodeReference();
363
      memberNode.setValue(ipAddress);
364
      le.setMemberNode(memberNode);
365
      Subject princ = new Subject();
366
      princ.setValue(principal);
367
      le.setSubject(princ);
368
      le.setUserAgent("metacat/RESTService");
369

    
370
      // event filtering?
371
      if (event == null) {
372
    	  logs.add(le);
373
      } else if (le.getEvent().equals(event)) {
374
    	  logs.add(le);
375
      }
376
    }
377
    
378
    // d1 paging
379
    int total = logs.size();
380
    if (start != null && count != null) {
381
    	int toIndex = start + count;
382
    	if (toIndex <= total) {
383
    		logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
384
    	}
385
    }
386

    
387
    log.setLogEntryList(logs);
388
    log.setStart(start);
389
    log.setCount(logs.size());
390
    log.setTotal(total);
391
    logMetacat.info("getLogRecords");
392
    return log;
393
  }
394
    
395
  /**
396
   * Return the object identified by the given object identifier
397
   * 
398
   * @param session - the Session object containing the credentials for the Subject
399
   * @param pid - the object identifier for the given object
400
   * 
401
   * TODO: The D1 Authorization API doesn't provide information on which 
402
   * authentication system the Subject belongs to, and so it's not possible to
403
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
404
   * 
405
   * @return inputStream - the input stream of the given object
406
   * 
407
   * @throws InvalidToken
408
   * @throws ServiceFailure
409
   * @throws NotAuthorized
410
   * @throws InvalidRequest
411
   * @throws NotImplemented
412
   */
413
  public InputStream get(Session session, Identifier pid) 
414
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
415
    NotImplemented, InvalidRequest {
416
    
417
    InputStream inputStream = null; // bytes to be returned
418
    handler = new MetacatHandler(new Timer());
419
    boolean allowed = false;
420
    String localId; // the metacat docid for the pid
421
    
422
    // get the local docid from Metacat
423
    try {
424
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
425
    
426
    } catch (McdbDocNotFoundException e) {
427
      throw new NotFound("1020", "The object specified by " + 
428
                         pid.getValue() +
429
                         " does not exist at this node.");
430
    }
431
    
432
    // check for authorization
433
    allowed = isAuthorized(session, pid, Permission.READ);
434
    
435
    // if the person is authorized, perform the read
436
    if (allowed) {
437
      try {
438
        inputStream = handler.read(localId);
439
      } catch (Exception e) {
440
        throw new ServiceFailure("1020", "The object specified by " + 
441
            pid.getValue() +
442
            "could not be returned due to error: " +
443
            e.getMessage());
444
      }
445
    }
446

    
447
    // if we fail to set the input stream
448
    if ( inputStream == null ) {
449
      throw new NotFound("1020", "The object specified by " + 
450
                         pid.getValue() +
451
                         "does not exist at this node.");
452
    }
453
    
454
    return inputStream;
455
  }
456

    
457
  /**
458
   * Return the system metadata for a given object
459
   * 
460
   * @param session - the Session object containing the credentials for the Subject
461
   * @param pid - the object identifier for the given object
462
   * 
463
   * @return inputStream - the input stream of the given system metadata object
464
   * 
465
   * @throws InvalidToken
466
   * @throws ServiceFailure
467
   * @throws NotAuthorized
468
   * @throws NotFound
469
   * @throws InvalidRequest
470
   * @throws NotImplemented
471
   */
472
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
473
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
474
    InvalidRequest, NotImplemented {
475

    
476
    if (!isAuthorized(session, pid, Permission.READ)) {
477
      throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
478
    }
479
    SystemMetadata systemMetadata = null;
480
    try {
481
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
482
    } catch (McdbDocNotFoundException e) {
483
      throw new NotFound("1420", "No record found for: " + pid.getValue());
484
    }
485
    
486
    return systemMetadata;
487
  }
488
   
489
  /**
490
   * Set access for a given object using the object identifier and a Subject
491
   * under a given Session.
492
   * 
493
   * @param session - the Session object containing the credentials for the Subject
494
   * @param pid - the object identifier for the given object to apply the policy
495
   * @param policy - the access policy to be applied
496
   * 
497
   * @return true if the application of the policy succeeds
498
   * @throws InvalidToken
499
   * @throws ServiceFailure
500
   * @throws NotFound
501
   * @throws NotAuthorized
502
   * @throws NotImplemented
503
   * @throws InvalidRequest
504
   */
505
  public boolean setAccessPolicy(Session session, Identifier pid, 
506
    AccessPolicy accessPolicy) 
507
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
508
    NotImplemented, InvalidRequest {
509

    
510
    boolean success = false;
511
    
512
    // get the subject
513
    Subject subject = session.getSubject();
514
    // get the system metadata
515
    String pidStr = pid.getValue();
516
    
517
    // are we allowed to do this?
518
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
519
      throw new NotAuthorized("4420", "not allowed by " + subject.getValue() + " on " + pidStr);  
520
    }
521
    
522
    SystemMetadata systemMetadata = null;
523
    try {
524
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
525
    } catch (McdbDocNotFoundException e) {
526
      throw new NotFound("4400", "No record found for: " + pid);
527
    }
528
        
529
    // set the access policy
530
    systemMetadata.setAccessPolicy(accessPolicy);
531
    
532
    // update the metadata
533
    try {
534
      IdentifierManager.getInstance().updateSystemMetadata(systemMetadata);
535
      success = true;
536
    } catch (McdbDocNotFoundException e) {
537
      throw new ServiceFailure("4430", e.getMessage());
538
    }
539

    
540
    return success;
541
  }
542
  
543
  /**
544
   * Test if the user identified by the provided token has authorization 
545
   * for operation on the specified object.
546
   * 
547
   * @param session - the Session object containing the credentials for the Subject
548
   * @param pid - The identifer of the resource for which access is being checked
549
   * @param operation - The type of operation which is being requested for the given pid
550
   *
551
   * @return true if the operation is allowed
552
   * 
553
   * @throws ServiceFailure
554
   * @throws InvalidToken
555
   * @throws NotFound
556
   * @throws NotAuthorized
557
   * @throws NotImplemented
558
   * @throws InvalidRequest
559
   */
560
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
561
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
562
    NotImplemented, InvalidRequest {
563

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

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

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

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

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

    
906
  /**
907
   * Insert a systemMetadata document and return its localId
908
   */
909
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
910
    throws ServiceFailure {
911
    
912
  	logMetacat.debug("Starting to insert SystemMetadata...");
913
    sysmeta.setDateSysMetadataModified(new Date());
914
    logMetacat.debug("Inserting new system metadata with modified date " + 
915
        sysmeta.getDateSysMetadataModified());
916

    
917
    //insert the system metadata
918
	try {
919
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
920
	  
921
	} catch (McdbDocNotFoundException e) {
922
      throw new ServiceFailure("1030", "Error inserting system metadata: " + 
923
      	e.getClass() + ": " + e.getMessage());
924
      
925
    }
926
      
927
  }
928

    
929
  /**
930
   * Update a systemMetadata document
931
   * 
932
   * @param sysMeta - the system metadata object in the system to update
933
   */
934
  protected void updateSystemMetadata(SystemMetadata sysMeta)
935
    throws ServiceFailure {
936
      
937
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
938
    sysMeta.setDateSysMetadataModified(new Date());
939
    try {
940
	    IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
941
	    
942
    } catch (McdbDocNotFoundException e) {
943
    	
944
      throw new ServiceFailure("1030", "Error updating system metadata: " + 
945
        e.getClass() + ": " + e.getMessage());
946
      
947
    }
948
      
949
  }
950

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

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

    
989
    return newFile;
990
  }
991
  
992
}
(3-3/8)