Project

General

Profile

1 6174 cjones
/**
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$'
7
 *     '$Date$'
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 6226 cjones
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30 6174 cjones
import java.io.InputStream;
31 6241 cjones
import java.io.OutputStream;
32 6226 cjones
import java.sql.SQLException;
33 6225 leinfelder
import java.util.ArrayList;
34 6186 leinfelder
import java.util.Calendar;
35 6174 cjones
import java.util.Date;
36 6226 cjones
import java.util.Hashtable;
37 6194 leinfelder
import java.util.List;
38 6226 cjones
import java.util.Timer;
39 6186 leinfelder
import java.util.Vector;
40 6174 cjones
41 6226 cjones
42 6241 cjones
import org.apache.commons.io.IOUtils;
43 6186 leinfelder
import org.apache.log4j.Logger;
44 6241 cjones
import org.dataone.client.ObjectFormatCache;
45 6371 leinfelder
import org.dataone.service.util.Constants;
46 6241 cjones
import org.dataone.service.exceptions.IdentifierNotUnique;
47
import org.dataone.service.exceptions.InsufficientResources;
48 6174 cjones
import org.dataone.service.exceptions.InvalidRequest;
49 6241 cjones
import org.dataone.service.exceptions.InvalidSystemMetadata;
50 6174 cjones
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 6241 cjones
import org.dataone.service.exceptions.UnsupportedType;
56 6366 leinfelder
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 6174 cjones
72 6241 cjones
import edu.ucsb.nceas.metacat.AccessionNumberException;
73
import edu.ucsb.nceas.metacat.DocumentImpl;
74 6186 leinfelder
import edu.ucsb.nceas.metacat.EventLog;
75
import edu.ucsb.nceas.metacat.IdentifierManager;
76 6194 leinfelder
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
77 6226 cjones
import edu.ucsb.nceas.metacat.MetacatHandler;
78
import edu.ucsb.nceas.metacat.properties.PropertyService;
79 6241 cjones
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
80 6254 cjones
import edu.ucsb.nceas.metacat.util.SystemUtil;
81 6226 cjones
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
82 6186 leinfelder
83 6174 cjones
public abstract class D1NodeService {
84 6227 cjones
85 6226 cjones
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
86 6186 leinfelder
87 6241 cjones
  /* the metacat URL as a string (including ending /d1 service)*/
88 6254 cjones
  protected String metacatUrl;
89 6241 cjones
90 6226 cjones
  /* reference to the metacat handler */
91
  private MetacatHandler handler;
92 6174 cjones
93 6226 cjones
  /* parameters set in the incoming request */
94
  private Hashtable<String, String[]> params;
