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 6421 leinfelder
    if (session != null && session.getSubject() != null) {
453 6389 leinfelder
    	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 6412 leinfelder
    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 6227 cjones
    }
592
593 6293 leinfelder
    // add public subject
594
    Subject publicSubject = new Subject();
595
    publicSubject.setValue(Constants.PUBLIC_SUBJECT);
596
    subjects.add(publicSubject);
597
598 6227 cjones
    // get the system metadata
599 6241 cjones
    String pidStr = pid.getValue();
600 6227 cjones
    SystemMetadata systemMetadata = null;
601
    try {
602 6241 cjones
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
603 6227 cjones
    } catch (McdbDocNotFoundException e) {
604 6245 leinfelder
      throw new NotFound("1800", "No record found for " + pidStr);
605 6227 cjones
    }
606 6245 leinfelder
607 6293 leinfelder
    // 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 6245 leinfelder
    try {
617
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
618 6293 leinfelder
	    search: // label break
619 6245 leinfelder
	    for (AccessRule accessRule: allows) {
620
	      for (Subject s: subjects) {
621 6293 leinfelder
	        //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 6245 leinfelder
	        }
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 6227 cjones
638 6245 leinfelder
    // throw or return?
639 6227 cjones
    if (!allowed) {
640 6245 leinfelder
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
641 6227 cjones
    }
642 6245 leinfelder
643 6227 cjones
    return allowed;
644 6241 cjones
645 6227 cjones
  }
646
647 6256 cjones
  /*
648 6227 cjones
   * 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 6174 cjones
665 6257 cjones
  /**
666 6241 cjones
   * 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 6257 cjones
  protected boolean isScienceMetadata(SystemMetadata sysmeta) {
673 6241 cjones
674
    ObjectFormat objectFormat = null;
675
    boolean isScienceMetadata = false;
676
677
    try {
678 6384 cjones
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFmtid());
679 6402 cjones
      if ( objectFormat.getFormatType() == "METADATA" ) {
680
      	isScienceMetadata = true;
681
682
      }
683 6241 cjones
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 6226 cjones
713 6241 cjones
  }
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 6302 leinfelder
    String username = Constants.PUBLIC_SUBJECT;
776 6241 cjones
    String[] groupnames = null;
777 6302 leinfelder
    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 6241 cjones
    }
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 6255 cjones
  protected String insertDataObject(InputStream object, Identifier pid,
821 6241 cjones
          Session session) throws ServiceFailure {
822
823 6302 leinfelder
    String username = Constants.PUBLIC_SUBJECT;
824 6241 cjones
    String[] groupnames = null;
825 6302 leinfelder
    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 6241 cjones
    }
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 6255 cjones
914 6256 cjones
  /**
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 6276 leinfelder
	try {
927
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
928
929
	} catch (McdbDocNotFoundException e) {
930 6256 cjones
      throw new ServiceFailure("1030", "Error inserting system metadata: " +
931
      	e.getClass() + ": " + e.getMessage());
932
933
    }
934
935
  }
936
937
  /**
938 6255 cjones
   * 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 6241 cjones
   * 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
}