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 6402 cjones
      if ( objectFormat.getFormatType() == "METADATA" ) {
678
      	isScienceMetadata = true;
679
680
      }
681 6241 cjones
682
    } catch (InvalidRequest 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 (ServiceFailure 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 (NotFound 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
    } catch (InsufficientResources e) {
698
      logMetacat.debug("There was a problem determining if the object identified by" +
699
          sysmeta.getIdentifier().getValue() +
700
          " is science metadata: " + e.getMessage());
701
702
    } catch (NotImplemented e) {
703
      logMetacat.debug("There was a problem determining if the object identified by" +
704
          sysmeta.getIdentifier().getValue() +
705
          " is science metadata: " + e.getMessage());
706
707
    }
708
709
    return isScienceMetadata;
710 6226 cjones
711 6241 cjones
  }
712
713
  /**
714
   * Insert or update an XML document into Metacat
715
   *
716
   * @param xml - the XML document to insert or update
717
   * @param pid - the identifier to be used for the resulting object
718
   *
719
   * @return localId - the resulting docid of the document created or updated
720
   *
721
   */
722
  protected String insertOrUpdateDocument(String xml, Identifier pid,
723
    Session session, String insertOrUpdate)
724
    throws ServiceFailure {
725
726
  	logMetacat.debug("Starting to insert xml document...");
727
    IdentifierManager im = IdentifierManager.getInstance();
728
729
    // generate pid/localId pair for sysmeta
730
    String localId = null;
731
732
    if(insertOrUpdate.equals("insert")) {
733
      localId = im.generateLocalId(pid.getValue(), 1);
734
735
    } else {
736
      //localid should already exist in the identifier table, so just find it
737
      try {
738
        logMetacat.debug("Updating pid " + pid.getValue());
739
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
740
741
        localId = im.getLocalId(pid.getValue());
742
743
        logMetacat.debug("localId: " + localId);
744
        //increment the revision
745
        String docid = localId.substring(0, localId.lastIndexOf("."));
746
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
747
        int rev = new Integer(revS).intValue();
748
        rev++;
749
        docid = docid + "." + rev;
750
        localId = docid;
751
        logMetacat.debug("incremented localId: " + localId);
752
753
      } catch(McdbDocNotFoundException e) {
754
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
755
            "pid " + pid.getValue() +
756
            " should have been in the identifier table, but it wasn't: " +
757
            e.getMessage());
758
759
      }
760
761
    }
762
763
    String[] action = new String[1];
764
    action[0] = insertOrUpdate;
765
    params.put("action", action);
766
    String[] docid = new String[1];
767
    docid[0] = localId;
768
    params.put("docid", docid);
769
    String[] doctext = new String[1];
770
    doctext[0] = xml;
771
    params.put("doctext", doctext);
772
773 6302 leinfelder
    String username = Constants.PUBLIC_SUBJECT;
774 6241 cjones
    String[] groupnames = null;
775 6302 leinfelder
    if (session != null ) {
776
    	username = session.getSubject().getValue();
777
    	if (session.getSubjectList() != null) {
778
    		List<Group> groupList = session.getSubjectList().getGroupList();
779
    		if (groupList != null) {
780
    			groupnames = new String[groupList.size()];
781
    			for (int i = 0; i > groupList.size(); i++ ) {
782
    				groupnames[i] = groupList.get(i).getGroupName();
783
    			}
784
    		}
785
    	}
786 6241 cjones
    }
787
788
    // do the insert or update action
789
    String result = handler.handleInsertOrUpdateAction(metacatUrl, null,
790
                        null, params, username, groupnames);
791
792
    if(result.indexOf("<error>") != -1) {
793
    	String detailCode = "";
794
    	if ( insertOrUpdate.equals("insert") ) {
795
    		detailCode = "1190";
796
797
    	} else if ( insertOrUpdate.equals("update") ) {
798
    		detailCode = "1310";
799
800
    	}
801
        throw new ServiceFailure(detailCode,
802
          "Error inserting or updating document: " + result);
803
    }
804
    logMetacat.debug("Finsished inserting xml document with id " + localId);
805
806
    return localId;
807
  }
808
809
  /**
810
   * Insert a data document
811
   *
812
   * @param object
813
   * @param pid
814
   * @param sessionData
815
   * @throws ServiceFailure
816
   * @returns localId of the data object inserted
817
   */
