Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: $'
7
 *     '$Date: 2009-06-13 15:28:13 +0300  $'
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
package edu.ucsb.nceas.metacat.dataone;
24

    
25
import java.io.ByteArrayOutputStream;
26
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32
import java.io.PrintWriter;
33
import java.io.StringBufferInputStream;
34
import java.security.MessageDigest;
35
import java.sql.SQLException;
36
import java.util.*;
37
import java.text.DateFormat;
38

    
39
import javax.servlet.ServletContext;
40
import javax.servlet.http.HttpServletRequest;
41
import javax.servlet.http.HttpServletResponse;
42

    
43
import org.apache.commons.io.IOUtils;
44
import org.apache.log4j.Logger;
45
import org.dataone.service.exceptions.IdentifierNotUnique;
46
import org.dataone.service.exceptions.InsufficientResources;
47
import org.dataone.service.exceptions.InvalidRequest;
48
import org.dataone.service.exceptions.InvalidSystemMetadata;
49
import org.dataone.service.exceptions.InvalidToken;
50
import org.dataone.service.exceptions.NotAuthorized;
51
import org.dataone.service.exceptions.NotFound;
52
import org.dataone.service.exceptions.NotImplemented;
53
import org.dataone.service.exceptions.ServiceFailure;
54
import org.dataone.service.exceptions.UnsupportedType;
55
import org.dataone.service.mn.MemberNodeCrud;
56
import org.dataone.service.types.*;
57
import org.jibx.runtime.BindingDirectory;
58
import org.jibx.runtime.IBindingFactory;
59
import org.jibx.runtime.IMarshallingContext;
60
import org.jibx.runtime.IUnmarshallingContext;
61
import org.jibx.runtime.JiBXException;
62

    
63
import com.gc.iotools.stream.is.InputStreamFromOutputStream;
64

    
65
import edu.ucsb.nceas.metacat.AccessionNumberException;
66
import edu.ucsb.nceas.metacat.MetacatResultSet;
67
import edu.ucsb.nceas.metacat.MetacatResultSet.Document;
68
import edu.ucsb.nceas.metacat.DocumentImpl;
69
import edu.ucsb.nceas.metacat.EventLog;
70
import edu.ucsb.nceas.metacat.IdentifierManager;
71
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
72
import edu.ucsb.nceas.metacat.McdbException;
73
import edu.ucsb.nceas.metacat.MetacatHandler;
74
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
75
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
76
import edu.ucsb.nceas.metacat.properties.PropertyService;
77
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
78
import edu.ucsb.nceas.metacat.service.SessionService;
79
import edu.ucsb.nceas.metacat.util.DocumentUtil;
80
import edu.ucsb.nceas.metacat.util.SessionData;
81
import edu.ucsb.nceas.utilities.ParseLSIDException;
82
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
83

    
84
/**
85
 * 
86
 * Implements DataONE MemberNode CRUD API for Metacat. 
87
 * 
88
 * @author Matthew Jones
89
 */
