Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000-2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: cjones $'
7
 *     '$Date: 2011-06-29 08:44:24 -0700 (Wed, 29 Jun 2011) $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23

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

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

    
44
import javax.servlet.http.HttpServletRequest;
45

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

    
74
import edu.ucsb.nceas.metacat.AccessionNumberException;
75
import edu.ucsb.nceas.metacat.DocumentImpl;
76
import edu.ucsb.nceas.metacat.EventLog;
77
import edu.ucsb.nceas.metacat.IdentifierManager;
78
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
79
import edu.ucsb.nceas.metacat.McdbException;
80
import edu.ucsb.nceas.metacat.MetacatHandler;
81
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
82
import edu.ucsb.nceas.metacat.properties.PropertyService;
83
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
84
import edu.ucsb.nceas.metacat.util.SessionData;
85
import edu.ucsb.nceas.utilities.ParseLSIDException;
86
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
87

    
88
public abstract class D1NodeService {
89
  
90
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
91

    
92
  /* the metacat URL as a string (including ending /d1 service)*/
93
  private String metacatUrl;
94
  
95
  /* reference to the metacat handler */
96
  private MetacatHandler handler;
97
  
98
  /* parameters set in the incoming request */
99
  private Hashtable<String, String[]> params;
100

    
101
  /**
102
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
103
   * 
104
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
105
   */
106
  public D1NodeService(String metacatUrl) {
107
    this.metacatUrl = metacatUrl;
108
    
109
  }
110
  
111
  /**
112
   * Adds a new object to the Node, where the object is either a data 
113
   * object or a science metadata object. This method is called by clients 
114
   * to create new data objects on Member Nodes or internally for Coordinating
115
   * Nodes
116
   * 
117
   * @param session - the Session object containing the credentials for the Subject
118
   * @param pid - The object identifier to be created
119
   * @param object - the object bytes
120
   * @param sysmeta - the system metadata that describes the object  
121
   * 
122
   * @return pid - the object identifier created
123
   * 
124
   * @throws InvalidToken
125
   * @throws ServiceFailure
126
   * @throws NotAuthorized
127
   * @throws IdentifierNotUnique
128
   * @throws UnsupportedType
129
   * @throws InsufficientResources
130
   * @throws InvalidSystemMetadata
131
   * @throws NotImplemented
132
   * @throws InvalidRequest
133
   */
134
  public Identifier create(Session session, Identifier pid, InputStream object,
135
    SystemMetadata sysmeta) 
136
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
137
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
138
    NotImplemented, InvalidRequest {
139

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

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

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

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

    
209
        }
210
                    
211
      }
212
        
213

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

    
221
    // setting the resulting identifier failed
222
    if (resultPid == null ) {
223
      throw new ServiceFailure("1190", "The Node is unable to create the object. " +
224
        "The resulting identifier was null.");
225
      
226
    }
227
    
228
    return resultPid;
229
  }
230

    
231
  /**
232
   * Return the log records associated with a given event between the start and 
233
   * end dates listed given a particular Subject listed in the Session
234
   * 
235
   * @param session - the Session object containing the credentials for the Subject
236
   * @param fromDate - the start date of the desired log records
237
   * @param toDate - the end date of the desired log records
238
   * @param event - restrict log records of a specific event type
239
   * @param start - zero based offset from the first record in the 
240
   *                set of matching log records. Used to assist with 
241
   *                paging the response.
242
   * @param count - maximum number of log records to return in the response. 
243
   *                Used to assist with paging the response.
244
   * 
245
   * @return the desired log records
246
   * 
247
   * @throws InvalidToken
248
   * @throws ServiceFailure
249
   * @throws NotAuthorized
250
   * @throws InvalidRequest
251
   * @throws NotImplemented
252
   */
253
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
254
      Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
