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 ServletContext servletContext;
93
    private HttpServletRequest request;
94
    private HttpServletResponse response;*/
95
    
96
    private static CrudService crudService = null;
97

    
98
    private MetacatHandler handler;
99
    private Hashtable<String, String[]> params;
100
    Logger logMetacat = null;
101
    
102
    private String metacatUrl;
103

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

    
146
        handler = new MetacatHandler(new Timer());
147

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

    
252
        logMetacat.debug("Starting CrudService.create()...");
253
        
254
        // authenticate & get user info
255
        SessionData sessionData = getSessionData(token);
256
        String username = sessionData.getUserName();
257
        String[] groups = sessionData.getGroupNames();
258

    
259
        if (username == null || username.equals("public"))
260
        {
261
            throw new NotAuthorized("1000", "User " + username + " is not authorized to create content." +
262
                    "  If you are not logged in, please do so and retry the request.");
263
        }
264
        
265
        // verify that guid == SystemMetadata.getIdentifier()
266
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
267
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
268
            throw new InvalidSystemMetadata("1180", 
269
                "GUID in method call does not match GUID in system metadata.");
270
        }
271

    
272
        logMetacat.debug("Checking if identifier exists...");
273
        // Check that the identifier does not already exist
274
        IdentifierManager im = IdentifierManager.getInstance();
275
        if (im.identifierExists(guid.getValue())) {
276
            throw new IdentifierNotUnique("1120", 
277
                "GUID is already in use by an existing object.");
278
        }
279

    
280
        // Check if we are handling metadata or data
281
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
282
        
283
        if (isScienceMetadata) {
284
            // CASE METADATA:
285
            try {
286
                this.insertDocument(object, guid, sessionData);
287
            } catch (IOException e) {
288
                String msg = "Could not create string from XML stream: " +
289
                    " " + e.getMessage();
290
                logMetacat.debug(msg);
291
                throw new ServiceFailure("1190", msg);
292
            }
293

    
294
        } else {
295
            // DEFAULT CASE: DATA (needs to be checked and completed)
296
            insertDataObject(object, guid, sessionData);
297
            
298
        }
299

    
300
        // For Metadata and Data, insert the system metadata into the object store too
301
        insertSystemMetadata(sysmeta, sessionData);
302

    
303
        logMetacat.debug("Returning from CrudService.create()");
304
        return guid;
305
    }
306
    
307
    /**
308
     * update an existing object with a new object.  Change the system metadata
309
     * to reflect the changes and update it as well.
310
     */
311
    public Identifier update(AuthToken token, Identifier guid, 
312
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
313
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
314
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
315
            NotImplemented {
316
        try
317
        {
318
            SessionData sessionData = getSessionData(token);
319
            
320
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
321
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
322
            //change sm.old's obsoletedBy field 
323
            List l = sm.getObsoletedByList();
324
            l.add(guid);
325
            sm.setObsoletedByList(l);
326
            //update sm.old
327
            updateSystemMetadata(sm, sessionData);
328
            
329
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
330
            sysmeta.addObsolete(obsoletedGuid);
331
            //insert sm.new
332
            insertSystemMetadata(sysmeta, sessionData);
333
            
334
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
335
            if(isScienceMetadata)
336
            {
337
                //update the doc
338
                updateDocument(object, obsoletedGuid, guid, sessionData);
339
            }
340
            else
341
            {
342
                //update a data file, not xml
343
                insertDataObject(object, guid, sessionData);
344
            }
345
            return guid;
346
        }
347
        catch(Exception e)
348
        {
349
            throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
350
        }
351
    }
352
    
353
    /**
354
     * set the permission on the document
355
     * @param token
356
     * @param principal
357
     * @param permission
358
     * @param permissionType
359
     * @param permissionOrder
360
     * @return
361
     */
362
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
363
            String permissionType, String permissionOrder)
364
      throws ServiceFailure
365
    {
366
        try
367
        {
368
            IdentifierManager im = IdentifierManager.getInstance();
369
            String docid = im.getLocalId(id.getValue());
370
            final SessionData sessionData = getSessionData(token);
371
            String permNum = "0";
372
            if(permission.equals("read"))
373
            {
374
                permNum = "4";
375
            }
376
            else if(permission.equals("write"))
377
            {
378
                permNum = "6";
379
            }
380
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
381
                    principal, permNum, permissionType, permissionOrder);
382
        }