90
public class CrudService implements MemberNodeCrud
91
{
92
    private static CrudService crudService = null;
93

    
94
    private MetacatHandler handler;
95
    private Hashtable<String, String[]> params;
96
    private Logger logMetacat = null;
97
    private Logger logCrud = null;
98
    
99
    private String metacatUrl;
100

    
101
    /**
102
     * singleton accessor
103
     */
104
    public static CrudService getInstance()
105
    {
106
      if(crudService == null)
107
      {
108
        crudService = new CrudService();
109
      }
110
      
111
      return crudService;
112
    }
113
    
114
    /**
115
     * Initializes new instance by setting servlet context,request and response.
116
     */
117
    public CrudService() {
118
    //change crud service into a singleton.  dont pass servlet data structures here
119
        logMetacat = Logger.getLogger(CrudService.class);
120
        logCrud = Logger.getLogger("DataOneLogger");
121
        try
122
        {
123
            String server = PropertyService.getProperty("server.name");
124
            String port = PropertyService.getProperty("server.httpPort");
125
            String context = PropertyService.getProperty("application.context");
126
            metacatUrl = "http://" + server + ":" + port + "/" + context;
127
            logMetacat.debug("Initializing CrudService with url " + metacatUrl);
128
        }
129
        catch(Exception e)
130
        {
131
            logMetacat.error("Could not find servlet url in CrudService: " + e.getMessage());
132
            e.printStackTrace();
133
            throw new RuntimeException("Error getting servlet url in CrudService: " + e.getMessage());
134
        }
135
        
136
        /*this.servletContext = servletContext;
137
        this.request = request;
138
        this.response = response;*/
139
        
140
        params = new Hashtable<String, String[]>();
141

    
142
        handler = new MetacatHandler(new Timer());
143

    
144
    }
145
    
146
    /**
147
     * return the context url CrudService is using.
148
     */
149
    public String getContextUrl()
150
    {
151
        return metacatUrl;
152
    }
153
    
154
    /**
155
     * Set the context url that this service uses.  It is normally not necessary
156
     * to call this method unless you are trying to connect to a server other
157
     * than the one in which this service is installed.  Otherwise, this value is
158
     * taken from the metacat.properties file (server.name, server.port, application.context).
159
     */
160
    public void setContextUrl(String url)
161
    {
162
        metacatUrl = url;
163
    }
164
    
165
    /**
166
     * set the params for this service from an HttpServletRequest param list
167
     */
168
    public void setParamsFromRequest(HttpServletRequest request)
169
    {
170
        Enumeration paramlist = request.getParameterNames();
171
        while (paramlist.hasMoreElements()) {
172
            String name = (String) paramlist.nextElement();
173
            String[] value = (String[])request.getParameterValues(name);
174
            params.put(name, value);
175
        }
176
    }
177
    
178
    /**
179
     * Authenticate against metacat and get a token.
180
     * @param username
181
     * @param password
182
     * @return
183
     * @throws ServiceFailure
184
     */
185
    public AuthToken authenticate(String username, String password)
186
      throws ServiceFailure
187
    {
188
        try
189
        {
190
            MetacatRestClient restClient = new MetacatRestClient(getContextUrl());   
191
            String response = restClient.login(username, password);
192
            String sessionid = restClient.getSessionId();
193
            SessionService sessionService = SessionService.getInstance();
194
            sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
195
            AuthToken token = new AuthToken(sessionid);
196
            EventLog.getInstance().log(metacatUrl,
197
                    username, null, "authenticate");
198
            logCrud.info("authenticate");
199
            return token;
200
        }
201
        catch(Exception e)
202
        {
203
            throw new ServiceFailure("1000", "Error authenticating with metacat: " + e.getMessage());
204
        }
205
    }
206
    
207
    /**
208
     * set the parameter values needed for this request
209
     */
210
    public void setParameter(String name, String[] value)
211
    {
212
        params.put(name, value);
213
    }
214
    
215
    /**
216
     * Generate SystemMetadata for any object in the object store that does
217
     * not already have it.  SystemMetadata documents themselves, are, of course,
218
     * exempt.  This is a utility method for migration of existing object 
219
     * stores to DataONE where SystemMetadata is required for all objects.  See 
220
     * https://trac.dataone.org/ticket/591
221
     * 
222
     * @param token an authtoken with appropriate permissions to read all 
223
     * documents in the object store.  To work correctly, this should probably
224
     * be an adminstrative credential.
225
     */
226
    public void generateMissingSystemMetadata(AuthToken token)
227
    {
228
        IdentifierManager im = IdentifierManager.getInstance();
229
        //get the list of ids with no SM
230
        List<String> l = im.getLocalIdsWithNoSystemMetadata();
231
        for(int i=0; i<l.size(); i++)
232
        { //for each id, add a system metadata doc
233
            String localId = l.get(i);
234
            //System.out.println("Creating SystemMetadata for localId " + localId);
235
            //get the document
236
            try
237
            {
238
                //generate required system metadata fields from the document
239
                SystemMetadata sm = createSystemMetadata(localId, token);
240
                //insert the systemmetadata object
241
                SessionData sessionData = getSessionData(token);
242
                insertSystemMetadata(sm, sessionData);
243
                
244
                String username = sessionData.getUserName();
245
                EventLog.getInstance().log(metacatUrl,
246
                        username, localId, "generateMissingSystemMetadata");
247
            }
248
            catch(Exception e)
249
            {
250
                //e.printStackTrace();
251
                System.out.println("Exception generating missing system metadata: " + e.getMessage());
252
                logMetacat.error("Could not generate missing system metadata: " + e.getMessage());
253
            }
254
        }
255
        logCrud.info("generateMissingSystemMetadata");
256
    }
257
    
258
    /**
259
     * create an object via the crud interface
260
     */
261
    public Identifier create(AuthToken token, Identifier guid, 
262
            InputStream object, SystemMetadata sysmeta) throws InvalidToken, 
263
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
264
            InsufficientResources, InvalidSystemMetadata, NotImplemented {
265

    
266
        logMetacat.debug("Starting CrudService.create()...");
267
        
268
        // authenticate & get user info
269
        SessionData sessionData = getSessionData(token);
270
        String username = sessionData.getUserName();
271
        String[] groups = sessionData.getGroupNames();
272
        String localId = null;
273

    
274
        if (username == null || username.equals("public"))
275
        {
276
            throw new NotAuthorized("1000", "User " + username + " is not authorized to create content." +
277
                    "  If you are not logged in, please do so and retry the request.");
278
        }
279
        
280
        // verify that guid == SystemMetadata.getIdentifier()
281
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
282
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
283
            throw new InvalidSystemMetadata("1180", 
284
                "GUID in method call does not match GUID in system metadata.");
285
        }
286

    
287
        logMetacat.debug("Checking if identifier exists...");
288
        // Check that the identifier does not already exist
289
        IdentifierManager im = IdentifierManager.getInstance();
290
        if (im.identifierExists(guid.getValue())) {
291
            throw new IdentifierNotUnique("1120", 
292
                "GUID is already in use by an existing object.");
293
        }
294

    
295
        // Check if we are handling metadata or data
296
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
297
        
298
        if (isScienceMetadata) {
299
            // CASE METADATA:
300
            try {
301
                this.insertDocument(object, guid, sessionData);
302
                localId = im.getLocalId(guid.getValue());
303
            } catch (IOException e) {
304
                String msg = "Could not create string from XML stream: " +
305
                    " " + e.getMessage();
306
                logMetacat.debug(msg);
307
                throw new ServiceFailure("1190", msg);
308
            } catch(Exception e) {
309
                String msg = "Unexpected error in CrudService.create: " + e.getMessage();
310
                logMetacat.debug(msg);
311
                throw new ServiceFailure("1190", msg);
312
            }
313
            
314

    
315
        } else {
316
            // DEFAULT CASE: DATA (needs to be checked and completed)
317
            insertDataObject(object, guid, sessionData);
318
            
319
        }
320

    
321
        // For Metadata and Data, insert the system metadata into the object store too
322
        insertSystemMetadata(sysmeta, sessionData);
323
        logMetacat.debug("Returning from CrudService.create()");
324
        EventLog.getInstance().log(metacatUrl,
325
                username, localId, "create");
326
        logCrud.info("create localId:" + localId + " guid:" + guid.getValue());
327
        return guid;
328
    }
329
    
330
    /**
331
     * update an existing object with a new object.  Change the system metadata
332
     * to reflect the changes and update it as well.
333
     */
334
    public Identifier update(AuthToken token, Identifier guid, 
335
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
336
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
337
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
338
            NotImplemented {
339
        try
340
        {
341
            SessionData sessionData = getSessionData(token);
342
            
343
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
344
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
345
            //change sm.old's obsoletedBy field 
346
            List l = sm.getObsoletedByList();
347
            l.add(guid);
348
            sm.setObsoletedByList(l);
349
            //update sm.old
350
            updateSystemMetadata(sm, sessionData);
351
            
352
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
353
            sysmeta.addObsolete(obsoletedGuid);
354
            //insert sm.new
355
            insertSystemMetadata(sysmeta, sessionData);
356
            
357
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
358
            if(isScienceMetadata)
359
            {
360
                //update the doc
361
                updateDocument(object, obsoletedGuid, guid, sessionData);
362
            }
363
            else
364
            {
365
                //update a data file, not xml
366
                insertDataObject(object, guid, sessionData);
367
            }
368
            
369
            IdentifierManager im = IdentifierManager.getInstance();
370
            String username = sessionData.getUserName();
371
            EventLog.getInstance().log(metacatUrl,
372
                    username, im.getLocalId(guid.getValue()), "update");
373
            logCrud.info("update localId:" + im.getLocalId(guid.getValue()) + " guid:" + guid.getValue());
374
            return guid;
375
        }
376
        catch(Exception e)
377
        {
378
            throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
379
        }
380
    }
381
    
382
    /**
383
     * set the permission on the document
384
     * @param token
385
     * @param principal
386
     * @param permission
387
     * @param permissionType
388
     * @param permissionOrder
389
     * @return
390
     */
391
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
392
            String permissionType, String permissionOrder)