95
96 6241 cjones
  /**
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 6254 cjones
  public D1NodeService() {
102
  	this.metacatUrl = "";
103
104
    try {
105 6308 cjones
	    this.metacatUrl = SystemUtil.getContextURL() + "/" +
106 6254 cjones
	    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 6241 cjones
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 6174 cjones
144 6241 cjones
    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 6278 leinfelder
    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 6337 leinfelder
179 6241 cjones
    }
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 6302 leinfelder
      } else {
215
216
	      // DEFAULT CASE: DATA (needs to be checked and completed)
217
	      localId = insertDataObject(object, pid, session);
218
      }
219
220 6241 cjones
    }
221 6313 leinfelder
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 6302 leinfelder
229 6241 cjones
    // setting the resulting identifier failed
230 6302 leinfelder
    if (localId == null ) {
231
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
232 6241 cjones
    }
233 6313 leinfelder
234 6241 cjones
235 6302 leinfelder
    resultPid = pid;
236
237 6241 cjones
    return resultPid;
238
  }
239
240 6227 cjones
  /**
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 6179 cjones
      Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
264 6227 cjones
      NotAuthorized, InvalidRequest, NotImplemented {
265 6174 cjones
266 6186 leinfelder
267 6227 cjones
    Log log = new Log();
268 6321 leinfelder
    List<LogEntry> logs = new Vector<LogEntry>();
269 6227 cjones
    IdentifierManager im = IdentifierManager.getInstance();
270
    EventLog el = EventLog.getInstance();
271 6353 cjones
    if ( fromDate == null ) {
272 6227 cjones
      logMetacat.debug("setting fromdate from null");
273
      fromDate = new Date(1);
274
    }
275 6353 cjones
    if ( toDate == null ) {
276 6227 cjones
      logMetacat.debug("setting todate from null");
277
      toDate = new Date();
278
    }
279 6186 leinfelder
280 6353 cjones
    if ( start == null ) {
281
    	start = 0;
282
283
    }
284
285
    if ( count == null ) {
286
    	count = 1000;
287
288
    }
289
290 6227 cjones
    logMetacat.debug("fromDate: " + fromDate);
291
    logMetacat.debug("toDate: " + toDate);
292 6186 leinfelder
293 6227 cjones
    String report = el.getReport(null, null, null, null,
294
        new java.sql.Timestamp(fromDate.getTime()),
295
        new java.sql.Timestamp(toDate.getTime()), false);
296 6186 leinfelder
297 6227 cjones
    logMetacat.debug("report: " + report);
298 6186 leinfelder
299 6227 cjones
    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 6186 leinfelder
311 6227 cjones
      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 6186 leinfelder
318 6227 cjones
      LogEntry le = new LogEntry();
319 6186 leinfelder
320 6227 cjones
      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 6241 cjones
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
331 6227 cjones
        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 6241 cjones
        // try to get the pid, if that doesn't
338 6227 cjones
        // work, just use the local id
339
        // throw new ServiceFailure("1030",
340 6241 cjones
        // "Error getting pid for localId " +
341 6227 cjones
        // docid + ": " + ex.getMessage());\
342 6186 leinfelder
343 6241 cjones
        // skip it if the pid can't be found
344 6227 cjones
        continue;
345
      }
346 6186 leinfelder
347 6227 cjones
      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 6186 leinfelder
366 6321 leinfelder
      // event filtering?
367 6227 cjones
      if (event == null) {
368 6321 leinfelder
    	  logs.add(le);
369
      } else if (le.getEvent().equals(event)) {
370
    	  logs.add(le);
371 6227 cjones
      }
372
    }
373 6321 leinfelder
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 6186 leinfelder
383 6227 cjones
    log.setLogEntryList(logs);
384 6321 leinfelder
    log.setStart(start);
385
    log.setCount(logs.size());
386
    log.setTotal(total);
387 6227 cjones
    logMetacat.info("getLogRecords");
388
    return log;
389
  }
390 6241 cjones
391 6227 cjones
  /**
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 6226 cjones
413 6227 cjones
    InputStream inputStream = null; // bytes to be returned
414 6226 cjones
    handler = new MetacatHandler(new Timer());
415 6227 cjones
    boolean allowed = false;
416
    String localId; // the metacat docid for the pid
417 6226 cjones
418 6227 cjones
    // get the local docid from Metacat
419
    try {
420
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
421
422 6226 cjones
    } catch (McdbDocNotFoundException e) {
423
      throw new NotFound("1020", "The object specified by " +
424 6227 cjones
                         pid.getValue() +
425 6283 leinfelder
                         " does not exist at this node.");
426 6226 cjones
    }
427
428
    // check for authorization
429 6227 cjones
    allowed = isAuthorized(session, pid, Permission.READ);
430
431
    // if the person is authorized, perform the read
432 6323 leinfelder
    if (allowed) {
433 6226 cjones
      try {
434 6323 leinfelder
        inputStream = handler.read(localId);
435
      } catch (Exception e) {
436 6226 cjones
        throw new ServiceFailure("1020", "The object specified by " +
437
            pid.getValue() +
438 6323 leinfelder
            "could not be returned due to error: " +
439 6226 cjones
            e.getMessage());
440
      }
441 6227 cjones
    }
442 6226 cjones
443 6227 cjones
    // if we fail to set the input stream
444
    if ( inputStream == null ) {
445 6226 cjones
      throw new NotFound("1020", "The object specified by " +
446
                         pid.getValue() +
447
                         "does not exist at this node.");
448 6227 cjones
    }
449
450
    return inputStream;
451
  }
452 6174 cjones
453 6227 cjones
  /**
454
   * Return the system metadata for a given object
455
   *
456
   * @param session - the Session object containing the credentials for the Subject
457
   * @param pid - the object identifier for the given object
458
   *
459
   * @return inputStream - the input stream of the given system metadata object
460
   *
461
   * @throws InvalidToken
462
   * @throws ServiceFailure
463
   * @throws NotAuthorized
464
   * @throws NotFound
465
   * @throws InvalidRequest
466
   * @throws NotImplemented
467
   */
