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
      try
459
      {
460
          params.clear();
461
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
462
          params.put("qformat", new String[] {"xml"});
463
          params.put("returnfield", new String[] {"size", "originMemberNode", 
464
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "checksum/@algorithm"});
465
          params.put("anyfield", new String[] {"%"});
466
          
467
          MetacatResultSet rs = handler.query(metacatUrl, params, sessionData.getUserName(), 
468
                  sessionData.getGroupNames(), sessionData.getId());
469
          List docs = rs.getDocuments();
470
          if(count == 1000)
471
          {
472
              count = docs.size();
473
          }
474
          
475
          for(int i=start; i<count; i++)
476
          {
477
              //get the document from the result
478
              Document d = (Document)docs.get(i);
479
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
480
              if(returnedObjectFormat == null)
481
              {
482
                  continue;
483
              }
484
              if(objectFormat != null && !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
485
              { //make sure the objectFormat is the one specified
486
                  continue;
487
              }
488
              
489
              String dateSMM = d.getField("dateSysMetadataModified");
490
              if(dateSMM == null)
491
              {
492
                  continue;
493
              }
494
              Date dateSysMetadataModified = parseDate(dateSMM);
495
              int startDateComparison = 0;
496
              int endDateComparison = 0;
497
              if(startTime != null)
498
              {
499
                  startDateComparison = dateSysMetadataModified.compareTo(startTime);
500
              }
501
              
502
              if(endTime != null)
503
              {
504
                  endDateComparison = dateSysMetadataModified.compareTo(endTime);
505
              }
506
              
507
              if(startDateComparison < 0 || endDateComparison > 0)
508
              { //this date falls outside of the startTime and endTime params, so
509
                //skip it
510
                  continue;                  
511
              }
512
              
513
              ObjectInfo info = new ObjectInfo();
514
              //add the fields to the info object
515
              Checksum cs = new Checksum();
516
              cs.setValue(d.getField("checksum"));
517
              String csalg = d.getField("algorithm");
518
              if(csalg == null)
519
              {
520
                  csalg = "MD5";
521
              }
522
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
523
              cs.setAlgorithm(ca);
524
              info.setChecksum(cs);
525
              info.setDateSysMetadataModified(dateSysMetadataModified);
526
              Identifier id = new Identifier();
527
              id.setValue(d.getField("identifier"));
528
              info.setIdentifier(id);
529
              info.setObjectFormat(returnedObjectFormat);
530
              info.setSize(new Long(d.getField("size").trim()).longValue());
531
              //add the ObjectInfo to the ObjectList
532
              ol.addObjectInfo(info);
533
          }
534
      }
535
      catch(Exception e)
536
      {
537
          e.printStackTrace();
538
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
539
      }
540
      String username = sessionData.getUserName();
541
      EventLog.getInstance().log(metacatUrl,
542
              username, null, "read");
543
      logCrud.info("listObjects");
544
      return ol;
545
    }
546
    
547
    /**
548
     * Call listObjects with the default values for replicaStatus (true), start (0),
549
     * and count (1000).
550
     * @param token
551
     * @param startTime
552
     * @param endTime
553
     * @param objectFormat
554
     * @return
555
     * @throws NotAuthorized
556
     * @throws InvalidRequest
557
     * @throws NotImplemented
558
     * @throws ServiceFailure
559
     * @throws InvalidToken
560
     */
561
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
562
        ObjectFormat objectFormat)
563
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
564
    {
565
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
566
    }
567

    
568
    /**
569
     * Delete a document.  NOT IMPLEMENTED
570
     */
571
    public Identifier delete(AuthToken token, Identifier guid)
572
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
573
            NotImplemented {
574
        logCrud.info("delete");
575
        throw new NotImplemented("1000", "This method not yet implemented.");
576
    }
577

    
578
    /**
579
     * describe a document.  NOT IMPLEMENTED
580
     */
581
    public DescribeResponse describe(AuthToken token, Identifier guid)
582
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
583
            NotImplemented {
584
        logCrud.info("describe");
585
        throw new NotImplemented("1000", "This method not yet implemented.");
586
    }
