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-09-12 09:32:28 -0700 (Mon, 12 Sep 2011) $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23

    
24
package edu.ucsb.nceas.metacat.dataone;
25

    
26
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32
import java.sql.SQLException;
33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.Date;
36
import java.util.Hashtable;
37
import java.util.List;
38
import java.util.Timer;
39
import java.util.Vector;
40

    
41

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

    
72
import edu.ucsb.nceas.metacat.AccessionNumberException;
73
import edu.ucsb.nceas.metacat.DocumentImpl;
74
import edu.ucsb.nceas.metacat.EventLog;
75
import edu.ucsb.nceas.metacat.IdentifierManager;
76
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
77
import edu.ucsb.nceas.metacat.MetacatHandler;
78
import edu.ucsb.nceas.metacat.properties.PropertyService;
79
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
80
import edu.ucsb.nceas.metacat.util.SystemUtil;
81
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
82

    
83
public abstract class D1NodeService {
84
  
85
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
86

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

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

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

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

    
169
    logMetacat.debug("Checking if identifier exists...");
170
    // Check that the identifier does not already exist
171
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
172
	    	throw new IdentifierNotUnique("1120", 
173
			          "The requested identifier " + pid.getValue() +
174
			          " is already used by another object and" +
175
			          "therefore can not be used for this object. Clients should choose" +
176
			          "a new identifier that is unique and retry the operation or " +
177
			          "use CN_crud.reserveIdentifier() to reserve one.");
178
    	
179
    }
180

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

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

    
212
        }
213
                    
214
      } else {
215
	        
216
	      // DEFAULT CASE: DATA (needs to be checked and completed)
217
	      localId = insertDataObject(object, pid, session);
218
      }   
219
    
220
    }
221

    
222
    // save the sysmeta
223
    try {
224
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
225
	} catch (McdbDocNotFoundException e) {
226
	    throw new ServiceFailure("1190", "Unable to save System Metadata for the object. ");
227
	}
228
    
229
    // setting the resulting identifier failed
230
    if (localId == null ) {
231
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
232
    }
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
    List<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
    if ( start == null ) {
281
    	start = 0;
282
    	
283
    }
284
    
285
    if ( count == null ) {
286
    	count = 1000;
287
    	
288
    }
289

    
290
    logMetacat.debug("fromDate: " + fromDate);
291
    logMetacat.debug("toDate: " + toDate);
292

    
293
    String report = el.getReport(null, null, null, null,
294
        new java.sql.Timestamp(fromDate.getTime()),
295
        new java.sql.Timestamp(toDate.getTime()), false);
296

    
297
    logMetacat.debug("report: " + report);
298

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

    
311
      String entryId = getLogEntryField("entryid", entry);
312
      String ipAddress = getLogEntryField("ipAddress", entry);
313
      String principal = getLogEntryField("principal", entry);
314
      String docid = getLogEntryField("docid", entry);
315
      String eventS = getLogEntryField("event", entry);
316
      String dateLogged = getLogEntryField("dateLogged", entry);
317

    
318
      LogEntry le = new LogEntry();
319

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

    
343
        // skip it if the pid can't be found
344
        continue;
345
      }
346

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

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

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

    
443
    // if we fail to set the input stream
444
    if ( inputStream == null ) {
445
      throw new NotFound("1020", "The object specified by " + 
446
                         pid.getValue() +
447
                         "does not exist at this node.");
448
    }
449
    
450
	// log the read event
451
    String principal = Constants.PUBLIC_SUBJECT;
452
    if (session.getSubject() != null) {
453
    	principal = session.getSubject().getValue();
454
    }
455
    EventLog.getInstance().log(null, principal, localId, "read");
456
    
457
    return inputStream;
458
  }
459

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

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

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

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

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

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

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

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

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

    
914
  /**
915
   * Insert a systemMetadata document and return its localId
916
   */
917
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
918
    throws ServiceFailure {
919
    
920
  	logMetacat.debug("Starting to insert SystemMetadata...");
921
    sysmeta.setDateSysMetadataModified(new Date());
922
    logMetacat.debug("Inserting new system metadata with modified date " + 
923
        sysmeta.getDateSysMetadataModified());
924

    
925
    //insert the system metadata
926
	try {
927
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
928
	  
929
	} catch (McdbDocNotFoundException e) {
930
      throw new ServiceFailure("1030", "Error inserting system metadata: " + 
931
      	e.getClass() + ": " + e.getMessage());
932
      
933
    }
934
      
935
  }
936

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

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

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

    
997
    return newFile;
998
  }
999
  
1000
}
(3-3/7)