393
      throws ServiceFailure
394
    {
395
        try
396
        {
397
            IdentifierManager im = IdentifierManager.getInstance();
398
            String docid = im.getLocalId(id.getValue());
399
            final SessionData sessionData = getSessionData(token);
400
            String permNum = "0";
401
            if(permission.equals("read"))
402
            {
403
                permNum = "4";
404
            }
405
            else if(permission.equals("write"))
406
            {
407
                permNum = "6";
408
            }
409
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
410
                    principal, permNum, permissionType, permissionOrder);
411
            
412
            String username = sessionData.getUserName();
413
            EventLog.getInstance().log(metacatUrl,
414
                    username, im.getLocalId(id.getValue()), "setAccess");
415
            logCrud.info("setAccess");
416
        }
417
        catch(Exception e)
418
        {
419
            e.printStackTrace();
420
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
421
        }
422
    }
423
    
424
    /**
425
     *  Retrieve the list of objects present on the MN that match the calling 
426
     *  parameters. This method is required to support the process of Member 
427
     *  Node synchronization. At a minimum, this method should be able to 
428
     *  return a list of objects that match:
429
     *  startTime <= SystemMetadata.dateSysMetadataModified
430
     *  but is expected to also support date range (by also specifying endTime), 
431
     *  and should also support slicing of the matching set of records by 
432
     *  indicating the starting index of the response (where 0 is the index 
433
     *  of the first item) and the count of elements to be returned.
434
     *  
435
     *  If startTime or endTime is null, the query is not restricted by that parameter.
436
     *  
437
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
438
     * @param token
439
     * @param startTime
440
     * @param endTime
441
     * @param objectFormat
442
     * @param replicaStatus
443
     * @param start
444
     * @param count
445
     * @return ObjectList
446
     * @throws NotAuthorized
447
     * @throws InvalidRequest
448
     * @throws NotImplemented
449
     * @throws ServiceFailure
450
     * @throws InvalidToken
451
     */
452
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
453
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
454
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
455
    {
456
      ObjectList ol = new ObjectList();
457
      final SessionData sessionData = getSessionData(token);
458
      int totalAfterQuery = 0;
459
      try
460
      {
461
          params.clear();
462
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
463
          params.put("qformat", new String[] {"xml"});
464
          params.put("returnfield", new String[] {"size", "originMemberNode", 
465
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "checksum/@algorithm"});
466
          params.put("anyfield", new String[] {"%"});
467
          
468
          //System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
469
          //    " sessionid: " + sessionData.getId() + " params: " + params.toString());
470
          
471
          MetacatResultSet rs = handler.query(metacatUrl, params, sessionData.getUserName(), 
472
                  sessionData.getGroupNames(), sessionData.getId());
473
          List docs = rs.getDocuments();
474
          if(count == 1000)
475
          {
476
              count = docs.size();
477
          }
478
          
479
          //System.out.println("query returned " + docs.size() + " documents.");
480
          Vector<Document> docCopy = new Vector<Document>();
481
          
482
          //preparse the list to remove any that don't match the query params
483
          for(int i=0; i<docs.size(); i++)
484
          {
485
              Document d = (Document)docs.get(i);
486
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
487
              
488
              if(returnedObjectFormat != null && 
489
                 objectFormat != null && 
490
                 !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
491
              { //make sure the objectFormat is the one specified
492
                  continue;
493
              }
494
              
495
              String dateSMM = d.getField("dateSysMetadataModified");
496
              //System.out.println("docid: " + d.docid + " dateSMM: " + dateSMM);
497
              if((startTime != null || endTime != null) && dateSMM == null)
498
              {  //if startTime or endTime are not null, we need a date to compare to
499
                  continue;
500
              }
501
              
502
              //date parse
503
              Date dateSysMetadataModified = null;
504
              if(dateSMM != null)
505
              {
506
                  dateSysMetadataModified = parseDate(dateSMM);
507
              }
508
              //System.out.println("dateSysMetadataModified: " + dateSysMetadataModified);
509
              //System.out.println("startTime: " + startTime);
510
              //System.out.println("endtime: " + endTime);
511
              int startDateComparison = 0;
512
              int endDateComparison = 0;
513
              if(startTime != null)
514
              {
515
                  if(dateSysMetadataModified == null)
516
                  {
517
                      startDateComparison = -1;
518
                  }
519
                  else
520
                  {
521
                      startDateComparison = dateSysMetadataModified.compareTo(startTime);
522
                  }
523
                  //System.out.println("startDateCom: " + startDateComparison);
524
              }
525
              else
526
              {
527
                  startDateComparison = 1;
528
              }
529
              
530
              if(endTime != null)
531
              {
532
                  if(dateSysMetadataModified == null)
533
                  {
534
                      endDateComparison = 1;
535
                  }
536
                  else
537
                  {
538
                      endDateComparison = dateSysMetadataModified.compareTo(endTime);
539
                  }
540
                  //System.out.println("endDateCom: " + endDateComparison);
541
              }
542
              else
543
              {
544
                  endDateComparison = -1;
545
              }
546
              
547
              
548
              if(startDateComparison < 0 || endDateComparison > 0)
549
              { 
550
                  continue;                  
551
              }
552
              
553
              docCopy.add((Document)docs.get(i));
554
          } //end pre-parse
555
          
556
          docs = docCopy;
557
          totalAfterQuery = docs.size();
558
          //System.out.println("total after subquery: " + totalAfterQuery);
559
          
560
          //make sure we don't run over the end
561
          int end = start + count;
562
          if(end > docs.size())
563
          {
564
              end = docs.size();
565
          }
566
          
567
          for(int i=start; i<end; i++)
568
          {
569
              //get the document from the result
570
              Document d = (Document)docs.get(i);
571
              //System.out.println("processing doc " + d.docid);
572
              
573
              String dateSMM = d.getField("dateSysMetadataModified");
574
              Date dateSysMetadataModified = null;
575
              if(dateSMM != null)
576
              {
577
                  try
578
                  {
579
                      dateSysMetadataModified = parseDate(dateSMM);
580
                  }
581
                  catch(Exception e)
582
                  { //if we fail to parse the date, just ignore the value
583
                      dateSysMetadataModified = null;
584
                  }
585
              }
586
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
587
                
588
              
589
              ObjectInfo info = new ObjectInfo();
590
              //add the fields to the info object
591
              Checksum cs = new Checksum();
592
              cs.setValue(d.getField("checksum"));
593
              String csalg = d.getField("algorithm");
594
              if(csalg == null)
595
              {
596
                  csalg = "MD5";
597
              }
598
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
599
              cs.setAlgorithm(ca);
600
              info.setChecksum(cs);
601
              info.setDateSysMetadataModified(dateSysMetadataModified);
602
              Identifier id = new Identifier();
603
              id.setValue(d.getField("identifier"));
604
              info.setIdentifier(id);
605
              info.setObjectFormat(returnedObjectFormat);
606
              String size = d.getField("size");
607
              if(size != null)
608
              {
609
                  info.setSize(new Long(size.trim()).longValue());
610
              }
611
              //add the ObjectInfo to the ObjectList
612
              if(info.getIdentifier().getValue() != null)
613
              { //id can be null from tests.  should not happen in production.
614
                  ol.addObjectInfo(info);
615
              }
616
          }
617
      }
618
      catch(Exception e)
619
      {
620
          e.printStackTrace();
621
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
622
      }
623
      String username = sessionData.getUserName();
624
      EventLog.getInstance().log(metacatUrl,
625
              username, null, "read");
626
      logCrud.info("listObjects");
627
      //System.out.println("ol.size: " + ol.sizeObjectInfoList());
628
      ol.setCount(count);
629
      ol.setStart(start);
630
      ol.setTotal(totalAfterQuery);
631
      return ol;
632
    }
633
    
634
    /**
635
     * Call listObjects with the default values for replicaStatus (true), start (0),
636
     * and count (1000).
637
     * @param token
638
     * @param startTime
639
     * @param endTime
640
     * @param objectFormat
641
     * @return
642
     * @throws NotAuthorized
643
     * @throws InvalidRequest
644
     * @throws NotImplemented
645
     * @throws ServiceFailure
646
     * @throws InvalidToken
647
     */
648
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
649
        ObjectFormat objectFormat)