587
    
588
    /**
589
     * get a document with a specified guid.
590
     */
591
    public InputStream get(AuthToken token, Identifier guid)
592
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
593
            NotImplemented {
594
        
595
        // Retrieve the session information from the AuthToken
596
        // If the session is expired, then the user is 'public'
597
        final SessionData sessionData = getSessionData(token);
598
        
599
        // Look up the localId for this global identifier
600
        IdentifierManager im = IdentifierManager.getInstance();
601
        try {
602
            final String localId = im.getLocalId(guid.getValue());
603

    
604
            final InputStreamFromOutputStream<String> objectStream = 
605
                new InputStreamFromOutputStream<String>() {
606
                
607
                @Override
608
                public String produce(final OutputStream dataSink) throws Exception {
609

    
610
                    try {
611
                        handler.readFromMetacat(metacatUrl, null, 
612
                                dataSink, localId, "xml",
613
                                sessionData.getUserName(), 
614
                                sessionData.getGroupNames(), true, params);
615
                    } catch (PropertyNotFoundException e) {
616
                        e.printStackTrace();
617
                        throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
618
                    } catch (ClassNotFoundException e) {
619
                        e.printStackTrace();
620
                        throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
621
                    } catch (IOException e) {
622
                        e.printStackTrace();
623
                        throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
624
                    } catch (SQLException e) {
625
                        e.printStackTrace();
626
                        throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
627
                    } catch (McdbException e) {
628
                        e.printStackTrace();
629
                        throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
630
                    } catch (ParseLSIDException e) {
631
                        e.printStackTrace();
632
                        throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
633
                    } catch (InsufficientKarmaException e) {
634
                        e.printStackTrace();
635
                        throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
636
                    }
637

    
638
                    return "Completed";
639
                }
640
            };
641
            
642
            String username = sessionData.getUserName();
643
            EventLog.getInstance().log(metacatUrl,
644
                    username, im.getLocalId(guid.getValue()), "read");
645
            logCrud.info("get localId:" + localId + " guid:" + guid.getValue());
646
            return objectStream;
647

    
648
        } catch (McdbDocNotFoundException e) {
649
            throw new NotFound("1020", e.getMessage());
650
        }
651
    }
652

    
653
    /**
654
     * get the checksum for a document.  NOT IMPLEMENTED
655
     */
656
    public Checksum getChecksum(AuthToken token, Identifier guid)
657
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
658
            InvalidRequest, NotImplemented {
659
        logCrud.info("getChecksum");
660
        throw new NotImplemented("1000", "This method not yet implemented.");
661
    }
662

    
663
    /**
664
     * get the checksum for a document.  NOT IMPLEMENTED
665
     */
666
    public Checksum getChecksum(AuthToken token, Identifier guid, 
667
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
668
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
669
        logCrud.info("getChecksum");
670
        throw new NotImplemented("1000", "This method not yet implemented.");
671
    }
672

    
673
    /**
674
     * get log records.  
675
     */
676
    public Log getLogRecords(AuthToken token, Date fromDate, Date toDate, Event event)
677
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
678
            NotImplemented 