383
        catch(Exception e)
384
        {
385
            e.printStackTrace();
386
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
387
        }
388
    }
389
    
390
    /**
391
     *  Retrieve the list of objects present on the MN that match the calling 
392
     *  parameters. This method is required to support the process of Member 
393
     *  Node synchronization. At a minimum, this method should be able to 
394
     *  return a list of objects that match:
395
     *  startTime <= SystemMetadata.dateSysMetadataModified
396
     *  but is expected to also support date range (by also specifying endTime), 
397
     *  and should also support slicing of the matching set of records by 
398
     *  indicating the starting index of the response (where 0 is the index 
399
     *  of the first item) and the count of elements to be returned.
400
     *  
401
     *  If startTime or endTime is null, the query is not restricted by that parameter.
402
     *  
403
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
404
     * @param token
405
     * @param startTime
406
     * @param endTime
407
     * @param objectFormat
408
     * @param replicaStatus
409
     * @param start
410
     * @param count
411
     * @return ObjectList
412
     * @throws NotAuthorized
413
     * @throws InvalidRequest
414
     * @throws NotImplemented
415
     * @throws ServiceFailure
416
     * @throws InvalidToken
417
     */
418
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
419
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
420
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
421
    {
422
      ObjectList ol = new ObjectList();
423
      final SessionData sessionData = getSessionData(token);
424
      try
425
      {
426
          params.clear();
427
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
428
          params.put("qformat", new String[] {"xml"});
429
          params.put("returnfield", new String[] {"size", "originMemberNode", 
430
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "@algorithm"});
431
          params.put("anyfield", new String[] {"%"});
432
          
433
          MetacatResultSet rs = handler.query(metacatUrl, params, sessionData.getUserName(), 
434
                  sessionData.getGroupNames(), sessionData.getId());
435
          List docs = rs.getDocuments();
436

    
437
          if(count == 1000)
438
          {
439
              count = docs.size();
440
          }
441
          for(int i=start; i<count; i++)
442
          {
443
              //get the document from the results
444
              Document d = (Document)docs.get(i);
445
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
446
              if(objectFormat != null && !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
447
              { //make sure the objectFormat is the one specified
448
                  continue;
449
              }
450
              Date dateSysMetadataModified = parseDate(d.getField("dateSysMetadataModified"));
451
              int startDateComparison = 0;
452
              int endDateComparison = 0;
453
              if(startTime != null)
454
              {
455
                  startDateComparison = dateSysMetadataModified.compareTo(startTime);
456
              }
457
              
458
              if(endTime != null)
459
              {
460
                  endDateComparison = dateSysMetadataModified.compareTo(endTime);
461
              }
462
              
463
              if(startDateComparison < 0 || endDateComparison > 0)
464
              { //this date falls outside of the startTime and endTime params, so
465
                //skip it
466
                  continue;                  
467
              }
468
              
469
              ObjectInfo info = new ObjectInfo();
470
              //add the fields to the info object
471
              Checksum cs = new Checksum();
472
              cs.setValue(d.getField("checksum"));
473
              String csalg = d.getField("algorithm");
474
              if(csalg == null)
475
              {
476
                  csalg = "MD5";
477
              }
478
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
479
              cs.setAlgorithm(ca);
480
              info.setChecksum(cs);
481
              info.setDateSysMetadataModified(dateSysMetadataModified);
482
              Identifier id = new Identifier();
483
              id.setValue(d.getField("identifier"));
484
              info.setIdentifier(id);
485
              info.setObjectFormat(returnedObjectFormat);
486
              info.setSize(new Long(d.getField("size").trim()).longValue());
487
              //add the ObjectInfo to the ObjectList
488
              ol.addObjectInfo(info);
489
              //System.out.println(d.toString());
490
          }
491
      }
492
      catch(Exception e)
493
      {
494
          e.printStackTrace();
495
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
496
      }
497
      return ol;
498
    }
499
    
500
    /**
501
     * Call listObjects with the default values for replicaStatus (true), start (0),
502
     * and count (1000).
503
     * @param token
504
     * @param startTime
505
     * @param endTime
506
     * @param objectFormat
507
     * @return
508
     * @throws NotAuthorized
509
     * @throws InvalidRequest
510
     * @throws NotImplemented
511
     * @throws ServiceFailure
512
     * @throws InvalidToken
513
     */
514
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
515
        ObjectFormat objectFormat)