255
      NotAuthorized, InvalidRequest, NotImplemented {
256

    
257

    
258
    Log log = new Log();
259
    Vector<LogEntry> logs = new Vector<LogEntry>();
260
    IdentifierManager im = IdentifierManager.getInstance();
261
    EventLog el = EventLog.getInstance();
262
    if (fromDate == null) {
263
      logMetacat.debug("setting fromdate from null");
264
      fromDate = new Date(1);
265
    }
266
    if (toDate == null) {
267
      logMetacat.debug("setting todate from null");
268
      toDate = new Date();
269
    }
270

    
271
    logMetacat.debug("fromDate: " + fromDate);
272
    logMetacat.debug("toDate: " + toDate);
273

    
274
    String report = el.getReport(null, null, null, null,
275
        new java.sql.Timestamp(fromDate.getTime()),
276
        new java.sql.Timestamp(toDate.getTime()), false);
277

    
278
    logMetacat.debug("report: " + report);
279

    
280
    String logEntry = "<logEntry>";
281
    String endLogEntry = "</logEntry>";
282
    int startIndex = 0;
283
    int foundIndex = report.indexOf(logEntry, startIndex);
284
    while (foundIndex != -1) {
285
      // parse out each entry
286
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
287
      String entry = report.substring(foundIndex, endEntryIndex);
288
      logMetacat.debug("entry: " + entry);
289
      startIndex = endEntryIndex + endLogEntry.length();
290
      foundIndex = report.indexOf(logEntry, startIndex);
291

    
292
      String entryId = getLogEntryField("entryid", entry);
293
      String ipAddress = getLogEntryField("ipAddress", entry);
294
      String principal = getLogEntryField("principal", entry);
295
      String docid = getLogEntryField("docid", entry);
296
      String eventS = getLogEntryField("event", entry);
297
      String dateLogged = getLogEntryField("dateLogged", entry);
298

    
299
      LogEntry le = new LogEntry();
300

    
301
      Event e = Event.convert(eventS);
302
      if (e == null) { // skip any events that are not Dataone Crud events
303
        continue;
304
      }
305
      le.setEvent(e);
306
      Identifier entryid = new Identifier();
307
      entryid.setValue(entryId);
308
      le.setEntryId(entryid);
309
      Identifier identifier = new Identifier();
310
      try {
311
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
312
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
313
          continue;
314
        }
315
        docid = docid.substring(0, docid.lastIndexOf("."));
316
        identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
317
      } catch (Exception ex) { 
318
        // try to get the pid, if that doesn't
319
        // work, just use the local id
320
        // throw new ServiceFailure("1030",
321
        // "Error getting pid for localId " +
322
        // docid + ": " + ex.getMessage());\
323

    
324
        // skip it if the pid can't be found
325
        continue;
326
      }
327

    
328
      le.setIdentifier(identifier);
329
      le.setIpAddress(ipAddress);
330
      Calendar c = Calendar.getInstance();
331
      String year = dateLogged.substring(0, 4);
332
      String month = dateLogged.substring(5, 7);
333
      String date = dateLogged.substring(8, 10);
334
      logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
335
      c.set(new Integer(year).intValue(), new Integer(month).intValue(),
336
          new Integer(date).intValue());
337
      Date logDate = c.getTime();
338
      le.setDateLogged(logDate);
339
      NodeReference memberNode = new NodeReference();
340
      memberNode.setValue(ipAddress);
341
      le.setMemberNode(memberNode);
342
      Subject princ = new Subject();
343
      princ.setValue(principal);
344
      le.setSubject(princ);
345
      le.setUserAgent("metacat/RESTService");
346

    
347
      if (event == null) {
348
        logs.add(le);
349
      }
350

    
351
      if (event != null
352
          && e.toString().toLowerCase().trim().equals(
353
              event.toString().toLowerCase().trim())) {
354
        logs.add(le);
355
      }
356
    }
357

    
358
    log.setLogEntryList(logs);
359
    logMetacat.info("getLogRecords");
360
    return log;
361
  }
362
    
363
  /**
364
   * Return the object identified by the given object identifier
365
   * 
366
   * @param session - the Session object containing the credentials for the Subject
367
   * @param pid - the object identifier for the given object
368
   * 
369
   * TODO: The D1 Authorization API doesn't provide information on which 
370
   * authentication system the Subject belongs to, and so it's not possible to
371
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
372
   * 
373
   * @return inputStream - the input stream of the given object
374
   * 
375
   * @throws InvalidToken
376
   * @throws ServiceFailure
377
   * @throws NotAuthorized
378
   * @throws InvalidRequest
379
   * @throws NotImplemented
380
   */
381
  public InputStream get(Session session, Identifier pid) 
