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 6389 leinfelder
  protected 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 6389 leinfelder
	// 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 6227 cjones
    return inputStream;
458
  }
459 6174 cjones
460 6227 cjones
  /**
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 6174 cjones
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
477
    InvalidRequest, NotImplemented {
478
479 6227 cjones
    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 6174 cjones
  }
491 6241 cjones
492 6227 cjones
  /**
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 6179 cjones
    AccessPolicy accessPolicy)
510 6227 cjones
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized,
511
    NotImplemented, InvalidRequest {
512 6174 cjones
513 6227 cjones
    boolean success = false;
514
515
    // get the subject
516
    Subject subject = session.getSubject();
517
    // get the system metadata
518 6241 cjones
    String pidStr = pid.getValue();
519 6227 cjones
520
    // are we allowed to do this?
521
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
522 6241 cjones
      throw new NotAuthorized("4420", "not allowed by " + subject.getValue() + " on " + pidStr);
523 6227 cjones
    }
524
525
    SystemMetadata systemMetadata = null;
526
    try {
527 6241 cjones
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
528 6227 cjones
    } catch (McdbDocNotFoundException e) {
529 6241 cjones
      throw new NotFound("4400", "No record found for: " + pid);
530 6227 cjones
    }
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 6194 leinfelder
543 6227 cjones
    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 6174 cjones
567 6227 cjones
    boolean allowed = false;
568
569
    // get the subjects from the session
570
    List<Subject> subjects = new ArrayList<Subject>();
571 6245 leinfelder
    Subject subject = session.getSubject();
572
    if (subject != null) {
573
    	subjects.add(subject);
574 6227 cjones
    }
575 6245 leinfelder
    SubjectList subjectList = session.getSubjectList();
576
    if (subjectList != null) {
577
    	List<Person> personList = subjectList.getPersonList();
578
    	if (personList != null) {
579
		    for (Person p: personList) {
580
		      subjects.add(p.getSubject());
581
		    }
582
    	}
583
    	List<Group> groupList = subjectList.getGroupList();
584
    	if (groupList != null) {
585
		    for (Group g: groupList) {
586
		      subjects.add(g.getSubject());
587
		    }
588
    	}
589 6227 cjones
    }
590
591 6293 leinfelder
    // add public subject
592
    Subject publicSubject = new Subject();
593
    publicSubject.setValue(Constants.PUBLIC_SUBJECT);
594
    subjects.add(publicSubject);
595
596 6227 cjones
    // get the system metadata
597 6241 cjones
    String pidStr = pid.getValue();
598 6227 cjones
    SystemMetadata systemMetadata = null;
599
    try {
600 6241 cjones
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
601 6227 cjones
    } catch (McdbDocNotFoundException e) {
602 6245 leinfelder
      throw new NotFound("1800", "No record found for " + pidStr);
603 6227 cjones
    }
604 6245 leinfelder
605 6293 leinfelder
    // do we own it?
606
    for (Subject s: subjects) {
607
    	allowed = systemMetadata.getRightsHolder().getValue().equals(s.getValue());
608
    	if (allowed) {
609
    		return allowed;
610
    	}
611
    }
612
613
    // otherwise check the access rules
614 6245 leinfelder
    try {
615
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
616 6293 leinfelder
	    search: // label break
617 6245 leinfelder
	    for (AccessRule accessRule: allows) {
618
	      for (Subject s: subjects) {
619 6293 leinfelder
	        //if (accessRule.getSubjectList().contains(s)) {
620
        	for (Subject ruleSubject: accessRule.getSubjectList()) {
621
        		if (ruleSubject.getValue().equals(s.getValue())) {
622
		          allowed = accessRule.getPermissionList().contains(permission);
623
		          if (allowed) {
624
		        	  break search; //label break
625
		          }
626
        		}
627 6245 leinfelder
	        }
628
	      }
629
	    }
630
    } catch (Exception e) {
631
    	// catch all for errors - safe side should be to deny the access
632
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
633
		allowed = false;
634
	}
635 6227 cjones
636 6245 leinfelder
    // throw or return?
637 6227 cjones
    if (!allowed) {
638 6245 leinfelder
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
639 6227 cjones
    }
640 6245 leinfelder
641 6227 cjones
    return allowed;
642 6241 cjones
643 6227 cjones
  }
644
645 6256 cjones
  /*
646 6227 cjones
   * parse a logEntry and get the relevant field from it
647
   *
648
   * @param fieldname
649
   * @param entry
650
   * @return
651
   */