516
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
517
    {
518
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
519
    }
520

    
521
    /**
522
     * Delete a document.  NOT IMPLEMENTED
523
     */
524
    public Identifier delete(AuthToken token, Identifier guid)
525
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
526
            NotImplemented {
527
        throw new NotImplemented("1000", "This method not yet implemented.");
528
    }
529

    
530
    /**
531
     * describe a document.  NOT IMPLEMENTED
532
     */
533
    public DescribeResponse describe(AuthToken token, Identifier guid)
534
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
535
            NotImplemented {
536
        throw new NotImplemented("1000", "This method not yet implemented.");
537
    }
538
    
539
    /**
540
     * get a document with a specified guid.
541
     */
542
    public InputStream get(AuthToken token, Identifier guid)
543
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
544
            NotImplemented {
545
        
546
        // Retrieve the session information from the AuthToken
547
        // If the session is expired, then the user is 'public'
548
        final SessionData sessionData = getSessionData(token);
549
        
550
        // Look up the localId for this global identifier
551
        IdentifierManager im = IdentifierManager.getInstance();
552
        try {
553
            final String localId = im.getLocalId(guid.getValue());
554

    
555
            final InputStreamFromOutputStream<String> objectStream = 
556
                new InputStreamFromOutputStream<String>() {
557
                
558
                @Override
559
                public String produce(final OutputStream dataSink) throws Exception {
560

    
561
                    try {
562
                        handler.readFromMetacat(metacatUrl, null, 
563
                                dataSink, localId, "xml",
564
                                sessionData.getUserName(), 
565
                                sessionData.getGroupNames(), true, params);
566
                    } catch (PropertyNotFoundException e) {
567
                        e.printStackTrace();
568
                        throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
569
                    } catch (ClassNotFoundException e) {
570
                        e.printStackTrace();
571
                        throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
572
                    } catch (IOException e) {
573
                        e.printStackTrace();
574
                        throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
575
                    } catch (SQLException e) {
576
                        e.printStackTrace();
577
                        throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
578
                    } catch (McdbException e) {
579
                        e.printStackTrace();
580
                        throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
581
                    } catch (ParseLSIDException e) {
582
                        e.printStackTrace();
583
                        throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
584
                    } catch (InsufficientKarmaException e) {
585
                        e.printStackTrace();
586
                        throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
587
                    }
588

    
589
                    return "Completed";
590
                }
591
            };
592
            return objectStream;
593

    
594
        } catch (McdbDocNotFoundException e) {
595
            throw new NotFound("1020", e.getMessage());
596
        }
597
    }
598

    
599
    /**
600
     * get the checksum for a document.  NOT IMPLEMENTED
601
     */
602
    public Checksum getChecksum(AuthToken token, Identifier guid)
603
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
604
            InvalidRequest, NotImplemented {
605
        throw new NotImplemented("1000", "This method not yet implemented.");
606
    }
607

    
608
    /**
609
     * get the checksum for a document.  NOT IMPLEMENTED
610
     */
611
    public Checksum getChecksum(AuthToken token, Identifier guid, 
612
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
613
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
614
        throw new NotImplemented("1000", "This method not yet implemented.");
615
    }
616

    
617
    /**
618
     * get log records.  NOT IMPLEMENTED
619
     */
620
    public LogRecordSet getLogRecords(AuthToken token, Date fromDate, Date toDate)
621
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
622
            NotImplemented {
623
        throw new NotImplemented("1000", "This method not yet implemented.");
624
    }
625

    
626
    /**
627
     * get the system metadata for a document with a specified guid.
628
     */
