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

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

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

    
1006
    /*
1007
     * Look up the information on the session using the token provided in
1008
     * the AuthToken.  The Session should have all relevant user information.
1009
     * If the session has expired or is invalid, the 'public' session will
1010
     * be returned, giving the user anonymous access.
1011
     */
1012
    public static SessionData getSessionData(AuthToken token) {
1013
        SessionData sessionData = null;
1014
        String sessionId = "PUBLIC";
1015
        if (token != null) {
1016
            sessionId = token.getToken();
1017
        }
1018
        
1019
        // if the session id is registered in SessionService, get the
1020
        // SessionData for it. Otherwise, use the public session.
1021
        //System.out.println("sessionid: " + sessionId);
1022
        if (sessionId != null &&
1023
            !sessionId.toLowerCase().equals("public") &&
1024
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1025
        {
1026
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1027
        } else {
1028
            sessionData = SessionService.getInstance().getPublicSession();
1029
        }
1030
        
1031
        return sessionData;
1032
    }
1033

    
1034
    /** 
1035
     * Determine if a given object should be treated as an XML science metadata
1036
     * object. 
1037
     * 
1038
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1039
     * 
1040
     * @param sysmeta the SystemMetadata describig the object
1041
     * @return true if the object should be treated as science metadata
1042
     */
1043
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1044
        boolean scimeta = false;
1045
        switch (sysmeta.getObjectFormat()) {
1046
            case EML_2_1_0: scimeta = true; break;
1047
            case EML_2_0_1: scimeta = true; break;
1048
            case EML_2_0_0: scimeta = true; break;
1049
            case FGDC_STD_001_1_1999: scimeta = true; break;
1050
            case FGDC_STD_001_1998: scimeta = true; break;
1051
            case NCML_2_2: scimeta = true; break;
1052
        }
1053
        
1054
        return scimeta;
1055
    }
1056

    
1057
    /**
1058
     * insert a data doc
1059
     * @param object
1060
     * @param guid
1061
     * @param sessionData
1062
     * @throws ServiceFailure
1063
     */
1064
    private void insertDataObject(InputStream object, Identifier guid, 
1065
            SessionData sessionData) throws ServiceFailure {
1066
        
1067
        String username = sessionData.getUserName();
1068
        String[] groups = sessionData.getGroupNames();
1069

    
1070
        // generate guid/localId pair for object
1071
        logMetacat.debug("Generating a guid/localId mapping");
1072
        IdentifierManager im = IdentifierManager.getInstance();
1073
        String localId = im.generateLocalId(guid.getValue(), 1);
1074

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

    
1138
    /**
1139
     * write a file to a stream
1140
     * @param dir
1141
     * @param fileName
1142
     * @param data
1143
     * @return
1144
     * @throws ServiceFailure
1145
     */
1146
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1147
        throws ServiceFailure {
1148
        
1149
        File newFile = new File(dir, fileName);
1150
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1151

    
1152
        try {
1153
            if (newFile.createNewFile()) {
1154
                // write data stream to desired file
1155
                OutputStream os = new FileOutputStream(newFile);
1156
                long length = IOUtils.copyLarge(data, os);
1157
                os.flush();
1158
                os.close();
1159
            } else {
1160
                logMetacat.debug("File creation failed, or file already exists.");
1161
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1162
            }
1163
        } catch (FileNotFoundException e) {
1164
            logMetacat.debug("FNF: " + e.getMessage());
1165
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1166
                    + e.getMessage());
1167
        } catch (IOException e) {
1168
            logMetacat.debug("IOE: " + e.getMessage());
1169
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1170
                    + " " + e.getMessage());
1171
        }
1172

    
1173
        return newFile;
1174
    }
1175

    
1176
    /**
1177
     * insert a systemMetadata doc
1178
     */
1179
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1180
        throws ServiceFailure 
1181
    {
1182
        logMetacat.debug("Starting to insert SystemMetadata...");
1183
    
1184
        // generate guid/localId pair for sysmeta
1185
        Identifier sysMetaGuid = new Identifier();
1186
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1187
        sysmeta.setDateSysMetadataModified(new Date());
1188

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

    
1277
        // generate guid/localId pair for sysmeta
1278
        String localId = null;
1279
        if(insertOrUpdate.equals("insert"))
1280
        {
1281
            localId = im.generateLocalId(guid.getValue(), 1);
1282
        }
1283
        else
1284
        {
1285
            //localid should already exist in the identifier table, so just find it
1286
            try
1287
            {
1288
                localId = im.getLocalId(guid.getValue());
1289
                //increment the revision
1290
                String docid = localId.substring(0, localId.lastIndexOf("."));
1291
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1292
                int rev = new Integer(revS).intValue();
1293
                rev++;
1294
                docid = docid + "." + rev;
1295
                localId = docid;
1296
            }
1297
            catch(McdbDocNotFoundException e)
1298
            {
1299
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1300
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1301
            }
1302
        }
1303
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1304
                localId);
1305

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