679
    {
680
        Log log = new Log();
681
        Vector<LogEntry> logs = new Vector<LogEntry>();
682
        IdentifierManager im = IdentifierManager.getInstance();
683
        EventLog el = EventLog.getInstance();
684
        if(fromDate == null)
685
        {
686
            fromDate = new Date(1);
687
        }
688
        if(toDate == null)
689
        {
690
            toDate = new Date();
691
        }
692
        String report = el.getReport(null, null, null, null, 
693
                new java.sql.Timestamp(fromDate.getTime()), 
694
                new java.sql.Timestamp(toDate.getTime()));
695
        
696
        String logEntry = "<logEntry>";
697
        String endLogEntry = "</logEntry>";
698
        int startIndex = 0;
699
        int foundIndex = report.indexOf(logEntry, startIndex);
700
        while(foundIndex != -1)
701
        {
702
            //parse out each entry
703
            int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
704
            String entry = report.substring(foundIndex, endEntryIndex);
705
            //System.out.println("entry: " + entry);
706
            startIndex = endEntryIndex + endLogEntry.length();
707
            foundIndex = report.indexOf(logEntry, startIndex);
708
            
709
            String entryId = getLogEntryField("entryid", entry);
710
            String ipAddress = getLogEntryField("ipAddress", entry);
711
            String principal = getLogEntryField("principal", entry);
712
            String docid = getLogEntryField("docid", entry);
713
            String eventS = getLogEntryField("event", entry);
714
            String dateLogged = getLogEntryField("dateLogged", entry);
715
            
716
            LogEntry le = new LogEntry();
717
            
718
            Event e = Event.convert(eventS);
719
            if(e == null)
720
            { //skip any events that are not Dataone Crud events
721
                continue;
722
            }
723
            le.setEvent(e);
724
            Identifier entryid = new Identifier();
725
            entryid.setValue(entryId);
726
            le.setEntryId(entryid);
727
            Identifier identifier = new Identifier();
728
            try
729
            {
730
                identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
731
            }
732
            catch(Exception ex)
733
            { //try to get the guid, if that doesn't work, just use the local id
734
                identifier.setValue(docid);
735
            }
736
            
737
            le.setIdentifier(identifier);
738
            le.setIpAddress(ipAddress);
739
            Calendar c = Calendar.getInstance();
740
            String year = dateLogged.substring(0, 4);
741
            String month = dateLogged.substring(5, 7);
742
            String date = dateLogged.substring(8, 10);
743
            //System.out.println("year: " + year + " month: " + month + " day: " + date);
744
            c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
745
            Date logDate = c.getTime();
746
            le.setDateLogged(logDate);
747
            NodeReference memberNode = new NodeReference();
748
            memberNode.setValue(ipAddress);
749
            le.setMemberNode(memberNode);
750
            Principal princ = new Principal();
751
            princ.setValue(principal);
752
            le.setPrincipal(princ);
753
            le.setUserAgent("metacat/RESTService");
754
            
755
            if(event == null)
756
            {
757
                logs.add(le);
758
            }
759
            
760
            if(event != null &&
761
               e.toString().toLowerCase().trim().equals(event.toString().toLowerCase().trim()))
762
            {
763
              logs.add(le);
764
            }
765
        }
766
        
767
        log.setLogEntryList(logs);
768
        logCrud.info("getLogRecords");
769
        return log;
770
    }
771
    
772
    /**
773
     * parse a logEntry and get the relavent field from it
774
     * @param fieldname
775
     * @param entry
776
     * @return
777
     */
778
    private String getLogEntryField(String fieldname, String entry)
779
    {
780
        String begin = "<" + fieldname + ">";
781
        String end = "</" + fieldname + ">";
782
        //System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
783
        String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
784
        //System.out.println("entry " + fieldname + " : " + s);
785
        return s;
786
    }
787

    
788
    /**
789
     * get the system metadata for a document with a specified guid.
790
     */