382
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
383
    NotImplemented, InvalidRequest {
384
    
385
    InputStream inputStream = null; // bytes to be returned
386
    handler = new MetacatHandler(new Timer());
387
    boolean allowed = false;
388
    String localId; // the metacat docid for the pid
389
    
390
    // get the local docid from Metacat
391
    try {
392
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
393
    
394
    } catch (McdbDocNotFoundException e) {
395
      throw new NotFound("1020", "The object specified by " + 
396
                         pid.getValue() +
397
                         "does not exist at this node.");
398
    }
399
    
400
    // check for authorization
401
    allowed = isAuthorized(session, pid, Permission.READ);
402
    
403
    // if the person is authorized, perform the read
404
    if ( allowed ) {
405
      
406
      // get the object bytes
407
      // TODO: stream to file to stream conversion throughout Metacat needs to
408
      // be resolved
409
      File tmpDir;
410
      try
411
      {
412
          tmpDir = new File(PropertyService.getProperty("application.tempDir"));
413
      }
414
      catch(PropertyNotFoundException pnfe)
415
      {
416
          logMetacat.error("D1NodeService.get(): " +
417
                  "application.tmpDir not found.  Using /tmp instead.");
418
          tmpDir = new File("/tmp");
419
      }
420
      
421
      Date d = new Date();
422
      final File outputFile = new File(tmpDir, "metacat.output." + d.getTime());
423
      FileOutputStream dataSink;
424
      try {
425
        dataSink = new FileOutputStream(outputFile);
426
        handler.read(localId);
427

    
428
      } catch (FileNotFoundException e) {
429
        throw new ServiceFailure("1020", "The object specified by " + 
430
            pid.getValue() +
431
            "could not be returned due to a file read error: " +
432
            e.getMessage());
433
        
434
      } catch (PropertyNotFoundException e) {
435
        throw new ServiceFailure("1020", "The object specified by " + 
436
            pid.getValue() +
437
            "could not be returned due to an internal error: " +
438
            e.getMessage());
439
        
440
      } catch (ClassNotFoundException e) {
441
        throw new ServiceFailure("1020", "The object specified by " + 
442
            pid.getValue() +
443
            "could not be returned due to an internal error: " +
444
            e.getMessage());
445
        
446
      } catch (IOException e) {
447
        throw new ServiceFailure("1020", "The object specified by " + 
448
            pid.getValue() +
449
            "could not be returned due to a file read error: " +
450
            e.getMessage());
451
        
452
      } catch (SQLException e) {
453
        throw new ServiceFailure("1020", "The object specified by " + 
454
            pid.getValue() +
455
            "could not be returned due to a database error: " +
456
            e.getMessage());
457
        
458
      } catch (McdbException e) {
459
        throw new ServiceFailure("1020", "The object specified by " + 
460
            pid.getValue() +
461
            "could not be returned due to database error: " +
462
            e.getMessage());
463
        
464
      } catch (ParseLSIDException e) {
465
        throw new ServiceFailure("1020", "The object specified by " + 
466
            pid.getValue() +
467
            "could not be returned due to a parse error: " +
468
            e.getMessage());
469
        
470
      }
471
      
472
      //set a timer to clean up the temp files
473
      Timer t = new Timer();
474
      TimerTask tt = new TimerTask() {
475
          @Override
476
          public void run()
477
          {
478
              outputFile.delete();
479
          }
480
      };
481
      t.schedule(tt, 20000); //schedule after 20 secs
482
      
483
      try {
484
        inputStream = new FileInputStream(outputFile);
485
      } catch (FileNotFoundException e) {
486
        throw new ServiceFailure("1020", "The object specified by " + 
487
          pid.getValue() +
488
          "could not be returned due to a file read error: " +
489
          e.getMessage());
490
        
491
      }      
492
      
493
    }
494

    
495
    // if we fail to set the input stream
496
    if ( inputStream == null ) {
497
      throw new NotFound("1020", "The object specified by " + 
498
                         pid.getValue() +
499
                         "does not exist at this node.");
500
    }
501
    
502
    return inputStream;
503
  }
504

    
505
  /**
506
   * Return the system metadata for a given object
507
   * 
508
   * @param session - the Session object containing the credentials for the Subject
509
   * @param pid - the object identifier for the given object
510
   * 
511
   * @return inputStream - the input stream of the given system metadata object
512
   * 
513
   * @throws InvalidToken
514
   * @throws ServiceFailure
515
   * @throws NotAuthorized
516
   * @throws NotFound
517
   * @throws InvalidRequest
518
   * @throws NotImplemented
519
   */
520
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
521
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
522
    InvalidRequest, NotImplemented {
523

    
524
    if (!isAuthorized(session, pid, Permission.READ)) {
525
      throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
526
    }
527
    SystemMetadata systemMetadata = null;
528
    try {
529
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
530
    } catch (McdbDocNotFoundException e) {
531
      throw new NotFound("1420", "No record found for: " + pid.getValue());
532
    }
533
    
534
    return systemMetadata;
535
  }
536
   