818 6255 cjones
  protected String insertDataObject(InputStream object, Identifier pid,
819 6241 cjones
          Session session) throws ServiceFailure {
820
821 6302 leinfelder
    String username = Constants.PUBLIC_SUBJECT;
822 6241 cjones
    String[] groupnames = null;
823 6302 leinfelder
    if (session != null ) {
824
    	username = session.getSubject().getValue();
825
    	if (session.getSubjectList() != null) {
826
    		List<Group> groupList = session.getSubjectList().getGroupList();
827
    		if (groupList != null) {
828
    			groupnames = new String[groupList.size()];
829
    			for (int i = 0; i > groupList.size(); i++ ) {
830
    				groupnames[i] = groupList.get(i).getGroupName();
831
    			}
832
    		}
833
    	}
834 6241 cjones
    }
835
836
    // generate pid/localId pair for object
837
    logMetacat.debug("Generating a pid/localId mapping");
838
    IdentifierManager im = IdentifierManager.getInstance();
839
    String localId = im.generateLocalId(pid.getValue(), 1);
840
841
    try {
842
      logMetacat.debug("Case DATA: starting to write to disk.");
843
      if (DocumentImpl.getDataFileLockGrant(localId)) {
844
845
        // Save the data file to disk using "localId" as the name
846
        try {
847
          String datafilepath = PropertyService.getProperty("application.datafilepath");
848
849
          File dataDirectory = new File(datafilepath);
850
          dataDirectory.mkdirs();
851
852
          File newFile = writeStreamToFile(dataDirectory, localId, object);
853
854
          // TODO: Check that the file size matches SystemMetadata
855
          // long size = newFile.length();
856
          // if (size == 0) {
857
          //     throw new IOException("Uploaded file is 0 bytes!");
858
          // }
859
860
          // Register the file in the database (which generates an exception
861
          // if the localId is not acceptable or other untoward things happen
862
          try {
863
            logMetacat.debug("Registering document...");
864
            DocumentImpl.registerDocument(localId, "BIN", localId,
865
                    username, groupnames);
866
            logMetacat.debug("Registration step completed.");
867
868
          } catch (SQLException e) {
869
            //newFile.delete();
870
            logMetacat.debug("SQLE: " + e.getMessage());
871
            e.printStackTrace(System.out);
872
            throw new ServiceFailure("1190", "Registration failed: " +
873
            		e.getMessage());
874
875
          } catch (AccessionNumberException e) {
876
            //newFile.delete();
877
            logMetacat.debug("ANE: " + e.getMessage());
878
            e.printStackTrace(System.out);
879
            throw new ServiceFailure("1190", "Registration failed: " +
880
            	e.getMessage());
881
882
          } catch (Exception e) {
883
            //newFile.delete();
884
            logMetacat.debug("Exception: " + e.getMessage());
885
            e.printStackTrace(System.out);
886
            throw new ServiceFailure("1190", "Registration failed: " +
887
            	e.getMessage());
888
          }
889
890
          logMetacat.debug("Logging the creation event.");
891
          EventLog.getInstance().log(metacatUrl, username, localId, "create");
892
893
          // Schedule replication for this data file
894
          logMetacat.debug("Scheduling replication.");
895
          ForceReplicationHandler frh = new ForceReplicationHandler(
896
            localId, "create", false, null);
897
898
        } catch (PropertyNotFoundException e) {
899
          throw new ServiceFailure("1190", "Could not lock file for writing:" +
900
          	e.getMessage());
901
902
        }
903
      }
904
      return localId;
905
    } catch (Exception e) {
906
        // Could not get a lock on the document, so we can not update the file now
907
        throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
908
    }
909
910
  }
911 6255 cjones
912 6256 cjones
  /**
913
   * Insert a systemMetadata document and return its localId
914
   */
915
  protected void insertSystemMetadata(SystemMetadata sysmeta)
916
    throws ServiceFailure {
917
918
  	logMetacat.debug("Starting to insert SystemMetadata...");
919
    sysmeta.setDateSysMetadataModified(new Date());
920
    logMetacat.debug("Inserting new system metadata with modified date " +
921
        sysmeta.getDateSysMetadataModified());
922
923
    //insert the system metadata
924 6276 leinfelder
	try {
925
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
926
927
	} catch (McdbDocNotFoundException e) {
928 6256 cjones
      throw new ServiceFailure("1030", "Error inserting system metadata: " +
929
      	e.getClass() + ": " + e.getMessage());
930
931
    }
932
933
  }
934
935
  /**
936 6255 cjones
   * Update a systemMetadata document
937
   *
938
   * @param sysMeta - the system metadata object in the system to update
939
   */
940
  protected void updateSystemMetadata(SystemMetadata sysMeta)
941
    throws ServiceFailure {
942
943
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
944
    sysMeta.setDateSysMetadataModified(new Date());
945
    try {
946
	    IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
947
948
    } catch (McdbDocNotFoundException e) {
949
950
      throw new ServiceFailure("1030", "Error updating system metadata: " +
951
        e.getClass() + ": " + e.getMessage());
952
953
    }
954
955
  }
956
957
  /*
958 6241 cjones
   * Write a stream to a file
959
   *
960
   * @param dir - the directory to write to
961
   * @param fileName - the file name to write to
962
   * @param data - the object bytes as an input stream
963
   *
964
   * @return newFile - the new file created
965
   *
966
   * @throws ServiceFailure
967
   */
968
  private File writeStreamToFile(File dir, String fileName, InputStream data)
969
    throws ServiceFailure {
970
971
    File newFile = new File(dir, fileName);
972
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
973
974
    try {
975
        if (newFile.createNewFile()) {
976
          // write data stream to desired file
977
          OutputStream os = new FileOutputStream(newFile);
978
          long length = IOUtils.copyLarge(data, os);
979
          os.flush();
980
          os.close();
981
        } else {
982
          logMetacat.debug("File creation failed, or file already exists.");
983
          throw new ServiceFailure("1190", "File already exists: " + fileName);
984
        }
985
    } catch (FileNotFoundException e) {
986
      logMetacat.debug("FNF: " + e.getMessage());
987
      throw new ServiceFailure("1190", "File not found: " + fileName + " "
988
                + e.getMessage());
989
    } catch (IOException e) {
990
      logMetacat.debug("IOE: " + e.getMessage());
991
      throw new ServiceFailure("1190", "File was not written: " + fileName
992
                + " " + e.getMessage());
993
    }
994
995
    return newFile;
996
  }
997
998
}