791
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
792
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
793
            InvalidRequest, NotImplemented {
794
        
795
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
796
        
797
        // Retrieve the session information from the AuthToken
798
        // If the session is expired, then the user is 'public'
799
        final SessionData sessionData = getSessionData(token);
800
                
801
        try {
802
            IdentifierManager im = IdentifierManager.getInstance();
803
            final String localId = im.getSystemMetadataId(guid.getValue());
804
            
805
            // Read system metadata from metacat's db
806
            final InputStreamFromOutputStream<String> objectStream = 
807
                new InputStreamFromOutputStream<String>() {
808
                
809
                @Override
810
                public String produce(final OutputStream dataSink) throws Exception {
811
                    try {
812
                        handler.readFromMetacat(metacatUrl, null, 
813
                                dataSink, localId, "xml",
814
                                sessionData.getUserName(), 
815
                                sessionData.getGroupNames(), true, params);
816
                    } catch (PropertyNotFoundException e) {
817
                        e.printStackTrace();
818
                        throw new ServiceFailure("1030", "Property not found while reading system metadata from metacat: " + e.getMessage());
819
                    } catch (ClassNotFoundException e) {
820
                        e.printStackTrace();
821
                        throw new ServiceFailure("1030", "Class not found while reading system metadata from metacat: " + e.getMessage());
822
                    } catch (IOException e) {
823
                        e.printStackTrace();
824
                        throw new ServiceFailure("1030", "IOException while reading system metadata from metacat: " + e.getMessage());
825
                    } catch (SQLException e) {
826
                        e.printStackTrace();
827
                        throw new ServiceFailure("1030", "SQLException while reading system metadata from metacat: " + e.getMessage());
828
                    } catch (McdbException e) {
829
                        e.printStackTrace();
830
                        throw new ServiceFailure("1030", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
831
                    } catch (ParseLSIDException e) {
832
                        e.printStackTrace();
833
                        throw new NotFound("1020", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
834
                    } catch (InsufficientKarmaException e) {
835
                        e.printStackTrace();
836
                        throw new NotAuthorized("1000", "User not authorized for get() on system metadata: " + e.getMessage());
837
                    }
838

    
839
                    return "Completed";
840
                }
841
            };
842
            
843
            // Deserialize the xml to create a SystemMetadata object
844
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
845
            String username = sessionData.getUserName();
846
            EventLog.getInstance().log(metacatUrl,
847
                    username, im.getLocalId(guid.getValue()), "read");
848
            logCrud.info("getSystemMetadata localId: " + localId + " guid:" + guid.getValue());
849
            return sysmeta;
850
            
851
        } catch (McdbDocNotFoundException e) {
852
            //e.printStackTrace();
853
            throw new NotFound("1000", e.getMessage());
854
        }                
855
    }
856
    
857
    /**
858
     * parse the date in the systemMetadata
859
     * @param s
860
     * @return
861
     * @throws Exception
862
     */
863
    private Date parseDate(String s)
864
      throws Exception
865
    {
866
        Date d = null;
867
        int tIndex = s.indexOf("T");
868
        int zIndex = s.indexOf("Z");
869
        if(tIndex != -1 && zIndex != -1)
870
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
871
            //System.out.println("original date: " + s);
872
            
873
            String date = s.substring(0, tIndex);
874
            String year = date.substring(0, date.indexOf("-"));
875
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
876
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
877
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
878
                    " month: " + new Integer(month).intValue() + " day: " + 
879
                    new Integer(day).intValue());
880
            */
881
            String time = s.substring(tIndex + 1, zIndex);
882
            String hour = time.substring(0, time.indexOf(":"));
883
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
884
            String seconds = "00";
885
            String milliseconds = "00";
886
            if(time.indexOf(".") != -1)
887
            {
888
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
889
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
890
            }
891
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
892
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
893
                    new Integer(seconds).intValue() + " milli: " + 
894
                    new Integer(milliseconds).intValue());*/
895
            
896
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
897
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
898
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
899
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
900
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
901
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
902
            d = new Date(c.getTimeInMillis());
903
            //System.out.println("d: " + d);
904
            return d;
905
        }
906
        else
907
        {  //if it's not in the expected format, try the formatter
908
            return DateFormat.getDateTimeInstance().parse(s);
909
        }
910
    }
911

    
912
    /*
913
     * Look up the information on the session using the token provided in
914
     * the AuthToken.  The Session should have all relevant user information.
915
     * If the session has expired or is invalid, the 'public' session will
916
     * be returned, giving the user anonymous access.
917
     */
918
    public static SessionData getSessionData(AuthToken token) {
919
        SessionData sessionData = null;
920
        String sessionId = "PUBLIC";
921
        if (token != null) {
922
            sessionId = token.getToken();
923
        }
924
        
925
        // if the session id is registered in SessionService, get the
926
        // SessionData for it. Otherwise, use the public session.
927
        if (sessionId != null &&
928
            !sessionId.toLowerCase().equals("public") &&
929
            SessionService.getInstance().isSessionRegistered(sessionId)) 
930
        {
931
            //System.out.println("looking for registered session");
932
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
933
        } else {
934
            //System.out.println("returning public session");
935
            sessionData = SessionService.getInstance().getPublicSession();
936
        }
937
        
938
        return sessionData;
939
    }