468
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
469 6174 cjones
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
470
    InvalidRequest, NotImplemented {
471
472 6227 cjones
    if (!isAuthorized(session, pid, Permission.READ)) {
473
      throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());
474
    }
475
    SystemMetadata systemMetadata = null;
476
    try {
477
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
478
    } catch (McdbDocNotFoundException e) {
479
      throw new NotFound("1420", "No record found for: " + pid.getValue());
480
    }
481
482
    return systemMetadata;
483 6174 cjones
  }
484 6241 cjones
485 6227 cjones
  /**
486
   * Set access for a given object using the object identifier and a Subject
487
   * under a given Session.
488
   *
489
   * @param session - the Session object containing the credentials for the Subject
490
   * @param pid - the object identifier for the given object to apply the policy
491
   * @param policy - the access policy to be applied
492
   *
493
   * @return true if the application of the policy succeeds
494
   * @throws InvalidToken
495
   * @throws ServiceFailure
496
   * @throws NotFound
497
   * @throws NotAuthorized
498
   * @throws NotImplemented
499
   * @throws InvalidRequest
500
   */
501
  public boolean setAccessPolicy(Session session, Identifier pid,
502 6179 cjones
    AccessPolicy accessPolicy)
503 6227 cjones
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized,
504
    NotImplemented, InvalidRequest {
505 6174 cjones
506 6227 cjones
    boolean success = false;
507
508
    // get the subject
509
    Subject subject = session.getSubject();
510
    // get the system metadata
511 6241 cjones
    String pidStr = pid.getValue();
512 6227 cjones
513
    // are we allowed to do this?
514
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
515 6241 cjones
      throw new NotAuthorized("4420", "not allowed by " + subject.getValue() + " on " + pidStr);
516 6227 cjones
    }
517
518
    SystemMetadata systemMetadata = null;
519
    try {
520 6241 cjones
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
521 6227 cjones
    } catch (McdbDocNotFoundException e) {
522 6241 cjones
      throw new NotFound("4400", "No record found for: " + pid);
523 6227 cjones
    }
524
525
    // set the access policy
526
    systemMetadata.setAccessPolicy(accessPolicy);
527
528
    // update the metadata
529
    try {
530
      IdentifierManager.getInstance().updateSystemMetadata(systemMetadata);
531
      success = true;
532
    } catch (McdbDocNotFoundException e) {
533
      throw new ServiceFailure("4430", e.getMessage());
534
    }
535 6194 leinfelder
536 6227 cjones
    return success;
537
  }
538
539
  /**
540
   * Test if the user identified by the provided token has authorization
541
   * for operation on the specified object.
542
   *
543
   * @param session - the Session object containing the credentials for the Subject
544
   * @param pid - The identifer of the resource for which access is being checked
545
   * @param operation - The type of operation which is being requested for the given pid
546
   *
547
   * @return true if the operation is allowed
548
   *
549
   * @throws ServiceFailure
550
   * @throws InvalidToken
551
   * @throws NotFound
552
   * @throws NotAuthorized
553
   * @throws NotImplemented
554
   * @throws InvalidRequest
555
   */