652
  private String getLogEntryField(String fieldname, String entry) {
653
    String begin = "<" + fieldname + ">";
654
    String end = "</" + fieldname + ">";
655
    // logMetacat.debug("looking for " + begin + " and " + end +
656
    // " in entry " + entry);
657
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
658
        .indexOf(end));
659
    logMetacat.debug("entry " + fieldname + " : " + s);
660
    return s;
661
  }
662 6174 cjones
663 6257 cjones
  /**
664 6241 cjones
   * Determine if a given object should be treated as an XML science metadata
665
   * object.
666
   *
667
   * @param sysmeta - the SystemMetadata describing the object
668
   * @return true if the object should be treated as science metadata
669
   */
670 6257 cjones
  protected boolean isScienceMetadata(SystemMetadata sysmeta) {
671 6241 cjones
672
    ObjectFormat objectFormat = null;
673
    boolean isScienceMetadata = false;
674
675
    try {
676 6384 cjones
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFmtid());
677 6241 cjones
      isScienceMetadata = objectFormat.isScienceMetadata();
678
679
    } catch (InvalidRequest e) {
680
       logMetacat.debug("There was a problem determining if the object identified by" +
681
         sysmeta.getIdentifier().getValue() +
682
         " is science metadata: " + e.getMessage());
683
684
    } catch (ServiceFailure 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 (NotFound 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 (InsufficientResources 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 (NotImplemented 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
    }
705
706
    return isScienceMetadata;
707 6226 cjones
708 6241 cjones
  }
709
710
  /**
711
   * Insert or update an XML document into Metacat
712
   *
713
   * @param xml - the XML document to insert or update
714
   * @param pid - the identifier to be used for the resulting object
715
   *
716
   * @return localId - the resulting docid of the document created or updated
717
   *
718
   */
719
  protected String insertOrUpdateDocument(String xml, Identifier pid,
720
    Session session, String insertOrUpdate)
721
    throws ServiceFailure {
722
723
  	logMetacat.debug("Starting to insert xml document...");
724
    IdentifierManager im = IdentifierManager.getInstance();
725
726
    // generate pid/localId pair for sysmeta
727
    String localId = null;
728
729
    if(insertOrUpdate.equals("insert")) {
730
      localId = im.generateLocalId(pid.getValue(), 1);
731
732
    } else {
733
      //localid should already exist in the identifier table, so just find it
734
      try {
735
        logMetacat.debug("Updating pid " + pid.getValue());
736
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
737
738
        localId = im.getLocalId(pid.getValue());
739
740
        logMetacat.debug("localId: " + localId);
741
        //increment the revision
742
        String docid = localId.substring(0, localId.lastIndexOf("."));
743
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
744
        int rev = new Integer(revS).intValue();
745
        rev++;
746
        docid = docid + "." + rev;
747
        localId = docid;
748
        logMetacat.debug("incremented localId: " + localId);
749
750
      } catch(McdbDocNotFoundException e) {
751
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
752
            "pid " + pid.getValue() +
753
            " should have been in the identifier table, but it wasn't: " +
754
            e.getMessage());
755
756
      }
757
758
    }
759
760
    String[] action = new String[1];
761
    action[0] = insertOrUpdate;
762
    params.put("action", action);
763
    String[] docid = new String[1];
764
    docid[0] = localId;
765
    params.put("docid", docid);
766
    String[] doctext = new String[1];
767
    doctext[0] = xml;
768
    params.put("doctext", doctext);
769
770 6302 leinfelder
    String username = Constants.PUBLIC_SUBJECT;
771 6241 cjones
    String[] groupnames = null;
772 6302 leinfelder
    if (session != null ) {
773
    	username = session.getSubject().getValue();
774
    	if (session.getSubjectList() != null) {
775
    		List<Group> groupList = session.getSubjectList().getGroupList();
776
    		if (groupList != null) {
777
    			groupnames = new String[groupList.size()];
778
    			for (int i = 0; i > groupList.size(); i++ ) {
779
    				groupnames[i] = groupList.get(i).getGroupName();
780
    			}
781
    		}
782
    	}
783 6241 cjones
    }
784
785
    // do the insert or update action
786
    String result = handler.handleInsertOrUpdateAction(metacatUrl, null,
787
                        null, params, username, groupnames);
788
789
    if(result.indexOf("<error>") != -1) {
790
    	String detailCode = "";
791
    	if ( insertOrUpdate.equals("insert") ) {
792
    		detailCode = "1190";
793
794
    	} else if ( insertOrUpdate.equals("update") ) {
795
    		detailCode = "1310";
796
797
    	}
798
        throw new ServiceFailure(detailCode,
799
          "Error inserting or updating document: " + result);
800
    }
801
    logMetacat.debug("Finsished inserting xml document with id " + localId);
802
803
    return localId;
804
  }
805
806
  /**
807
   * Insert a data document
808
   *
809
   * @param object
810
   * @param pid
811
   * @param sessionData
812
   * @throws ServiceFailure
813
   * @returns localId of the data object inserted
814
   */
815 6255 cjones
  protected String insertDataObject(InputStream object, Identifier pid,
816 6241 cjones
          Session session) throws ServiceFailure {
817
818 6302 leinfelder
    String username = Constants.PUBLIC_SUBJECT;
819 6241 cjones
    String[] groupnames = null;
820 6302 leinfelder
    if (session != null ) {
821
    	username = session.getSubject().getValue();
822
    	if (session.getSubjectList() != null) {
823
    		List<Group> groupList = session.getSubjectList().getGroupList();
824
    		if (groupList != null) {
825
    			groupnames = new String[groupList.size()];
826
    			for (int i = 0; i > groupList.size(); i++ ) {
827
    				groupnames[i] = groupList.get(i).getGroupName();
828
    			}
829
    		}
830
    	}
831 6241 cjones
    }
832
833
    // generate pid/localId pair for object
834
    logMetacat.debug("Generating a pid/localId mapping");
835
    IdentifierManager im = IdentifierManager.getInstance();
836
    String localId = im.generateLocalId(pid.getValue(), 1);
837
838
    try {
839
      logMetacat.debug("Case DATA: starting to write to disk.");
840
      if (DocumentImpl.getDataFileLockGrant(localId)) {
841
842
        // Save the data file to disk using "localId" as the name
843
        try {
844
          String datafilepath = PropertyService.getProperty("application.datafilepath");
845
846
          File dataDirectory = new File(datafilepath);
847
          dataDirectory.mkdirs();
848
849
          File newFile = writeStreamToFile(dataDirectory, localId, object);
850
851
          // TODO: Check that the file size matches SystemMetadata
852
          // long size = newFile.length();
853
          // if (size == 0) {
854
          //     throw new IOException("Uploaded file is 0 bytes!");
855
          // }
856
857
          // Register the file in the database (which generates an exception
858
          // if the localId is not acceptable or other untoward things happen
859
          try {
860
            logMetacat.debug("Registering document...");
861
            DocumentImpl.registerDocument(localId, "BIN", localId,
862
                    username, groupnames);
863
            logMetacat.debug("Registration step completed.");
864
865
          } catch (SQLException e) {
866
            //newFile.delete();
867
            logMetacat.debug("SQLE: " + e.getMessage());
868
            e.printStackTrace(System.out);
869
            throw new ServiceFailure("1190", "Registration failed: " +
870
            		e.getMessage());
871
872
          } catch (AccessionNumberException e) {
873
            //newFile.delete();
874
            logMetacat.debug("ANE: " + e.getMessage());
875
            e.printStackTrace(System.out);
876
            throw new ServiceFailure("1190", "Registration failed: " +
877
            	e.getMessage());
878
879
          } catch (Exception e) {
880
            //newFile.delete();
881
            logMetacat.debug("Exception: " + e.getMessage());
882
            e.printStackTrace(System.out);
883
            throw new ServiceFailure("1190", "Registration failed: " +
884
            	e.getMessage());
885
          }
886
887
          logMetacat.debug("Logging the creation event.");
888
          EventLog.getInstance().log(metacatUrl, username, localId, "create");
889
890
          // Schedule replication for this data file
891
          logMetacat.debug("Scheduling replication.");
892
          ForceReplicationHandler frh = new ForceReplicationHandler(
893
            localId, "create", false, null);
894
895
        } catch (PropertyNotFoundException e) {
896
          throw new ServiceFailure("1190", "Could not lock file for writing:" +
897
          	e.getMessage());
898
899
        }
900
      }
901
      return localId;
902
    } catch (Exception e) {
903
        // Could not get a lock on the document, so we can not update the file now
904
        throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
905
    }
906
907
  }
908 6255 cjones
909 6256 cjones
  /**
910
   * Insert a systemMetadata document and return its localId
911
   */
912
  protected void insertSystemMetadata(SystemMetadata sysmeta)
913
    throws ServiceFailure {
914
915
  	logMetacat.debug("Starting to insert SystemMetadata...");
916
    sysmeta.setDateSysMetadataModified(new Date());
917
    logMetacat.debug("Inserting new system metadata with modified date " +
918
        sysmeta.getDateSysMetadataModified());
919
920
    //insert the system metadata
921 6276 leinfelder
	try {
922
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
923
924
	} catch (McdbDocNotFoundException e) {
925 6256 cjones
      throw new ServiceFailure("1030", "Error inserting system metadata: " +
926
      	e.getClass() + ": " + e.getMessage());
927
928
    }
929
930
  }
931
932
  /**
933 6255 cjones
   * Update a systemMetadata document
934
   *
935
   * @param sysMeta - the system metadata object in the system to update
936
   */
937
  protected void updateSystemMetadata(SystemMetadata sysMeta)
938
    throws ServiceFailure {
939
940
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
941
    sysMeta.setDateSysMetadataModified(new Date());
942
    try {
943
	    IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
944
945
    } catch (McdbDocNotFoundException e) {
946
947
      throw new ServiceFailure("1030", "Error updating system metadata: " +
948
        e.getClass() + ": " + e.getMessage());
949
950
    }
951
952
  }
953
954
  /*
955 6241 cjones
   * Write a stream to a file
956
   *
957
   * @param dir - the directory to write to
958
   * @param fileName - the file name to write to
959
   * @param data - the object bytes as an input stream
960
   *
961
   * @return newFile - the new file created
962
   *
963
   * @throws ServiceFailure
964
   */
965
  private File writeStreamToFile(File dir, String fileName, InputStream data)
966
    throws ServiceFailure {
967
968
    File newFile = new File(dir, fileName);
969
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
970
971
    try {
972
        if (newFile.createNewFile()) {
973
          // write data stream to desired file
974
          OutputStream os = new FileOutputStream(newFile);
975
          long length = IOUtils.copyLarge(data, os);
976
          os.flush();
977
          os.close();
978
        } else {
979
          logMetacat.debug("File creation failed, or file already exists.");
980
          throw new ServiceFailure("1190", "File already exists: " + fileName);
981
        }
982
    } catch (FileNotFoundException e) {
983
      logMetacat.debug("FNF: " + e.getMessage());
984
      throw new ServiceFailure("1190", "File not found: " + fileName + " "
985
                + e.getMessage());
986
    } catch (IOException e) {
987
      logMetacat.debug("IOE: " + e.getMessage());
988
      throw new ServiceFailure("1190", "File was not written: " + fileName
989
                + " " + e.getMessage());
990
    }
991
992
    return newFile;
993
  }
994
995
}