940

    
941
    /** 
942
     * Determine if a given object should be treated as an XML science metadata
943
     * object. 
944
     * 
945
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
946
     * 
947
     * @param sysmeta the SystemMetadata describig the object
948
     * @return true if the object should be treated as science metadata
949
     */
950
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
951
        boolean scimeta = false;
952
        switch (sysmeta.getObjectFormat()) {
953
            case EML_2_1_0: scimeta = true; break;
954
            case EML_2_0_1: scimeta = true; break;
955
            case EML_2_0_0: scimeta = true; break;
956
            case FGDC_STD_001_1_1999: scimeta = true; break;
957
            case FGDC_STD_001_1998: scimeta = true; break;
958
            case NCML_2_2: scimeta = true; break;
959
        }
960
        
961
        return scimeta;
962
    }
963

    
964
    /**
965
     * insert a data doc
966
     * @param object
967
     * @param guid
968
     * @param sessionData
969
     * @throws ServiceFailure
970
     */
971
    private void insertDataObject(InputStream object, Identifier guid, 
972
            SessionData sessionData) throws ServiceFailure {
973
        
974
        String username = sessionData.getUserName();
975
        String[] groups = sessionData.getGroupNames();
976

    
977
        // generate guid/localId pair for object
978
        logMetacat.debug("Generating a guid/localId mapping");
979
        IdentifierManager im = IdentifierManager.getInstance();
980
        String localId = im.generateLocalId(guid.getValue(), 1);
981

    
982
        try {
983
            logMetacat.debug("Case DATA: starting to write to disk.");
984
            if (DocumentImpl.getDataFileLockGrant(localId)) {
985
    
986
                // Save the data file to disk using "localId" as the name
987
                try {
988
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
989
    
990
                    File dataDirectory = new File(datafilepath);
991
                    dataDirectory.mkdirs();
992
    
993
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
994
    
995
                    // TODO: Check that the file size matches SystemMetadata
996
                    //                        long size = newFile.length();
997
                    //                        if (size == 0) {
998
                    //                            throw new IOException("Uploaded file is 0 bytes!");
999
                    //                        }
1000
    
1001
                    // Register the file in the database (which generates an exception
1002
                    // if the localId is not acceptable or other untoward things happen
1003
                    try {
1004
                        logMetacat.debug("Registering document...");
1005
                        DocumentImpl.registerDocument(localId, "BIN", localId,
1006
                                username, groups);
1007
                        logMetacat.debug("Registration step completed.");
1008
                    } catch (SQLException e) {
1009
                        //newFile.delete();
1010
                        logMetacat.debug("SQLE: " + e.getMessage());
1011
                        e.printStackTrace(System.out);
1012
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1013
                    } catch (AccessionNumberException e) {
1014
                        //newFile.delete();
1015
                        logMetacat.debug("ANE: " + e.getMessage());
1016
                        e.printStackTrace(System.out);
1017
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1018
                    } catch (Exception e) {
1019
                        //newFile.delete();
1020
                        logMetacat.debug("Exception: " + e.getMessage());
1021
                        e.printStackTrace(System.out);
1022
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1023
                    }
1024
    
1025
                    logMetacat.debug("Logging the creation event.");
1026
                    EventLog.getInstance().log(metacatUrl,
1027
                            username, localId, "create");
1028
    
1029
                    // Schedule replication for this data file
1030
                    logMetacat.debug("Scheduling replication.");
1031
                    ForceReplicationHandler frh = new ForceReplicationHandler(
1032
                            localId, "create", false, null);
1033
    
1034
                } catch (PropertyNotFoundException e) {
1035
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1036
                }
1037
    
1038
            }
1039
        } catch (Exception e) {
1040
            // Could not get a lock on the document, so we can not update the file now
1041
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1042
        }
1043
    }