537
  /**
538
   * Set access for a given object using the object identifier and a Subject
539
   * under a given Session.
540
   * 
541
   * @param session - the Session object containing the credentials for the Subject
542
   * @param pid - the object identifier for the given object to apply the policy
543
   * @param policy - the access policy to be applied
544
   * 
545
   * @return true if the application of the policy succeeds
546
   * @throws InvalidToken
547
   * @throws ServiceFailure
548
   * @throws NotFound
549
   * @throws NotAuthorized
550
   * @throws NotImplemented
551
   * @throws InvalidRequest
552
   */
553
  public boolean setAccessPolicy(Session session, Identifier pid, 
554
    AccessPolicy accessPolicy) 
555
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
556
    NotImplemented, InvalidRequest {
557

    
558
    boolean success = false;
559
    
560
    // get the subject
561
    Subject subject = session.getSubject();
562
    // get the system metadata
563
    String pidStr = pid.getValue();
564
    
565
    // are we allowed to do this?
566
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
567
      throw new NotAuthorized("4420", "not allowed by " + subject.getValue() + " on " + pidStr);  
568
    }
569
    
570
    SystemMetadata systemMetadata = null;
571
    try {
572
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
573
    } catch (McdbDocNotFoundException e) {
574
      throw new NotFound("4400", "No record found for: " + pid);
575
    }
576
        
577
    // set the access policy
578
    systemMetadata.setAccessPolicy(accessPolicy);
579
    
580
    // update the metadata
581
    try {
582
      IdentifierManager.getInstance().updateSystemMetadata(systemMetadata);
583
      success = true;
584
    } catch (McdbDocNotFoundException e) {
585
      throw new ServiceFailure("4430", e.getMessage());
586
    }
587

    
588
    return success;
589
  }
590
  
591
  /**
592
   * Test if the user identified by the provided token has authorization 
593
   * for operation on the specified object.
594
   * 
595
   * @param session - the Session object containing the credentials for the Subject
596
   * @param pid - The identifer of the resource for which access is being checked
597
   * @param operation - The type of operation which is being requested for the given pid
598
   *
599
   * @return true if the operation is allowed
600
   * 
601
   * @throws ServiceFailure
602
   * @throws InvalidToken
603
   * @throws NotFound
604
   * @throws NotAuthorized
605
   * @throws NotImplemented
606
   * @throws InvalidRequest
607
   */
608
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
609
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
610
    NotImplemented, InvalidRequest {
611

    
612
    boolean allowed = false;
613
    
614
    // get the subjects from the session
615
    List<Subject> subjects = new ArrayList<Subject>();
616
    subjects.add(session.getSubject());
617
    for (Person p: session.getSubjectList().getPersonList()) {
618
      subjects.add(p.getSubject());
619
    }
620
    for (Group g: session.getSubjectList().getGroupList()) {
621
      subjects.add(g.getSubject());
622
    }
623
    
624
    // get the system metadata
625
    String pidStr = pid.getValue();
626
    SystemMetadata systemMetadata = null;
627
    try {
628
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
629
    } catch (McdbDocNotFoundException e) {
630
      throw new NotFound("1800", "No record found for: " + pid);
631
    }
632
    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
633
    for (AccessRule accessRule: allows) {
634
      for (Subject subject: subjects) {
635
        if (accessRule.getSubjectList().contains(subject)) {
636
          allowed = accessRule.getPermissionList().contains(permission);
637
          if (allowed) {
638
            break;
639
          }
640
        }
641
      }
642
    }
643
    
644
    // TODO: throw or return?
645
    if (!allowed) {
646
      throw new NotAuthorized("1820", permission + "not allowed on " + pid);
647
    }
648
    return allowed;
649
    
650
  }
651
  
652
  /**
653
   * parse a logEntry and get the relevant field from it
654
   * 
655
   * @param fieldname
656
   * @param entry
657
   * @return
658
   */
659
  private String getLogEntryField(String fieldname, String entry) {
660
    String begin = "<" + fieldname + ">";
661
    String end = "</" + fieldname + ">";
662
    // logMetacat.debug("looking for " + begin + " and " + end +
663
    // " in entry " + entry);
664
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
665
        .indexOf(end));
666
    logMetacat.debug("entry " + fieldname + " : " + s);
667
    return s;
668
  }
669

    
670
  /**
671
   * set the params for this service from an HttpServletRequest param list
672
   * 
673
   * @param request - the HTTP Servlet Request with the listed parameters
674
   */
675
  public void setParamsFromRequest(HttpServletRequest request) {
676
      
677
    @SuppressWarnings("unchecked")
678
    Enumeration<String> paramlist = request.getParameterNames();
679
    while (paramlist.hasMoreElements()) {
680
      String name = (String) paramlist.nextElement();
681
      String[] value = (String[])request.getParameterValues(name);
682
      params.put(name, value);
683
        
684
    }
685
  }