629
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
630
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
631
            InvalidRequest, NotImplemented {
632
        
633
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
634
        
635
        // Retrieve the session information from the AuthToken
636
        // If the session is expired, then the user is 'public'
637
        final SessionData sessionData = getSessionData(token);
638

    
639
        // TODO: Check access control rules
640
                
641
        try {
642
            IdentifierManager im = IdentifierManager.getInstance();
643
            final String localId = im.getSystemMetadataId(guid.getValue());
644
            
645
            // Read system metadata from metacat's db
646
            final InputStreamFromOutputStream<String> objectStream = 
647
                new InputStreamFromOutputStream<String>() {
648
                
649
                @Override
650
                public String produce(final OutputStream dataSink) throws Exception {
651
                    try {
652
                        handler.readFromMetacat(metacatUrl, null, 
653
                                dataSink, localId, "xml",
654
                                sessionData.getUserName(), 
655
                                sessionData.getGroupNames(), true, params);
656
                    } catch (PropertyNotFoundException e) {
657
                        e.printStackTrace();
658
                        throw new ServiceFailure("1030", "Property not found while reading system metadata from metacat: " + e.getMessage());
659
                    } catch (ClassNotFoundException e) {
660
                        e.printStackTrace();
661
                        throw new ServiceFailure("1030", "Class not found while reading system metadata from metacat: " + e.getMessage());
662
                    } catch (IOException e) {
663
                        e.printStackTrace();
664
                        throw new ServiceFailure("1030", "IOException while reading system metadata from metacat: " + e.getMessage());
665
                    } catch (SQLException e) {
666
                        e.printStackTrace();
667
                        throw new ServiceFailure("1030", "SQLException while reading system metadata from metacat: " + e.getMessage());
668
                    } catch (McdbException e) {
669
                        e.printStackTrace();
670
                        throw new ServiceFailure("1030", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
671
                    } catch (ParseLSIDException e) {
672
                        e.printStackTrace();
673
                        throw new NotFound("1020", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
674
                    } catch (InsufficientKarmaException e) {
675
                        e.printStackTrace();
676
                        throw new NotAuthorized("1000", "User not authorized for get() on system metadata: " + e.getMessage());
677
                    }
678

    
679
                    return "Completed";
680
                }
681
            };
682
            
683
            // Deserialize the xml to create a SystemMetadata object
684
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
685
            return sysmeta;
686
            
687
        } catch (McdbDocNotFoundException e) {
688
            //e.printStackTrace();
689
            throw new NotFound("1000", e.getMessage());
690
        }                
691
    }
692
    
693
    /**
694
     * parse the date in the systemMetadata
695
     * @param s
696
     * @return
697
     * @throws Exception
698
     */
699
    private Date parseDate(String s)
700
      throws Exception
701
    {
702
        Date d = null;
703
        int tIndex = s.indexOf("T");
704
        int zIndex = s.indexOf("Z");
705
        if(tIndex != -1 && zIndex != -1)
706
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
707
            //System.out.println("original date: " + s);
708
            
709
            String date = s.substring(0, tIndex);
710
            String year = date.substring(0, date.indexOf("-"));
711
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
712
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
713
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
714
                    " month: " + new Integer(month).intValue() + " day: " + 
715
                    new Integer(day).intValue());
716
            */
717
            String time = s.substring(tIndex + 1, zIndex);
718
            String hour = time.substring(0, time.indexOf(":"));
719
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
720
            String seconds = "00";
721
            String milliseconds = "00";
722
            if(time.indexOf(".") != -1)
723
            {
724
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
725
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
726
            }
727
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
728
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
729
                    new Integer(seconds).intValue() + " milli: " + 
730
                    new Integer(milliseconds).intValue());*/
731
            
732
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
733
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
734
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
735
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
736
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
737
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
738
            d = new Date(c.getTimeInMillis());
739
            //System.out.println("d: " + d);
740
            return d;
741
        }
742
        else
743
        {  //if it's not in the expected format, try the formatter
744
            return DateFormat.getDateTimeInstance().parse(s);
745
        }
746
    }
747

    
748
    /*
749
     * Look up the information on the session using the token provided in
750
     * the AuthToken.  The Session should have all relevant user information.
751
     * If the session has expired or is invalid, the 'public' session will
752
     * be returned, giving the user anonymous access.
753
     */