556
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
557
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
558
    NotImplemented, InvalidRequest {
559 6174 cjones
560 6227 cjones
    boolean allowed = false;
561
562
    // get the subjects from the session
563
    List<Subject> subjects = new ArrayList<Subject>();
564 6245 leinfelder
    Subject subject = session.getSubject();
565
    if (subject != null) {
566
    	subjects.add(subject);
567 6227 cjones
    }
568 6245 leinfelder
    SubjectList subjectList = session.getSubjectList();
569
    if (subjectList != null) {
570
    	List<Person> personList = subjectList.getPersonList();
571
    	if (personList != null) {
572
		    for (Person p: personList) {
573
		      subjects.add(p.getSubject());
574
		    }
575
    	}
576
    	List<Group> groupList = subjectList.getGroupList();
577
    	if (groupList != null) {
578
		    for (Group g: groupList) {
579
		      subjects.add(g.getSubject());
580
		    }
581
    	}
582 6227 cjones
    }
583
584 6293 leinfelder
    // add public subject
585
    Subject publicSubject = new Subject();
586
    publicSubject.setValue(Constants.PUBLIC_SUBJECT);
587
    subjects.add(publicSubject);
588
589 6227 cjones
    // get the system metadata
590 6241 cjones
    String pidStr = pid.getValue();
591 6227 cjones
    SystemMetadata systemMetadata = null;
592
    try {
593 6241 cjones
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
594 6227 cjones
    } catch (McdbDocNotFoundException e) {
595 6245 leinfelder
      throw new NotFound("1800", "No record found for " + pidStr);
596 6227 cjones
    }
597 6245 leinfelder
598 6293 leinfelder
    // do we own it?
599
    for (Subject s: subjects) {
600
    	allowed = systemMetadata.getRightsHolder().getValue().equals(s.getValue());
601
    	if (allowed) {
602
    		return allowed;
603
    	}
604
    }
605
606
    // otherwise check the access rules
607 6245 leinfelder
    try {
608
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
609 6293 leinfelder
	    search: // label break
610 6245 leinfelder
	    for (AccessRule accessRule: allows) {
611
	      for (Subject s: subjects) {
612 6293 leinfelder
	        //if (accessRule.getSubjectList().contains(s)) {
613
        	for (Subject ruleSubject: accessRule.getSubjectList()) {
614
        		if (ruleSubject.getValue().equals(s.getValue())) {
615
		          allowed = accessRule.getPermissionList().contains(permission);
616
		          if (allowed) {
617
		        	  break search; //label break
618
		          }
619
        		}
620 6245 leinfelder
	        }
621
	      }
622
	    }
623
    } catch (Exception e) {
624
    	// catch all for errors - safe side should be to deny the access
625
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
626
		allowed = false;
627
	}
628 6227 cjones
629 6245 leinfelder
    // throw or return?
630 6227 cjones
    if (!allowed) {
631 6245 leinfelder
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
632 6227 cjones
    }
633 6245 leinfelder
634 6227 cjones
    return allowed;
635 6241 cjones
636 6227 cjones
  }
637
638 6256 cjones
  /*
639 6227 cjones
   * parse a logEntry and get the relevant field from it
640
   *
641
   * @param fieldname
642
   * @param entry
643
   * @return
644
   */
645
  private String getLogEntryField(String fieldname, String entry) {
646
    String begin = "<" + fieldname + ">";
647
    String end = "</" + fieldname + ">";
648
    // logMetacat.debug("looking for " + begin + " and " + end +
649
    // " in entry " + entry);
650
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
651
        .indexOf(end));
652
    logMetacat.debug("entry " + fieldname + " : " + s);
653
    return s;
654
  }
655 6174 cjones
656 6257 cjones
  /**
657 6241 cjones
   * Determine if a given object should be treated as an XML science metadata
658
   * object.
659
   *
660
   * @param sysmeta - the SystemMetadata describing the object
661
   * @return true if the object should be treated as science metadata
662
   */