650
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
651
    {
652
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
653
    }
654

    
655
    /**
656
     * Delete a document.  NOT IMPLEMENTED
657
     */
658
    public Identifier delete(AuthToken token, Identifier guid)
659
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
660
            NotImplemented {
661
        logCrud.info("delete");
662
        throw new NotImplemented("1000", "This method not yet implemented.");
663
    }
664

    
665
    /**
666
     * describe a document.  NOT IMPLEMENTED
667
     */
668
    public DescribeResponse describe(AuthToken token, Identifier guid)
669
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
670
            NotImplemented {
671
        logCrud.info("describe");
672
        throw new NotImplemented("1000", "This method not yet implemented.");
673
    }
674
    
675
    /**
676
     * get a document with a specified guid.
677
     */
678
    public InputStream get(AuthToken token, Identifier guid)
679
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
680
            NotImplemented {
681
        
682
        // Retrieve the session information from the AuthToken
683
        // If the session is expired, then the user is 'public'
684
        final SessionData sessionData = getSessionData(token);
685
        
686
        // Look up the localId for this global identifier
687
        IdentifierManager im = IdentifierManager.getInstance();
688
        try {
689
            final String localId = im.getLocalId(guid.getValue());
690

    
691
            final InputStreamFromOutputStream<String> objectStream = 
692
                new InputStreamFromOutputStream<String>() {
693
                
694
                @Override
695
                public String produce(final OutputStream dataSink) throws Exception {
696

    
697
                    try {
698
                        handler.readFromMetacat(metacatUrl, null, 
699
                                dataSink, localId, "xml",
700
                                sessionData.getUserName(), 
701
                                sessionData.getGroupNames(), true, params);
702
                    } catch (PropertyNotFoundException e) {
703
                        e.printStackTrace();
704
                        throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
705
                    } catch (ClassNotFoundException e) {
706
                        e.printStackTrace();
707
                        throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
708
                    } catch (IOException e) {
709
                        e.printStackTrace();
710
                        throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
711
                    } catch (SQLException e) {
712
                        e.printStackTrace();
713
                        throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
714
                    } catch (McdbException e) {
715
                        e.printStackTrace();
716
                        throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
717
                    } catch (ParseLSIDException e) {
718
                        e.printStackTrace();
719
                        throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
720
                    } catch (InsufficientKarmaException e) {
721
                        e.printStackTrace();
722
                        throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
723
                    }
724

    
725
                    return "Completed";
726
                }
727
            };
728
            
729
            String username = sessionData.getUserName();
730
            EventLog.getInstance().log(metacatUrl,
731
                    username, im.getLocalId(guid.getValue()), "read");
732
            logCrud.info("get localId:" + localId + " guid:" + guid.getValue());
733
            return objectStream;
734

    
735
        } catch (McdbDocNotFoundException e) {
736
            throw new NotFound("1020", e.getMessage());
737
        }
738
    }
739

    
740
    /**
741
     * get the checksum for a document.  NOT IMPLEMENTED
742
     */
743
    public Checksum getChecksum(AuthToken token, Identifier guid)
744
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
745
            InvalidRequest, NotImplemented {
746
        logCrud.info("getChecksum");
747
        throw new NotImplemented("1000", "This method not yet implemented.");
748
    }
749

    
750
    /**
751
     * get the checksum for a document.  NOT IMPLEMENTED
752
     */
753
    public Checksum getChecksum(AuthToken token, Identifier guid, 
754
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
755
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
756
        logCrud.info("getChecksum");
757
        throw new NotImplemented("1000", "This method not yet implemented.");
758
    }
759

    
760
    /**
761
     * get log records.  
762
     */
763
    public Log getLogRecords(AuthToken token, Date fromDate, Date toDate, Event event)
764
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
765
            NotImplemented 