754
    protected static SessionData getSessionData(AuthToken token) {
755
        SessionData sessionData = null;
756
        String sessionId = "PUBLIC";
757
        if (token != null) {
758
            sessionId = token.getToken();
759
        }
760
        
761
        // if the session id is registered in SessionService, get the
762
        // SessionData for it. Otherwise, use the public session.
763
        if (SessionService.getInstance().isSessionRegistered(sessionId)) {
764
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
765
        } else {
766
            sessionData = SessionService.getInstance().getPublicSession();
767
        }
768
        
769
        return sessionData;
770
    }
771

    
772
    /** 
773
     * Determine if a given object should be treated as an XML science metadata
774
     * object. 
775
     * 
776
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
777
     * 
778
     * @param sysmeta the SystemMetadata describig the object
779
     * @return true if the object should be treated as science metadata
780
     */
781
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
782
        boolean scimeta = false;
783
        switch (sysmeta.getObjectFormat()) {
784
            case EML_2_1_0: scimeta = true; break;
785
            case EML_2_0_1: scimeta = true; break;
786
            case EML_2_0_0: scimeta = true; break;
787
            case FGDC_STD_001_1_1999: scimeta = true; break;
788
            case FGDC_STD_001_1998: scimeta = true; break;
789
            case NCML_2_2: scimeta = true; break;
790
        }
791
        
792
        return scimeta;
793
    }
794

    
795
    /**
796
     * insert a data doc
797
     * @param object
798
     * @param guid
799
     * @param sessionData
800
     * @throws ServiceFailure
801
     */
802
    private void insertDataObject(InputStream object, Identifier guid, 
803
            SessionData sessionData) throws ServiceFailure {
804
        
805
        String username = sessionData.getUserName();
806
        String[] groups = sessionData.getGroupNames();
807

    
808
        // generate guid/localId pair for object
809
        logMetacat.debug("Generating a guid/localId mapping");
810
        IdentifierManager im = IdentifierManager.getInstance();
811
        String localId = im.generateLocalId(guid.getValue(), 1);
812

    
813
        try {
814
            logMetacat.debug("Case DATA: starting to write to disk.");
815
            if (DocumentImpl.getDataFileLockGrant(localId)) {
816
    
817
                // Save the data file to disk using "localId" as the name
818
                try {
819
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
820
    
821
                    File dataDirectory = new File(datafilepath);
822
                    dataDirectory.mkdirs();
823
    
824
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
825
    
826
                    // TODO: Check that the file size matches SystemMetadata
827
                    //                        long size = newFile.length();
828
                    //                        if (size == 0) {
829
                    //                            throw new IOException("Uploaded file is 0 bytes!");
830
                    //                        }
831
    
832
                    // Register the file in the database (which generates an exception
833
                    // if the localId is not acceptable or other untoward things happen
834
                    try {
835
                        logMetacat.debug("Registering document...");
836
                        System.out.println("inserting data object: localId: " + localId);
837
                        DocumentImpl.registerDocument(localId, "BIN", localId,
838
                                username, groups);
839
                        logMetacat.debug("Registration step completed.");
840
                    } catch (SQLException e) {
841
                        //newFile.delete();
842
                        logMetacat.debug("SQLE: " + e.getMessage());
843
                        e.printStackTrace(System.out);
844
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
845
                    } catch (AccessionNumberException e) {
846
                        //newFile.delete();
847
                        logMetacat.debug("ANE: " + e.getMessage());
848
                        e.printStackTrace(System.out);
849
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
850
                    } catch (Exception e) {
851
                        //newFile.delete();
852
                        logMetacat.debug("Exception: " + e.getMessage());
853
                        e.printStackTrace(System.out);
854
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
855
                    }
856
    
857
                    logMetacat.debug("Logging the creation event.");
858
                    EventLog.getInstance().log(metacatUrl,
859
                            username, localId, "create");
860
    
861
                    // Schedule replication for this data file
862
                    logMetacat.debug("Scheduling replication.");
863
                    ForceReplicationHandler frh = new ForceReplicationHandler(
864
                            localId, "insert", false, null);
865
    
866
                } catch (PropertyNotFoundException e) {
867
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
868
                }
869
    
870
            }
871
        } catch (Exception e) {
872
            // Could not get a lock on the document, so we can not update the file now
873
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
874
        }
875
    }