1044

    
1045
    /**
1046
     * write a file to a stream
1047
     * @param dir
1048
     * @param fileName
1049
     * @param data
1050
     * @return
1051
     * @throws ServiceFailure
1052
     */
1053
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1054
        throws ServiceFailure {
1055
        
1056
        File newFile = new File(dir, fileName);
1057
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1058

    
1059
        try {
1060
            if (newFile.createNewFile()) {
1061
                // write data stream to desired file
1062
                OutputStream os = new FileOutputStream(newFile);
1063
                long length = IOUtils.copyLarge(data, os);
1064
                os.flush();
1065
                os.close();
1066
            } else {
1067
                logMetacat.debug("File creation failed, or file already exists.");
1068
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1069
            }
1070
        } catch (FileNotFoundException e) {
1071
            logMetacat.debug("FNF: " + e.getMessage());
1072
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1073
                    + e.getMessage());
1074
        } catch (IOException e) {
1075
            logMetacat.debug("IOE: " + e.getMessage());
1076
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1077
                    + " " + e.getMessage());
1078
        }
1079

    
1080
        return newFile;
1081
    }
1082

    
1083
    /**
1084
     * insert a systemMetadata doc
1085
     */
1086
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1087
        throws ServiceFailure 
1088
    {
1089
        logMetacat.debug("Starting to insert SystemMetadata...");
1090
    
1091
        // generate guid/localId pair for sysmeta
1092
        Identifier sysMetaGuid = new Identifier();
1093
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1094
        sysmeta.setDateSysMetadataModified(new Date());
1095

    
1096
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
1097
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
1098
        //insert the system metadata doc id into the identifiers table to 
1099
        //link it to the data or metadata document
1100
        IdentifierManager.getInstance().createSystemMetadataMapping(
1101
                sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
1102
    }
1103
    
1104
    /**
1105
     * update a systemMetadata doc
1106
     */
1107
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1108
      throws ServiceFailure
1109
    {
1110
        try
1111
        {
1112
            String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
1113
            sm.setDateSysMetadataModified(new Date());
1114
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
1115
            Identifier id = new Identifier();
1116
            id.setValue(smId);
1117
            String localId = updateDocument(xml, id, null, sessionData);
1118
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
1119
        }
1120
        catch(Exception e)
1121
        {
1122
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
1123
        }
1124
    }
1125
    
1126
    /**
1127
     * insert a document
1128
     * NOTE: this method shouldn't be used from the update or create() methods.  
1129
     * we shouldn't be putting the science metadata or data objects into memory.
1130
     */
1131
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1132
        throws ServiceFailure
1133
    {
1134
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
1135
    }
1136
    
1137
    /**
1138
     * insert a document from a stream
1139
     */
1140
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1141
      throws IOException, ServiceFailure
1142
    {
1143
        //HACK: change this eventually.  we should not be converting the stream to a string
1144
        String xml = IOUtils.toString(is);
1145
        return insertDocument(xml, guid, sessionData);
1146
    }
1147
    
1148
    /**
1149
     * update a document
1150
     * NOTE: this method shouldn't be used from the update or create() methods.  
1151
     * we shouldn't be putting the science metadata or data objects into memory.
1152
     */
1153
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1154
        throws ServiceFailure
1155
    {
1156
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
1157
    }
1158
    
1159
    /**
1160
     * update a document from a stream
1161
     */
1162
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1163
      throws IOException, ServiceFailure
1164
    {
1165
        //HACK: change this eventually.  we should not be converting the stream to a string
1166
        String xml = IOUtils.toString(is);
1167
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
1168
        IdentifierManager im = IdentifierManager.getInstance();
1169
        if(guid != null)
1170
        {
1171
          im.createMapping(guid.getValue(), localId);
1172
        }
1173
        return localId;
1174
    }
1175
    
1176
    /**
1177
     * insert a document, return the id of the document that was inserted
1178
     */
1179
    protected String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
1180
        throws ServiceFailure {
1181
        logMetacat.debug("Starting to insert xml document...");
1182
        IdentifierManager im = IdentifierManager.getInstance();
1183

    
1184
        // generate guid/localId pair for sysmeta
1185
        String localId = null;
1186
        if(insertOrUpdate.equals("insert"))
1187
        {
1188
            localId = im.generateLocalId(guid.getValue(), 1);
1189
        }
1190
        else
1191
        {
1192
            //localid should already exist in the identifier table, so just find it
1193
            try
1194
            {
1195
                localId = im.getLocalId(guid.getValue());
1196
                //increment the revision
1197
                String docid = localId.substring(0, localId.lastIndexOf("."));
1198
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1199
                int rev = new Integer(revS).intValue();
1200
                rev++;
1201
                docid = docid + "." + rev;
1202
                localId = docid;
1203
            }
1204
            catch(McdbDocNotFoundException e)
1205
            {
1206
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1207
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1208
            }
1209
        }
1210
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1211
                localId);
1212

    
1213
        String[] action = new String[1];
1214
        action[0] = insertOrUpdate;
1215
        params.put("action", action);
1216
        String[] docid = new String[1];
1217
        docid[0] = localId;
1218
        params.put("docid", docid);
1219
        String[] doctext = new String[1];
1220
        doctext[0] = xml;
1221
        logMetacat.debug(doctext[0]);
1222
        params.put("doctext", doctext);
1223
        
1224
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1225
        // onto output stream, or alternatively, capture that and parse it to 
1226
        // generate the right exceptions
1227
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1228
        //PrintWriter pw = new PrintWriter(output);
1229
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1230
                            null, params, sessionData.getUserName(), sessionData.getGroupNames());