766
    {
767
        Log log = new Log();
768
        Vector<LogEntry> logs = new Vector<LogEntry>();
769
        IdentifierManager im = IdentifierManager.getInstance();
770
        EventLog el = EventLog.getInstance();
771
        if(fromDate == null)
772
        {
773
            System.out.println("setting fromdate from null");
774
            fromDate = new Date(1);
775
        }
776
        if(toDate == null)
777
        {
778
            System.out.println("setting todate from null");
779
            toDate = new Date();
780
        }
781
        
782
        System.out.println("fromDate: " + fromDate);
783
        System.out.println("toDate: " + toDate);
784
        
785
        String report = el.getReport(null, null, null, null, 
786
                new java.sql.Timestamp(fromDate.getTime()), 
787
                new java.sql.Timestamp(toDate.getTime()));
788
        
789
        //System.out.println("report: " + report);
790
        
791
        String logEntry = "<logEntry>";
792
        String endLogEntry = "</logEntry>";
793
        int startIndex = 0;
794
        int foundIndex = report.indexOf(logEntry, startIndex);
795
        while(foundIndex != -1)
796
        {
797
            //parse out each entry
798
            int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
799
            String entry = report.substring(foundIndex, endEntryIndex);
800
            //System.out.println("entry: " + entry);
801
            startIndex = endEntryIndex + endLogEntry.length();
802
            foundIndex = report.indexOf(logEntry, startIndex);
803
            
804
            String entryId = getLogEntryField("entryid", entry);
805
            String ipAddress = getLogEntryField("ipAddress", entry);
806
            String principal = getLogEntryField("principal", entry);
807
            String docid = getLogEntryField("docid", entry);
808
            String eventS = getLogEntryField("event", entry);
809
            String dateLogged = getLogEntryField("dateLogged", entry);
810
            
811
            LogEntry le = new LogEntry();
812
            
813
            Event e = Event.convert(eventS);
814
            if(e == null)
815
            { //skip any events that are not Dataone Crud events
816
                continue;
817
            }
818
            le.setEvent(e);
819
            Identifier entryid = new Identifier();
820
            entryid.setValue(entryId);
821
            le.setEntryId(entryid);
822
            Identifier identifier = new Identifier();
823
            try
824
            {
825
                //System.out.println("converting docid '" + docid + "' to a guid.");
826
                if(docid == null || docid.trim().equals("") || docid.trim().equals("null"))
827
                {
828
                    continue;
829
                }
830
                docid = docid.substring(0, docid.lastIndexOf("."));
831
                identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
832
            }
833
            catch(Exception ex)
834
            { //try to get the guid, if that doesn't work, just use the local id
835
                throw new ServiceFailure("1030", "Error getting guid for localId " + 
836
                        docid + ": " + ex.getMessage());
837
            }
838
            
839
            le.setIdentifier(identifier);
840
            le.setIpAddress(ipAddress);
841
            Calendar c = Calendar.getInstance();
842
            String year = dateLogged.substring(0, 4);
843
            String month = dateLogged.substring(5, 7);
844
            String date = dateLogged.substring(8, 10);
845
            //System.out.println("year: " + year + " month: " + month + " day: " + date);
846
            c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
847
            Date logDate = c.getTime();
848
            le.setDateLogged(logDate);
849
            NodeReference memberNode = new NodeReference();
850
            memberNode.setValue(ipAddress);
851
            le.setMemberNode(memberNode);
852
            Principal princ = new Principal();
853
            princ.setValue(principal);
854
            le.setPrincipal(princ);
855
            le.setUserAgent("metacat/RESTService");
856
            
857
            if(event == null)
858
            {
859
                logs.add(le);
860
            }
861
            
862
            if(event != null &&
863
               e.toString().toLowerCase().trim().equals(event.toString().toLowerCase().trim()))
864
            {
865
              logs.add(le);
866
            }
867
        }
868
        
869
        log.setLogEntryList(logs);
870
        logCrud.info("getLogRecords");
871
        return log;
872
    }
873
    
874
    /**
875
     * parse a logEntry and get the relavent field from it
876
     * @param fieldname
877
     * @param entry
878
     * @return
879
     */
880
    private String getLogEntryField(String fieldname, String entry)
881
    {
882
        String begin = "<" + fieldname + ">";
883
        String end = "</" + fieldname + ">";
884
        //System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
885
        String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
886
        //System.out.println("entry " + fieldname + " : " + s);
887
        return s;
888
    }
889

    
890
    /**
891
     * get the system metadata for a document with a specified guid.
892
     */
893
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
894
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
895
            InvalidRequest, NotImplemented {
896
        
897
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
898
        
899
        // Retrieve the session information from the AuthToken
900
        // If the session is expired, then the user is 'public'
901
        final SessionData sessionData = getSessionData(token);
902
                
903
        try {
904
            IdentifierManager im = IdentifierManager.getInstance();
905
            final String localId = im.getSystemMetadataId(guid.getValue());
906
            
907
            // Read system metadata from metacat's db
908
            final InputStreamFromOutputStream<String> objectStream = 
909
                new InputStreamFromOutputStream<String>() {
910
                
911
                @Override
912
                public String produce(final OutputStream dataSink) throws Exception {
913
                    try {
914
                        handler.readFromMetacat(metacatUrl, null, 
915
                                dataSink, localId, "xml",
916
                                sessionData.getUserName(), 
917
                                sessionData.getGroupNames(), true, params);
918
                    } catch (PropertyNotFoundException e) {
919
                        e.printStackTrace();
920
                        throw new ServiceFailure("1030", "Property not found while reading system metadata from metacat: " + e.getMessage());
921
                    } catch (ClassNotFoundException e) {
922
                        e.printStackTrace();
923
                        throw new ServiceFailure("1030", "Class not found while reading system metadata from metacat: " + e.getMessage());
924
                    } catch (IOException e) {
925
                        e.printStackTrace();
926
                        throw new ServiceFailure("1030", "IOException while reading system metadata from metacat: " + e.getMessage());
927
                    } catch (SQLException e) {
928
                        e.printStackTrace();
929
                        throw new ServiceFailure("1030", "SQLException while reading system metadata from metacat: " + e.getMessage());
930
                    } catch (McdbException e) {
931
                        e.printStackTrace();
932
                        throw new ServiceFailure("1030", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
933
                    } catch (ParseLSIDException e) {
934
                        e.printStackTrace();
935
                        throw new NotFound("1020", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
936
                    } catch (InsufficientKarmaException e) {
937
                        e.printStackTrace();
938
                        throw new NotAuthorized("1000", "User not authorized for get() on system metadata: " + e.getMessage());
939
                    }
940

    
941
                    return "Completed";
942
                }
943
            };
944
            
945
            // Deserialize the xml to create a SystemMetadata object
946
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
947
            String username = sessionData.getUserName();
948
            EventLog.getInstance().log(metacatUrl,
949
                    username, im.getLocalId(guid.getValue()), "read");
950
            logCrud.info("getSystemMetadata localId: " + localId + " guid:" + guid.getValue());
951
            return sysmeta;
952
            
953
        } catch (McdbDocNotFoundException e) {
954
            //e.printStackTrace();
955
            throw new NotFound("1000", e.getMessage());
956
        }                
957
    }
958
    
959
    /**
960
     * parse the date in the systemMetadata
961
     * @param s
962
     * @return
963
     * @throws Exception
964
     */
965
    public Date parseDate(String s)
966
      throws Exception
967
    {
968
        Date d = null;
969
        int tIndex = s.indexOf("T");
970
        int zIndex = s.indexOf("Z");
971
        if(tIndex != -1 && zIndex != -1)
972
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
973
            //System.out.println("original date: " + s);
974
            
975
            String date = s.substring(0, tIndex);
976
            String year = date.substring(0, date.indexOf("-"));
977
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
978
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
979
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
980
                    " month: " + new Integer(month).intValue() + " day: " + 
981
                    new Integer(day).intValue());
982
            */
983
            String time = s.substring(tIndex + 1, zIndex);
984
            String hour = time.substring(0, time.indexOf(":"));
985
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
986
            String seconds = "00";
987
            String milliseconds = "00";
988
            if(time.indexOf(".") != -1)
989
            {
990
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
991
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
992
            }
993
            else
994
            {
995
                seconds = time.substring(time.lastIndexOf(":") + 1, time.length());
996
            }
997
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
998
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
999
                    new Integer(seconds).intValue() + " milli: " + 
1000
                    new Integer(milliseconds).intValue());*/
1001
            
1002
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
1003
            Calendar c = Calendar.getInstance(/*TimeZone.getTimeZone("GMT-0")*/TimeZone.getDefault());
1004
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
1005
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
1006
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
1007
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
1008
            d = new Date(c.getTimeInMillis());
1009
            //System.out.println("d: " + d);
1010
            return d;
1011
        }