663 6257 cjones
  protected boolean isScienceMetadata(SystemMetadata sysmeta) {
664 6241 cjones
665
    ObjectFormat objectFormat = null;
666
    boolean isScienceMetadata = false;
667
668
    try {
669
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getObjectFormat().getFmtid());
670
      isScienceMetadata = objectFormat.isScienceMetadata();
671
672
    } catch (InvalidRequest e) {
673
       logMetacat.debug("There was a problem determining if the object identified by" +
674
         sysmeta.getIdentifier().getValue() +
675
         " is science metadata: " + e.getMessage());
676
677
    } catch (ServiceFailure e) {
678
      logMetacat.debug("There was a problem determining if the object identified by" +
679
          sysmeta.getIdentifier().getValue() +
680
          " is science metadata: " + e.getMessage());
681
682
    } catch (NotFound e) {
683
      logMetacat.debug("There was a problem determining if the object identified by" +
684
          sysmeta.getIdentifier().getValue() +
685
          " is science metadata: " + e.getMessage());
686
687
    } catch (InsufficientResources e) {
688
      logMetacat.debug("There was a problem determining if the object identified by" +
689
          sysmeta.getIdentifier().getValue() +
690
          " is science metadata: " + e.getMessage());
691
692
    } catch (NotImplemented e) {
693
      logMetacat.debug("There was a problem determining if the object identified by" +
694
          sysmeta.getIdentifier().getValue() +
695
          " is science metadata: " + e.getMessage());
696
697
    }
698
699
    return isScienceMetadata;
700 6226 cjones
701 6241 cjones
  }
702
703
  /**
704
   * Insert or update an XML document into Metacat
705
   *
706
   * @param xml - the XML document to insert or update
707
   * @param pid - the identifier to be used for the resulting object
708
   *
709
   * @return localId - the resulting docid of the document created or updated
710
   *
711
   */
712
  protected String insertOrUpdateDocument(String xml, Identifier pid,
713
    Session session, String insertOrUpdate)
714
    throws ServiceFailure {
715
716
  	logMetacat.debug("Starting to insert xml document...");
717
    IdentifierManager im = IdentifierManager.getInstance();
718
719
    // generate pid/localId pair for sysmeta
720
    String localId = null;
721
722
    if(insertOrUpdate.equals("insert")) {
723
      localId = im.generateLocalId(pid.getValue(), 1);
724
725
    } else {
726
      //localid should already exist in the identifier table, so just find it
727
      try {
728
        logMetacat.debug("Updating pid " + pid.getValue());
729
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
730
731
        localId = im.getLocalId(pid.getValue());
732
733
        logMetacat.debug("localId: " + localId);
734
        //increment the revision
735
        String docid = localId.substring(0, localId.lastIndexOf("."));
736
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
737
        int rev = new Integer(revS).intValue();
738
        rev++;
739
        docid = docid + "." + rev;
740
        localId = docid;
741
        logMetacat.debug("incremented localId: " + localId);
742
743
      } catch(McdbDocNotFoundException e) {
744
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
745
            "pid " + pid.getValue() +
746
            " should have been in the identifier table, but it wasn't: " +
747
            e.getMessage());
748
749
      }
750
751
    }
752
753
    String[] action = new String[1];
754
    action[0] = insertOrUpdate;
755
    params.put("action", action);
756
    String[] docid = new String[1];
757
    docid[0] = localId;
758
    params.put("docid", docid);
759
    String[] doctext = new String[1];
760
    doctext[0] = xml;
761
    params.put("doctext", doctext);
762
763 6302 leinfelder
    String username = Constants.PUBLIC_SUBJECT;
764 6241 cjones
    String[] groupnames = null;