1231
        //String outputS = new String(output.toByteArray());
1232
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1233
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1234
        return localId;
1235
    }
1236
    
1237
    /**
1238
     * serialize a system metadata doc
1239
     * @param sysmeta
1240
     * @return
1241
     * @throws ServiceFailure
1242
     */
1243
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1244
        throws ServiceFailure {
1245
        IBindingFactory bfact;
1246
        ByteArrayOutputStream sysmetaOut = null;
1247
        try {
1248
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1249
            IMarshallingContext mctx = bfact.createMarshallingContext();
1250
            sysmetaOut = new ByteArrayOutputStream();
1251
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1252
        } catch (JiBXException e) {
1253
            e.printStackTrace();
1254
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1255
        }
1256
        
1257
        return sysmetaOut;
1258
    }
1259
    
1260
    /**
1261
     * deserialize a system metadata doc
1262
     * @param xml
1263
     * @return
1264
     * @throws ServiceFailure
1265
     */
1266
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1267
        throws ServiceFailure {
1268
        try {
1269
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1270
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1271
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1272
            return sysmeta;
1273
        } catch (JiBXException e) {
1274
            e.printStackTrace();
1275
            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1276
        }    
1277
    }
1278
    
1279
    /**
1280
     * produce an md5 checksum for item
1281
     */
1282
    private String checksum(InputStream is)
1283
      throws Exception
1284
    {        
1285
        byte[] buffer = new byte[1024];
1286
        MessageDigest complete = MessageDigest.getInstance("MD5");
1287
        int numRead;
1288
        
1289
        do 
1290
        {
1291
          numRead = is.read(buffer);
1292
          if (numRead > 0) 
1293
          {
1294
            complete.update(buffer, 0, numRead);
1295
          }
1296
        } while (numRead != -1);
1297
        
1298
        
1299
        return getHex(complete.digest());
1300
    }
1301
    
1302
    /**
1303
     * convert a byte array to a hex string
1304
     */
1305
    private static String getHex( byte [] raw ) 
1306
    {
1307
        final String HEXES = "0123456789ABCDEF";
1308
        if ( raw == null ) {
1309
          return null;
1310
        }
1311
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
1312
        for ( final byte b : raw ) {
1313
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
1314
             .append(HEXES.charAt((b & 0x0F)));
1315
        }
1316
        return hex.toString();
1317
    }
1318
    