1012
        else
1013
        {  //if it's not in the expected format, try the formatter
1014
            return DateFormat.getDateTimeInstance().parse(s);
1015
        }
1016
    }
1017

    
1018
    /*
1019
     * Look up the information on the session using the token provided in
1020
     * the AuthToken.  The Session should have all relevant user information.
1021
     * If the session has expired or is invalid, the 'public' session will
1022
     * be returned, giving the user anonymous access.
1023
     */
1024
    public static SessionData getSessionData(AuthToken token) {
1025
        SessionData sessionData = null;
1026
        String sessionId = "PUBLIC";
1027
        if (token != null) {
1028
            sessionId = token.getToken();
1029
        }
1030
        
1031
        // if the session id is registered in SessionService, get the
1032
        // SessionData for it. Otherwise, use the public session.
1033
        //System.out.println("sessionid: " + sessionId);
1034
        if (sessionId != null &&
1035
            !sessionId.toLowerCase().equals("public") &&
1036
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1037
        {
1038
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1039
        } else {
1040
            sessionData = SessionService.getInstance().getPublicSession();
1041
        }
1042
        
1043
        return sessionData;
1044
    }
1045

    
1046
    /** 
1047
     * Determine if a given object should be treated as an XML science metadata
1048
     * object. 
1049
     * 
1050
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1051
     * 
1052
     * @param sysmeta the SystemMetadata describig the object
1053
     * @return true if the object should be treated as science metadata
1054
     */
1055
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1056
        boolean scimeta = false;
1057
        switch (sysmeta.getObjectFormat()) {
1058
            case EML_2_1_0: scimeta = true; break;
1059
            case EML_2_0_1: scimeta = true; break;
1060
            case EML_2_0_0: scimeta = true; break;
1061
            case FGDC_STD_001_1_1999: scimeta = true; break;
1062
            case FGDC_STD_001_1998: scimeta = true; break;
1063
            case NCML_2_2: scimeta = true; break;
1064
        }
1065
        
1066
        return scimeta;
1067
    }
1068

    
1069
    /**
1070
     * insert a data doc
1071
     * @param object
1072
     * @param guid
1073
     * @param sessionData
1074
     * @throws ServiceFailure
1075
     */
1076
    private void insertDataObject(InputStream object, Identifier guid, 
1077
            SessionData sessionData) throws ServiceFailure {
1078
        
1079
        String username = sessionData.getUserName();
1080
        String[] groups = sessionData.getGroupNames();
1081

    
1082
        // generate guid/localId pair for object
1083
        logMetacat.debug("Generating a guid/localId mapping");
1084
        IdentifierManager im = IdentifierManager.getInstance();
1085
        String localId = im.generateLocalId(guid.getValue(), 1);
1086

    
1087
        try {
1088
            logMetacat.debug("Case DATA: starting to write to disk.");
1089
            if (DocumentImpl.getDataFileLockGrant(localId)) {
1090
    
1091
                // Save the data file to disk using "localId" as the name
1092
                try {
1093
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
1094
    
1095
                    File dataDirectory = new File(datafilepath);
1096
                    dataDirectory.mkdirs();
1097
    
1098
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
1099
    
1100
                    // TODO: Check that the file size matches SystemMetadata
1101
                    //                        long size = newFile.length();
1102
                    //                        if (size == 0) {
1103
                    //                            throw new IOException("Uploaded file is 0 bytes!");
1104
                    //                        }
1105
    
1106
                    // Register the file in the database (which generates an exception
1107
                    // if the localId is not acceptable or other untoward things happen
1108
                    try {
1109
                        logMetacat.debug("Registering document...");
1110
                        DocumentImpl.registerDocument(localId, "BIN", localId,
1111
                                username, groups);
1112
                        logMetacat.debug("Registration step completed.");
1113
                    } catch (SQLException e) {
1114
                        //newFile.delete();
1115
                        logMetacat.debug("SQLE: " + e.getMessage());
1116
                        e.printStackTrace(System.out);
1117
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1118
                    } catch (AccessionNumberException e) {
1119
                        //newFile.delete();
1120
                        logMetacat.debug("ANE: " + e.getMessage());
1121
                        e.printStackTrace(System.out);
1122
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1123
                    } catch (Exception e) {
1124
                        //newFile.delete();
1125
                        logMetacat.debug("Exception: " + e.getMessage());
1126
                        e.printStackTrace(System.out);
1127
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1128
                    }
1129
    
1130
                    logMetacat.debug("Logging the creation event.");
1131
                    EventLog.getInstance().log(metacatUrl,
1132
                            username, localId, "create");
1133
    
1134
                    // Schedule replication for this data file
1135
                    logMetacat.debug("Scheduling replication.");
1136
                    ForceReplicationHandler frh = new ForceReplicationHandler(
1137
                            localId, "create", false, null);
1138
    
1139
                } catch (PropertyNotFoundException e) {
1140
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1141
                }
1142
    
1143
            }
1144
        } catch (Exception e) {
1145
            // Could not get a lock on the document, so we can not update the file now
1146
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1147
        }
1148
    }