765 6302 leinfelder
    if (session != null ) {
766
    	username = session.getSubject().getValue();
767
    	if (session.getSubjectList() != null) {
768
    		List<Group> groupList = session.getSubjectList().getGroupList();
769
    		if (groupList != null) {
770
    			groupnames = new String[groupList.size()];
771
    			for (int i = 0; i > groupList.size(); i++ ) {
772
    				groupnames[i] = groupList.get(i).getGroupName();
773
    			}
774
    		}
775
    	}
776 6241 cjones
    }
777
778
    // do the insert or update action
779
    String result = handler.handleInsertOrUpdateAction(metacatUrl, null,
780
                        null, params, username, groupnames);
781
782
    if(result.indexOf("<error>") != -1) {
783
    	String detailCode = "";
784
    	if ( insertOrUpdate.equals("insert") ) {
785
    		detailCode = "1190";
786
787
    	} else if ( insertOrUpdate.equals("update") ) {
788
    		detailCode = "1310";
789
790
    	}
791
        throw new ServiceFailure(detailCode,
792
          "Error inserting or updating document: " + result);
793
    }
794
    logMetacat.debug("Finsished inserting xml document with id " + localId);
795
796
    return localId;
797
  }
798
799
  /**
800
   * Insert a data document
801
   *
802
   * @param object
803
   * @param pid
804
   * @param sessionData
805
   * @throws ServiceFailure
806
   * @returns localId of the data object inserted
807
   */
808 6255 cjones
  protected String insertDataObject(InputStream object, Identifier pid,
809 6241 cjones
          Session session) throws ServiceFailure {
810
811 6302 leinfelder
    String username = Constants.PUBLIC_SUBJECT;
812 6241 cjones
    String[] groupnames = null;
813 6302 leinfelder
    if (session != null ) {
814
    	username = session.getSubject().getValue();
815
    	if (session.getSubjectList() != null) {
816
    		List<Group> groupList = session.getSubjectList().getGroupList();
817
    		if (groupList != null) {
818
    			groupnames = new String[groupList.size()];
819
    			for (int i = 0; i > groupList.size(); i++ ) {
820
    				groupnames[i] = groupList.get(i).getGroupName();
821
    			}
822
    		}
823
    	}
824 6241 cjones
    }
825
826
    // generate pid/localId pair for object
827
    logMetacat.debug("Generating a pid/localId mapping");
828
    IdentifierManager im = IdentifierManager.getInstance();
829
    String localId = im.generateLocalId(pid.getValue(), 1);
830
831
    try {
832
      logMetacat.debug("Case DATA: starting to write to disk.");
833
      if (DocumentImpl.getDataFileLockGrant(localId)) {
834
835
        // Save the data file to disk using "localId" as the name
836
        try {
837
          String datafilepath = PropertyService.getProperty("application.datafilepath");
838
839
          File dataDirectory = new File(datafilepath);
840
          dataDirectory.mkdirs();
841
842
          File newFile = writeStreamToFile(dataDirectory, localId, object);
843
844
          // TODO: Check that the file size matches SystemMetadata
845
          // long size = newFile.length();
846
          // if (size == 0) {
847
          //     throw new IOException("Uploaded file is 0 bytes!");
848
          // }
849
850
          // Register the file in the database (which generates an exception
851
          // if the localId is not acceptable or other untoward things happen
852
          try {
853
            logMetacat.debug("Registering document...");
854
            DocumentImpl.registerDocument(localId, "BIN", localId,
855
                    username, groupnames);
856
            logMetacat.debug("Registration step completed.");
857
858
          } catch (SQLException e) {
859
            //newFile.delete();
860
            logMetacat.debug("SQLE: " + e.getMessage());
861
            e.printStackTrace(System.out);
862
            throw new ServiceFailure("1190", "Registration failed: " +
863
            		e.getMessage());
864
865
          } catch (AccessionNumberException e) {
866
            //newFile.delete();
867
            logMetacat.debug("ANE: " + e.getMessage());
868
            e.printStackTrace(System.out);
869
            throw new ServiceFailure("1190", "Registration failed: " +
870
            	e.getMessage());
871
872
          } catch (Exception e) {
873
            //newFile.delete();
874
            logMetacat.debug("Exception: " + e.getMessage());
875
            e.printStackTrace(System.out);
876
            throw new ServiceFailure("1190", "Registration failed: " +
877
            	e.getMessage());
878
          }
879
880
          logMetacat.debug("Logging the creation event.");
881
          EventLog.getInstance().log(metacatUrl, username, localId, "create");
882
883
          // Schedule replication for this data file
884
          logMetacat.debug("Scheduling replication.");
885
          ForceReplicationHandler frh = new ForceReplicationHandler(
886
            localId, "create", false, null);
887
888
        } catch (PropertyNotFoundException e) {
889
          throw new ServiceFailure("1190", "Could not lock file for writing:" +
890
          	e.getMessage());
891
892
        }
893
      }
894
      return localId;
895
    } catch (Exception e) {
896
        // Could not get a lock on the document, so we can not update the file now
897
        throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
898
    }
899
900
  }