1319
    /**
1320
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
1321
     * a proper date object
1322
     * @param date
1323
     * @return
1324
     */
1325
    private Date parseMetacatDate(String date)
1326
    {
1327
        String year = date.substring(0, 4);
1328
        String month = date.substring(5, 7);
1329
        String day = date.substring(8, 10);
1330
        Calendar c = Calendar.getInstance();
1331
        c.set(new Integer(year).intValue(), 
1332
              new Integer(month).intValue(), 
1333
              new Integer(day).intValue());
1334
        return c.getTime();
1335
    }
1336
    
1337
    /**
1338
     * find the size (in bytes) of a stream
1339
     * @param is
1340
     * @return
1341
     * @throws IOException
1342
     */
1343
    private long sizeOfStream(InputStream is)
1344
        throws IOException
1345
    {
1346
        long size = 0;
1347
        byte[] b = new byte[1024];
1348
        int numread = is.read(b, 0, 1024);
1349
        while(numread != -1)
1350
        {
1351
            size += numread;
1352
            numread = is.read(b, 0, 1024);
1353
        }
1354
        return size;
1355
    }
1356
    
1357
    /**
1358
     * create system metadata with a specified id, doc and format
1359
     */
1360
    private SystemMetadata createSystemMetadata(String localId, AuthToken token)
1361
      throws Exception
1362
    {
1363
        IdentifierManager im = IdentifierManager.getInstance();
1364
        Hashtable<String, String> docInfo = im.getDocumentInfo(localId);
1365
        
1366
        //get the document text
1367
        int rev = im.getLatestRevForLocalId(localId);
1368
        Identifier identifier = new Identifier();
1369
        identifier.setValue(im.getGUID(localId, rev));
1370
        InputStream is = this.get(token, identifier);
1371
        
1372
        SystemMetadata sm = new SystemMetadata();
1373
        //set the id
1374
        sm.setIdentifier(identifier);
1375
        
1376
        //set the object format
1377
        String doctype = docInfo.get("doctype");
1378
        ObjectFormat format = ObjectFormat.convert(docInfo.get("doctype"));
1379
        if(format == null)
1380
        {
1381
            if(doctype.trim().equals("BIN"))
1382
            {
1383
                format = ObjectFormat.APPLICATIONOCTETSTREAM;
1384
            }
1385
            else
1386
            {
1387
                format = ObjectFormat.convert("text/plain");
1388
            }
1389
        }
1390
        sm.setObjectFormat(format);
1391
        
1392
        //create the checksum
1393
        String checksumS = checksum(is);
1394
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
1395
        Checksum checksum = new Checksum();
1396
        checksum.setValue(checksumS);
1397
        checksum.setAlgorithm(ca);
1398
        sm.setChecksum(checksum);
1399
        
1400
        //set the size
1401
        is = this.get(token, identifier);
1402
        sm.setSize(sizeOfStream(is));
1403
        
1404
        //submitter
1405
        Principal p = new Principal();
1406
        p.setValue(docInfo.get("user_owner"));
1407
        sm.setSubmitter(p);
1408
        sm.setRightsHolder(p);
1409
        try
1410
        {
1411
            Date dateCreated = parseMetacatDate(docInfo.get("date_created"));
1412
            sm.setDateUploaded(dateCreated);
1413
            Date dateUpdated = parseMetacatDate(docInfo.get("date_updated"));
1414
            sm.setDateSysMetadataModified(dateUpdated);
1415
        }
1416
        catch(Exception e)
1417
        {
1418
            System.out.println("couldn't parse a date: " + e.getMessage());
1419
            Date dateCreated = new Date();
1420
            sm.setDateUploaded(dateCreated);
1421
            Date dateUpdated = new Date();
1422
            sm.setDateSysMetadataModified(dateUpdated);
1423
        }
1424
        NodeReference nr = new NodeReference();
1425
        nr.setValue("metacat");
1426
        sm.setOriginMemberNode(nr);
1427
        sm.setAuthoritativeMemberNode(nr);
1428
        return sm;
1429
    }
1430
}
(1-1/2)