1149

    
1150
    /**
1151
     * write a file to a stream
1152
     * @param dir
1153
     * @param fileName
1154
     * @param data
1155
     * @return
1156
     * @throws ServiceFailure
1157
     */
1158
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1159
        throws ServiceFailure {
1160
        
1161
        File newFile = new File(dir, fileName);
1162
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1163

    
1164
        try {
1165
            if (newFile.createNewFile()) {
1166
                // write data stream to desired file
1167
                OutputStream os = new FileOutputStream(newFile);
1168
                long length = IOUtils.copyLarge(data, os);
1169
                os.flush();
1170
                os.close();
1171
            } else {
1172
                logMetacat.debug("File creation failed, or file already exists.");
1173
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1174
            }
1175
        } catch (FileNotFoundException e) {
1176
            logMetacat.debug("FNF: " + e.getMessage());
1177
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1178
                    + e.getMessage());
1179
        } catch (IOException e) {
1180
            logMetacat.debug("IOE: " + e.getMessage());
1181
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1182
                    + " " + e.getMessage());
1183
        }
1184

    
1185
        return newFile;
1186
    }
1187

    
1188
    /**
1189
     * insert a systemMetadata doc
1190
     */
1191
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1192
        throws ServiceFailure 
1193
    {
1194
        logMetacat.debug("Starting to insert SystemMetadata...");
1195
    
1196
        // generate guid/localId pair for sysmeta
1197
        Identifier sysMetaGuid = new Identifier();
1198
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1199
        sysmeta.setDateSysMetadataModified(new Date());
1200

    
1201
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
1202
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
1203
        //insert the system metadata doc id into the identifiers table to 
1204
        //link it to the data or metadata document
1205
        IdentifierManager.getInstance().createSystemMetadataMapping(
1206
                sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
1207
    }
1208
    
1209
    /**
1210
     * update a systemMetadata doc
1211
     */
1212
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1213
      throws ServiceFailure
1214
    {
1215
        try
1216
        {
1217
            String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
1218
            sm.setDateSysMetadataModified(new Date());
1219
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
1220
            Identifier id = new Identifier();
1221
            id.setValue(smId);
1222
            String localId = updateDocument(xml, id, null, sessionData);
1223
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
1224
        }
1225
        catch(Exception e)
1226
        {
1227
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
1228
        }
1229
    }
1230
    
1231
    /**
1232
     * insert a document
1233
     * NOTE: this method shouldn't be used from the update or create() methods.  
1234
     * we shouldn't be putting the science metadata or data objects into memory.
1235
     */
1236
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1237
        throws ServiceFailure
1238
    {
1239
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
1240
    }
1241
    
1242
    /**
1243
     * insert a document from a stream
1244
     */
1245
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1246
      throws IOException, ServiceFailure
1247
    {
1248
        //HACK: change this eventually.  we should not be converting the stream to a string
1249
        String xml = IOUtils.toString(is);
1250
        return insertDocument(xml, guid, sessionData);
1251
    }
1252
    
1253
    /**
1254
     * update a document
1255
     * NOTE: this method shouldn't be used from the update or create() methods.  
1256
     * we shouldn't be putting the science metadata or data objects into memory.
1257
     */
1258
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1259
        throws ServiceFailure
1260
    {
1261
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
1262
    }
1263
    
1264
    /**
1265
     * update a document from a stream
1266
     */
1267
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1268
      throws IOException, ServiceFailure
1269
    {
1270
        //HACK: change this eventually.  we should not be converting the stream to a string
1271
        String xml = IOUtils.toString(is);
1272
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
1273
        IdentifierManager im = IdentifierManager.getInstance();
1274
        if(guid != null)
1275
        {
1276
          im.createMapping(guid.getValue(), localId);
1277
        }
1278
        return localId;
1279
    }
1280
    
1281
    /**
1282
     * insert a document, return the id of the document that was inserted
1283
     */
1284
    protected String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
1285
        throws ServiceFailure {
1286
        logMetacat.debug("Starting to insert xml document...");
1287
        IdentifierManager im = IdentifierManager.getInstance();
1288

    
1289
        // generate guid/localId pair for sysmeta
1290
        String localId = null;
1291
        if(insertOrUpdate.equals("insert"))
1292
        {
1293
            localId = im.generateLocalId(guid.getValue(), 1);
1294
        }
1295
        else
1296
        {
1297
            //localid should already exist in the identifier table, so just find it
1298
            try
1299
            {
1300
                localId = im.getLocalId(guid.getValue());
1301
                //increment the revision
1302
                String docid = localId.substring(0, localId.lastIndexOf("."));
1303
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1304
                int rev = new Integer(revS).intValue();
1305
                rev++;
1306
                docid = docid + "." + rev;
1307
                localId = docid;
1308
            }
1309
            catch(McdbDocNotFoundException e)
1310
            {
1311
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1312
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1313
            }
1314
        }
1315
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1316
                localId);
1317

    
1318
        String[] action = new String[1];
1319
        action[0] = insertOrUpdate;
1320
        params.put("action", action);
1321
        String[] docid = new String[1];
1322
        docid[0] = localId;
1323
        params.put("docid", docid);
1324
        String[] doctext = new String[1];
1325
        doctext[0] = xml;
1326
        logMetacat.debug(doctext[0]);
1327
        params.put("doctext", doctext);
1328
        
1329
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1330
        // onto output stream, or alternatively, capture that and parse it to 
1331
        // generate the right exceptions
1332
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1333
        //PrintWriter pw = new PrintWriter(output);
1334
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1335
                            null, params, sessionData.getUserName(), sessionData.getGroupNames());