876

    
877
    /**
878
     * write a file to a stream
879
     * @param dir
880
     * @param fileName
881
     * @param data
882
     * @return
883
     * @throws ServiceFailure
884
     */
885
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
886
        throws ServiceFailure {
887
        
888
        File newFile = new File(dir, fileName);
889
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
890

    
891
        try {
892
            if (newFile.createNewFile()) {
893
                // write data stream to desired file
894
                OutputStream os = new FileOutputStream(newFile);
895
                long length = IOUtils.copyLarge(data, os);
896
                os.flush();
897
                os.close();
898
            } else {
899
                logMetacat.debug("File creation failed, or file already exists.");
900
                throw new ServiceFailure("1190", "File already exists: " + fileName);
901
            }
902
        } catch (FileNotFoundException e) {
903
            logMetacat.debug("FNF: " + e.getMessage());
904
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
905
                    + e.getMessage());
906
        } catch (IOException e) {
907
            logMetacat.debug("IOE: " + e.getMessage());
908
            throw new ServiceFailure("1190", "File was not written: " + fileName 
909
                    + " " + e.getMessage());
910
        }
911

    
912
        return newFile;
913
    }
914

    
915
    /**
916
     * insert a systemMetadata doc
917
     */
918
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
919
        throws ServiceFailure 
920
    {
921
        logMetacat.debug("Starting to insert SystemMetadata...");
922
    
923
        // generate guid/localId pair for sysmeta
924
        Identifier sysMetaGuid = new Identifier();
925
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
926
        sysmeta.setDateSysMetadataModified(new Date());
927

    
928
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
929
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
930
        //insert the system metadata doc id into the identifiers table to 
931
        //link it to the data or metadata document
932
        IdentifierManager.getInstance().createSystemMetadataMapping(
933
                sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
934
    }
935
    
936
    /**
937
     * update a systemMetadata doc
938
     */
939
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
940
      throws ServiceFailure
941
    {
942
        try
943
        {
944
            String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
945
            sm.setDateSysMetadataModified(new Date());
946
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
947
            Identifier id = new Identifier();
948
            id.setValue(smId);
949
            String localId = updateDocument(xml, id, null, sessionData);
950
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
951
        }
952
        catch(Exception e)
953
        {
954
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
955
        }
956
    }
957
    
958
    /**
959
     * insert a document
960
     * NOTE: this method shouldn't be used from the update or create() methods.  
961
     * we shouldn't be putting the science metadata or data objects into memory.
962
     */
963
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
964
        throws ServiceFailure
965
    {
966
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
967
    }
968
    
969
    /**
970
     * insert a document from a stream
971
     */
972
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
973
      throws IOException, ServiceFailure
974
    {
975
        //HACK: change this eventually.  we should not be converting the stream to a string
976
        String xml = IOUtils.toString(is);
977
        return insertDocument(xml, guid, sessionData);
978
    }
979
    
980
    /**
981
     * update a document
982
     * NOTE: this method shouldn't be used from the update or create() methods.  
983
     * we shouldn't be putting the science metadata or data objects into memory.
984
     */
985
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
986
        throws ServiceFailure
987
    {
988
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
989
    }
990
    
991
    /**
992
     * update a document from a stream
993
     */
994
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
995
      throws IOException, ServiceFailure
996
    {
997
        //HACK: change this eventually.  we should not be converting the stream to a string
998
        String xml = IOUtils.toString(is);
999
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
1000
        IdentifierManager im = IdentifierManager.getInstance();
1001
        if(guid != null)
1002
        {
1003
          im.createMapping(guid.getValue(), localId);
1004
        }
1005
        return localId;
1006
    }
1007
    
1008
    /**
1009
     * insert a document, return the id of the document that was inserted
1010
     */
1011
    protected String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
1012
        throws ServiceFailure {
1013
        logMetacat.debug("Starting to insert xml document...");
1014
        IdentifierManager im = IdentifierManager.getInstance();
1015

    
1016
        // generate guid/localId pair for sysmeta
1017
        String localId = null;
1018
        if(insertOrUpdate.equals("insert"))
1019
        {
1020
            localId = im.generateLocalId(guid.getValue(), 1);
1021
        }
1022
        else
1023
        {
1024
            //localid should already exist in the identifier table, so just find it
1025
            try
1026
            {
1027
                localId = im.getLocalId(guid.getValue());
1028
                //increment the revision
1029
                String docid = localId.substring(0, localId.lastIndexOf("."));
1030
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1031
                int rev = new Integer(revS).intValue();
1032
                rev++;
1033
                docid = docid + "." + rev;
1034
                localId = docid;
1035
            }
1036
            catch(McdbDocNotFoundException e)
1037
            {
1038
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1039
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1040
            }
1041
        }
1042
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1043
                localId);
1044

    
1045
        String[] action = new String[1];
1046
        action[0] = insertOrUpdate;
1047
        params.put("action", action);
1048
        String[] docid = new String[1];
1049
        docid[0] = localId;
1050
        params.put("docid", docid);
1051
        String[] doctext = new String[1];
1052
        doctext[0] = xml;
1053
        logMetacat.debug(doctext[0]);
1054
        params.put("doctext", doctext);
1055
        
1056
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1057
        // onto output stream, or alternatively, capture that and parse it to 
1058
        // generate the right exceptions
1059
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1060
        //PrintWriter pw = new PrintWriter(output);
1061
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1062
                            null, params, sessionData.getUserName(), sessionData.getGroupNames());