686
  
687
  /** 
688
   * Determine if a given object should be treated as an XML science metadata
689
   * object. 
690
   * 
691
   * @param sysmeta - the SystemMetadata describing the object
692
   * @return true if the object should be treated as science metadata
693
   */
694
  private boolean isScienceMetadata(SystemMetadata sysmeta) {
695
    
696
    ObjectFormat objectFormat = null;
697
    boolean isScienceMetadata = false;
698
    
699
    try {
700
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getObjectFormat().getFmtid());
701
      isScienceMetadata = objectFormat.isScienceMetadata();
702
      
703
    } catch (InvalidRequest e) {
704
       logMetacat.debug("There was a problem determining if the object identified by" + 
705
         sysmeta.getIdentifier().getValue() + 
706
         " is science metadata: " + e.getMessage());
707
       
708
    } catch (ServiceFailure e) {
709
      logMetacat.debug("There was a problem determining if the object identified by" + 
710
          sysmeta.getIdentifier().getValue() + 
711
          " is science metadata: " + e.getMessage());
712
    
713
    } catch (NotFound e) {
714
      logMetacat.debug("There was a problem determining if the object identified by" + 
715
          sysmeta.getIdentifier().getValue() + 
716
          " is science metadata: " + e.getMessage());
717
    
718
    } catch (InsufficientResources e) {
719
      logMetacat.debug("There was a problem determining if the object identified by" + 
720
          sysmeta.getIdentifier().getValue() + 
721
          " is science metadata: " + e.getMessage());
722
    
723
    } catch (NotImplemented e) {
724
      logMetacat.debug("There was a problem determining if the object identified by" + 
725
          sysmeta.getIdentifier().getValue() + 
726
          " is science metadata: " + e.getMessage());
727
    
728
    }
729
    
730
    return isScienceMetadata;
731

    
732
  }
733
  
734
  /**
735
   * Insert or update an XML document into Metacat
736
   * 
737
   * @param xml - the XML document to insert or update
738
   * @param pid - the identifier to be used for the resulting object
739
   * 
740
   * @return localId - the resulting docid of the document created or updated
741
   * 
742
   */
743
  protected String insertOrUpdateDocument(String xml, Identifier pid, 
744
    Session session, String insertOrUpdate) 
745
    throws ServiceFailure {
746
    
747
  	logMetacat.debug("Starting to insert xml document...");
748
    IdentifierManager im = IdentifierManager.getInstance();
749

    
750
    // generate pid/localId pair for sysmeta
751
    String localId = null;
752
    
753
    if(insertOrUpdate.equals("insert")) {
754
      localId = im.generateLocalId(pid.getValue(), 1);
755
      
756
    } else {
757
      //localid should already exist in the identifier table, so just find it
758
      try {
759
        logMetacat.debug("Updating pid " + pid.getValue());
760
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
761
        
762
        localId = im.getLocalId(pid.getValue());
763
        
764
        logMetacat.debug("localId: " + localId);
765
        //increment the revision
766
        String docid = localId.substring(0, localId.lastIndexOf("."));
767
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
768
        int rev = new Integer(revS).intValue();
769
        rev++;
770
        docid = docid + "." + rev;
771
        localId = docid;
772
        logMetacat.debug("incremented localId: " + localId);
773
      
774
      } catch(McdbDocNotFoundException e) {
775
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
776
            "pid " + pid.getValue() + 
777
            " should have been in the identifier table, but it wasn't: " + 
778
            e.getMessage());
779
      
780
      }
781
      
782
    }
783

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

    
942
    try {
943
        if (newFile.createNewFile()) {
944
          // write data stream to desired file
945
          OutputStream os = new FileOutputStream(newFile);
946
          long length = IOUtils.copyLarge(data, os);
947
          os.flush();
948
          os.close();
949
        } else {
950
          logMetacat.debug("File creation failed, or file already exists.");
951
          throw new ServiceFailure("1190", "File already exists: " + fileName);
952
        }
953
    } catch (FileNotFoundException e) {
954
      logMetacat.debug("FNF: " + e.getMessage());
955
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
956
                + e.getMessage());
957
    } catch (IOException e) {
958
      logMetacat.debug("IOE: " + e.getMessage());
959
      throw new ServiceFailure("1190", "File was not written: " + fileName 
960
                + " " + e.getMessage());
961
    }
962

    
963
    return newFile;
964
  }
965
  
966
}
(3-3/8)