1336
        //String outputS = new String(output.toByteArray());
1337
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1338
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1339
        return localId;
1340
    }
1341
    
1342
    /**
1343
     * serialize a system metadata doc
1344
     * @param sysmeta
1345
     * @return
1346
     * @throws ServiceFailure
1347
     */
1348
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1349
        throws ServiceFailure {
1350
        IBindingFactory bfact;
1351
        ByteArrayOutputStream sysmetaOut = null;
1352
        try {
1353
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1354
            IMarshallingContext mctx = bfact.createMarshallingContext();
1355
            sysmetaOut = new ByteArrayOutputStream();
1356
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1357
        } catch (JiBXException e) {
1358
            e.printStackTrace();
1359
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1360
        }
1361
        
1362
        return sysmetaOut;
1363
    }
1364
    
1365
    /**
1366
     * deserialize a system metadata doc
1367
     * @param xml
1368
     * @return
1369
     * @throws ServiceFailure
1370
     */
1371
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1372
        throws ServiceFailure {
1373
        try {
1374
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1375
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1376
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1377
            return sysmeta;
1378
        } catch (JiBXException e) {
1379
            e.printStackTrace();
1380
            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1381
        }    
1382
    }
1383
    
1384
    /**
1385
     * produce an md5 checksum for item
1386
     */
1387
    private String checksum(InputStream is)
1388
      throws Exception
1389
    {        
1390
        byte[] buffer = new byte[1024];
1391
        MessageDigest complete = MessageDigest.getInstance("MD5");
1392
        int numRead;
1393
        
1394
        do 
1395
        {
1396
          numRead = is.read(buffer);
1397
          if (numRead > 0) 
1398
          {
1399
            complete.update(buffer, 0, numRead);
1400
          }
1401
        } while (numRead != -1);
1402
        
1403
        
1404
        return getHex(complete.digest());
1405
    }
1406
    
1407
    /**
1408
     * convert a byte array to a hex string
1409
     */
1410
    private static String getHex( byte [] raw ) 
1411
    {
1412
        final String HEXES = "0123456789ABCDEF";
1413
        if ( raw == null ) {
1414
          return null;
1415
        }
1416
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
1417
        for ( final byte b : raw ) {
1418
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
1419
             .append(HEXES.charAt((b & 0x0F)));
1420
        }
1421
        return hex.toString();
1422
    }
1423
    
1424
    /**
1425
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
1426
     * a proper date object
1427
     * @param date
1428
     * @return
1429
     */
1430
    private Date parseMetacatDate(String date)
1431
    {
1432
        String year = date.substring(0, 4);
1433
        String month = date.substring(5, 7);
1434
        String day = date.substring(8, 10);
1435
        Calendar c = Calendar.getInstance();
1436
        c.set(new Integer(year).intValue(), 
1437
              new Integer(month).intValue(), 
1438
              new Integer(day).intValue());
1439
        return c.getTime();
1440
    }
1441
    
1442
    /**
1443
     * find the size (in bytes) of a stream
1444
     * @param is
1445
     * @return
1446
     * @throws IOException
1447
     */
1448
    private long sizeOfStream(InputStream is)
1449
        throws IOException
1450
    {
1451
        long size = 0;
1452
        byte[] b = new byte[1024];
1453
        int numread = is.read(b, 0, 1024);
1454
        while(numread != -1)
1455
        {
1456
            size += numread;
1457
            numread = is.read(b, 0, 1024);
1458
        }
1459
        return size;
1460
    }
1461
    
1462
    /**
1463
     * create system metadata with a specified id, doc and format
1464
     */
1465
    private SystemMetadata createSystemMetadata(String localId, AuthToken token)
1466
      throws Exception
1467
    {
1468
        IdentifierManager im = IdentifierManager.getInstance();
1469
        Hashtable<String, String> docInfo = im.getDocumentInfo(localId);
1470
        
1471
        //get the document text
1472
        int rev = im.getLatestRevForLocalId(localId);
1473
        Identifier identifier = new Identifier();
1474
        identifier.setValue(im.getGUID(localId, rev));
1475
        InputStream is = this.get(token, identifier);
1476
        
1477
        SystemMetadata sm = new SystemMetadata();
1478
        //set the id
1479
        sm.setIdentifier(identifier);
1480
        
1481
        //set the object format
1482
        String doctype = docInfo.get("doctype");
1483
        ObjectFormat format = ObjectFormat.convert(docInfo.get("doctype"));
1484
        if(format == null)
1485
        {
1486
            if(doctype.trim().equals("BIN"))
1487
            {
1488
                format = ObjectFormat.APPLICATIONOCTETSTREAM;
1489
            }
1490
            else
1491
            {
1492
                format = ObjectFormat.convert("text/plain");
1493
            }
1494
        }
1495
        sm.setObjectFormat(format);
1496
        
1497
        //create the checksum
1498
        String checksumS = checksum(is);
1499
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
1500
        Checksum checksum = new Checksum();
1501
        checksum.setValue(checksumS);
1502
        checksum.setAlgorithm(ca);
1503
        sm.setChecksum(checksum);
1504
        
1505
        //set the size
1506
        is = this.get(token, identifier);
1507
        sm.setSize(sizeOfStream(is));
1508
        
1509
        //submitter
1510
        Principal p = new Principal();
1511
        p.setValue(docInfo.get("user_owner"));
1512
        sm.setSubmitter(p);
1513
        sm.setRightsHolder(p);
1514
        try
1515
        {
1516
            Date dateCreated = parseMetacatDate(docInfo.get("date_created"));
1517
            sm.setDateUploaded(dateCreated);
1518
            Date dateUpdated = parseMetacatDate(docInfo.get("date_updated"));
1519
            sm.setDateSysMetadataModified(dateUpdated);
1520
        }
1521
        catch(Exception e)
1522
        {
1523
            System.out.println("couldn't parse a date: " + e.getMessage());
1524
            Date dateCreated = new Date();
1525
            sm.setDateUploaded(dateCreated);
1526
            Date dateUpdated = new Date();
1527
            sm.setDateSysMetadataModified(dateUpdated);
1528
        }
1529
        NodeReference nr = new NodeReference();
1530
        nr.setValue("metacat");
1531
        sm.setOriginMemberNode(nr);
1532
        sm.setAuthoritativeMemberNode(nr);
1533
        return sm;
1534
    }
1535
}
(1-1/2)