1063
        //String outputS = new String(output.toByteArray());
1064
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1065
//        if (!(outputS.indexOf("<success>") > 0 && outputS.indexOf(localId) > 0)) {
1066
//            throw new ServiceFailure(1190, outputS);
1067
//        }
1068
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1069
        return localId;
1070
    }
1071
    
1072
    /**
1073
     * serialize a system metadata doc
1074
     * @param sysmeta
1075
     * @return
1076
     * @throws ServiceFailure
1077
     */
1078
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1079
        throws ServiceFailure {
1080
        IBindingFactory bfact;
1081
        ByteArrayOutputStream sysmetaOut = null;
1082
        try {
1083
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1084
            IMarshallingContext mctx = bfact.createMarshallingContext();
1085
            sysmetaOut = new ByteArrayOutputStream();
1086
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1087
        } catch (JiBXException e) {
1088
            e.printStackTrace();
1089
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1090
        }
1091
        
1092
        return sysmetaOut;
1093
    }
1094
    
1095
    /**
1096
     * deserialize a system metadata doc
1097
     * @param xml
1098
     * @return
1099
     * @throws ServiceFailure
1100
     */
1101
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1102
        throws ServiceFailure {
1103
        try {
1104
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1105
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1106
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1107
            return sysmeta;
1108
        } catch (JiBXException e) {
1109
            e.printStackTrace();
1110
            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1111
        }    
1112
    }
1113
    
1114
    /**
1115
     * produce an md5 checksum for item
1116
     */
1117
    private String checksum(InputStream is)
1118
      throws Exception
1119
    {        
1120
        byte[] buffer = new byte[1024];
1121
        MessageDigest complete = MessageDigest.getInstance("MD5");
1122
        int numRead;
1123
        
1124
        do 
1125
        {
1126
          numRead = is.read(buffer);
1127
          if (numRead > 0) 
1128
          {
1129
            complete.update(buffer, 0, numRead);
1130
          }
1131
        } while (numRead != -1);
1132
        
1133
        
1134
        return getHex(complete.digest());
1135
    }
1136
    
1137
    /**
1138
     * convert a byte array to a hex string
1139
     */
1140
    private static String getHex( byte [] raw ) 
1141
    {
1142
        final String HEXES = "0123456789ABCDEF";
1143
        if ( raw == null ) {
1144
          return null;
1145
        }
1146
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
1147
        for ( final byte b : raw ) {
1148
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
1149
             .append(HEXES.charAt((b & 0x0F)));
1150
        }
1151
        return hex.toString();
1152
    }