901 6255 cjones
902 6256 cjones
  /**
903
   * Insert a systemMetadata document and return its localId
904
   */
905
  protected void insertSystemMetadata(SystemMetadata sysmeta)
906
    throws ServiceFailure {
907
908
  	logMetacat.debug("Starting to insert SystemMetadata...");
909
    sysmeta.setDateSysMetadataModified(new Date());
910
    logMetacat.debug("Inserting new system metadata with modified date " +
911
        sysmeta.getDateSysMetadataModified());
912
913
    //insert the system metadata
914 6276 leinfelder
	try {
915
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
916
917
	} catch (McdbDocNotFoundException e) {
918 6256 cjones
      throw new ServiceFailure("1030", "Error inserting system metadata: " +
919
      	e.getClass() + ": " + e.getMessage());
920
921
    }
922
923
  }
924
925
  /**
926 6255 cjones
   * Update a systemMetadata document
927
   *
928
   * @param sysMeta - the system metadata object in the system to update
929
   */
930
  protected void updateSystemMetadata(SystemMetadata sysMeta)
931
    throws ServiceFailure {
932
933
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
934
    sysMeta.setDateSysMetadataModified(new Date());
935
    try {
936
	    IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
937
938
    } catch (McdbDocNotFoundException e) {
939
940
      throw new ServiceFailure("1030", "Error updating system metadata: " +
941
        e.getClass() + ": " + e.getMessage());
942
943
    }
944
945
  }
946
947
  /*
948 6241 cjones
   * Write a stream to a file
949
   *
950
   * @param dir - the directory to write to
951
   * @param fileName - the file name to write to
952
   * @param data - the object bytes as an input stream
953
   *
954
   * @return newFile - the new file created
955
   *
956
   * @throws ServiceFailure
957
   */
958
  private File writeStreamToFile(File dir, String fileName, InputStream data)
959
    throws ServiceFailure {
960
961
    File newFile = new File(dir, fileName);
962
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
963
964
    try {
965
        if (newFile.createNewFile()) {
966
          // write data stream to desired file
967
          OutputStream os = new FileOutputStream(newFile);
968
          long length = IOUtils.copyLarge(data, os);
969
          os.flush();
970
          os.close();
971
        } else {
972
          logMetacat.debug("File creation failed, or file already exists.");
973
          throw new ServiceFailure("1190", "File already exists: " + fileName);
974
        }
975
    } catch (FileNotFoundException e) {
976
      logMetacat.debug("FNF: " + e.getMessage());
977
      throw new ServiceFailure("1190", "File not found: " + fileName + " "
978
                + e.getMessage());
979
    } catch (IOException e) {
980
      logMetacat.debug("IOE: " + e.getMessage());
981
      throw new ServiceFailure("1190", "File was not written: " + fileName
982
                + " " + e.getMessage());
983
    }
984
985
    return newFile;
986
  }
987
988
}