1153
    
1154
    /**
1155
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
1156
     * a proper date object
1157
     * @param date
1158
     * @return
1159
     */
1160
    private Date parseMetacatDate(String date)
1161
    {
1162
        String year = date.substring(0, 4);
1163
        String month = date.substring(5, 7);
1164
        String day = date.substring(8, 10);
1165
        Calendar c = Calendar.getInstance();
1166
        c.set(new Integer(year).intValue(), 
1167
              new Integer(month).intValue(), 
1168
              new Integer(day).intValue());
1169
        return c.getTime();
1170
    }
1171
    
1172
    /**
1173
     * find the size (in bytes) of a stream
1174
     * @param is
1175
     * @return
1176
     * @throws IOException
1177
     */
1178
    private long sizeOfStream(InputStream is)
1179
        throws IOException
1180
    {
1181
        long size = 0;
1182
        byte[] b = new byte[1024];
1183
        int numread = is.read(b, 0, 1024);
1184
        while(numread != -1)
1185
        {
1186
            size += numread;
1187
            numread = is.read(b, 0, 1024);
1188
        }
1189
        return size;
1190
    }
1191
    
1192
    /**
1193
     * create system metadata with a specified id, doc and format
1194
     */
1195
    private SystemMetadata createSystemMetadata(String localId, AuthToken token)
1196
      throws Exception
1197
    {
1198
        IdentifierManager im = IdentifierManager.getInstance();
1199
        Hashtable<String, String> docInfo = im.getDocumentInfo(localId);
1200
        
1201
        //get the document text
1202
        int rev = im.getLatestRevForLocalId(localId);
1203
        Identifier identifier = new Identifier();
1204
        identifier.setValue(im.getGUID(localId, rev));
1205
        InputStream is = this.get(token, identifier);
1206
        
1207
        SystemMetadata sm = new SystemMetadata();
1208
        //set the id
1209
        sm.setIdentifier(identifier);
1210
        
1211
        //set the object format
1212
        String doctype = docInfo.get("doctype");
1213
        ObjectFormat format = ObjectFormat.convert(docInfo.get("doctype"));
1214
        if(format == null)
1215
        {
1216
            if(doctype.trim().equals("BIN"))
1217
            {
1218
                format = ObjectFormat.APPLICATIONOCTETSTREAM;
1219
            }
1220
            else
1221
            {
1222
                format = ObjectFormat.convert("text/plain");
1223
            }
1224
        }
1225
        sm.setObjectFormat(format);
1226
        
1227
        //create the checksum
1228
        String checksumS = checksum(is);
1229
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
1230
        Checksum checksum = new Checksum();
1231
        checksum.setValue(checksumS);
1232
        checksum.setAlgorithm(ca);
1233
        sm.setChecksum(checksum);
1234
        
1235
        //set the size
1236
        is = this.get(token, identifier);
1237
        sm.setSize(sizeOfStream(is));
1238
        
1239
        //submitter
1240
        Principal p = new Principal();
1241
        p.setValue(docInfo.get("user_owner"));
1242
        sm.setSubmitter(p);
1243
        sm.setRightsHolder(p);
1244
        try
1245
        {
1246
            Date dateCreated = parseMetacatDate(docInfo.get("date_created"));
1247
            sm.setDateUploaded(dateCreated);
1248
            Date dateUpdated = parseMetacatDate(docInfo.get("date_updated"));
1249
            sm.setDateSysMetadataModified(dateUpdated);
1250
        }
1251
        catch(Exception e)
1252
        {
1253
            System.out.println("couldn't parse a date: " + e.getMessage());
1254
            Date dateCreated = new Date();
1255
            sm.setDateUploaded(dateCreated);
1256
            Date dateUpdated = new Date();
1257
            sm.setDateSysMetadataModified(dateUpdated);
1258
        }
1259
        NodeReference nr = new NodeReference();
1260
        nr.setValue("metacat");
1261
        sm.setOriginMemberNode(nr);
1262
        sm.setAuthoritativeMemberNode(nr);
1263
        return sm;
1264
    }
1265
}
(1-1/2)