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
import java.text.SimpleDateFormat;
39

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

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

    
64
import org.dataone.service.types.Identifier;
65

    
66
import com.gc.iotools.stream.is.InputStreamFromOutputStream;
67

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

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

    
98
    private MetacatHandler handler;
99
    private Hashtable<String, String[]> params;
100
    private Logger logMetacat = null;
101
    private Logger logCrud = null;
102
    
103
    private String metacatUrl;
104
    
105
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
106

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

    
148
        handler = new MetacatHandler(new Timer());
149

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

    
292
        if (username == null || username.equals("public"))
293
        {
294
            //TODO: many of the thrown exceptions do not use the correct error codes
295
            //check these against the docs and correct them
296
            throw new NotAuthorized("1000", "User " + username + " is not authorized to create content." +
297
                    "  If you are not logged in, please do so and retry the request.");
298
        }
299
        
300
        // verify that guid == SystemMetadata.getIdentifier()
301
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
302
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
303
            throw new InvalidSystemMetadata("1180", 
304
                "GUID in method call does not match GUID in system metadata.");
305
        }
306

    
307
        logMetacat.debug("Checking if identifier exists...");
308
        // Check that the identifier does not already exist
309
        IdentifierManager im = IdentifierManager.getInstance();
310
        if (im.identifierExists(guid.getValue())) {
311
            throw new IdentifierNotUnique("1120", 
312
                "GUID is already in use by an existing object.");
313
        }
314

    
315
        // Check if we are handling metadata or data
316
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
317
        
318
        /* TODO:
319
         * For EML documents, the data url field needs to be checked here
320
         * and the describes and describedBy fields of the system metadata
321
         * need to be set with the appropriate uri.  Older EML documents
322
         * maybe have ecogrid:// uri's embedded in them.  See bug 618 
323
         * (https://trac.dataone.org/ticket/618) for more info on this.
324
         */
325
        if (isScienceMetadata) {
326
            // CASE METADATA:
327
            try {
328
                //System.out.println("CrudService: inserting document with guid " + guid.getValue());
329
                this.insertDocument(object, guid, sessionData);
330
                localId = im.getLocalId(guid.getValue());
331
            } catch (IOException e) {
332
                String msg = "Could not create string from XML stream: " +
333
                    " " + e.getMessage();
334
                logMetacat.debug(msg);
335
                throw new ServiceFailure("1190", msg);
336
            } catch(Exception e) {
337
                String msg = "Unexpected error in CrudService.create: " + e.getMessage();
338
                logMetacat.debug(msg);
339
                throw new ServiceFailure("1190", msg);
340
            }
341
            
342

    
343
        } else {
344
            // DEFAULT CASE: DATA (needs to be checked and completed)
345
            localId = insertDataObject(object, guid, sessionData);
346
            
347
        }
348

    
349
        // For Metadata and Data, insert the system metadata into the object store too
350
        String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
351
        //get the document info.  add any access params for the sysmeta too
352
        //System.out.println("looking for access records to add for system " +
353
        //    "metadata who's parent doc's  local id is " + localId);
354
        try
355
        {
356
            Hashtable<String, Object> h = im.getDocumentInfo(localId.substring(0, localId.lastIndexOf(".")));
357
            Vector v = (Vector)h.get("access");
358
            for(int i=0; i<v.size(); i++)
359
            {
360
                Hashtable ah = (Hashtable)v.elementAt(i);
361
                String principal = (String)ah.get("principal_name");
362
                String permission = (String)ah.get("permission");
363
                String permissionType = (String)ah.get("permission_type");
364
                String permissionOrder = (String)ah.get("permission_order");
365
                int perm = new Integer(permission).intValue();
366
                //System.out.println("found access record for principal " + principal);
367
                //System.out.println("permission: " + perm + " perm_type: " + permissionType + 
368
                //    " perm_order: " + permissionOrder);
369
                this.setAccess(token, guid, principal, perm, permissionType, permissionOrder, true);
370
            }
371
        }
372
        catch(Exception e)
373
        {
374
            logMetacat.error("Error setting permissions on System Metadata object " + 
375
                    " with id " + sysMetaLocalId + ": " + e.getMessage());
376
            //TODO: decide if this error should cancel the entire create or
377
            //if it should continue with just a logged error.
378
        }
379
        
380
        
381
        logMetacat.debug("Returning from CrudService.create()");
382
        EventLog.getInstance().log(metacatUrl,
383
                username, localId, "create");
384
        logCrud.info("create D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
385
                ":D1SYSMETA:"+ sysMetaLocalId + ":");
386
        return guid;
387
    }
388
    
389
    /**
390
     * update an existing object with a new object.  Change the system metadata
391
     * to reflect the changes and update it as well.
392
     */
393
    public Identifier update(AuthToken token, Identifier guid, 
394
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
395
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
396
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
397
            NotImplemented {
398
        try
399
        {
400
            SessionData sessionData = getSessionData(token);
401
            
402
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
403
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
404
            //change sm.old's obsoletedBy field 
405
            List l = sm.getObsoletedByList();
406
            l.add(guid);
407
            sm.setObsoletedByList(l);
408
            //update sm.old
409
            updateSystemMetadata(sm, sessionData);
410
            
411
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
412
            sysmeta.addObsolete(obsoletedGuid);
413
            //insert sm.new
414
            String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
415
            String localId;
416
            
417
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
418
            if(isScienceMetadata)
419
            {
420
                //update the doc
421
                localId = updateDocument(object, obsoletedGuid, guid, sessionData, false);
422
            }
423
            else
424
            {
425
                //update a data file, not xml
426
                localId = insertDataObject(object, guid, sessionData);
427
            }
428
            
429
            IdentifierManager im = IdentifierManager.getInstance();
430
            String username = "public";
431
            if(sessionData != null)
432
            {
433
                username = sessionData.getUserName();
434
            }
435
            EventLog.getInstance().log(metacatUrl,
436
                    username, im.getLocalId(guid.getValue()), "update");
437
            logCrud.info("update D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
438
                    ":D1SYSMETA:"+ sysMetaLocalId + ":");
439
            return guid;
440
        }
441
        catch(Exception e)
442
        {
443
            throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
444
        }
445
    }
446
    
447
    /**
448
     * set access permissions on both the science metadata and system metadata
449
     */
450
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
451
            String permissionType, String permissionOrder)
452
      throws ServiceFailure
453
    {
454
        setAccess(token, id, principal, permission, permissionType, permissionOrder, true);
455
    }
456
    
457
    /**
458
     * set access control on the doc
459
     * @param token
460
     * @param id
461
     * @param principal
462
     * @param permission
463
     */
464
    public void setAccess(AuthToken token, Identifier id, String principal, int permission,
465
      String permissionType, String permissionOrder, boolean setSystemMetadata)
466
      throws ServiceFailure
467
    {
468
        String perm = "";
469
        if(permission >= 4)
470
        {
471
            perm = "read";
472
        }
473
        if(permission >= 6)
474
        {
475
            perm = "write";
476
        }
477
        //System.out.println("perm in setAccess: " + perm);
478
        //System.out.println("permission in setAccess: " + permission);
479
        setAccess(token, id, principal, perm, permissionType, permissionOrder,
480
                setSystemMetadata);
481
       
482
    }
483
    
484
    /**
485
     * set the permission on the document
486
     * @param token
487
     * @param principal
488
     * @param permission
489
     * @param permissionType
490
     * @param permissionOrder
491
     * @return
492
     */
493
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
494
            String permissionType, String permissionOrder, boolean setSystemMetadata)
495
      throws ServiceFailure
496
    {
497
        /* TODO:
498
         * This is also not part of the D1 Crud spec.  This method is needed for
499
         * systems such as metacat where access to objects is controlled by
500
         * and ACL.  Higher level decisions need to be made about how this
501
         * should work within D1.
502
         */
503
        try
504
        {
505
            final SessionData sessionData = getSessionData(token);
506
            if(sessionData == null)
507
            {
508
                throw new ServiceFailure("1000", "User must be logged in to set access.");
509
            }
510
            IdentifierManager im = IdentifierManager.getInstance();
511
            String docid = im.getLocalId(id.getValue());
512
        
513
            String permNum = "0";
514
            if(permission.equals("read"))
515
            {
516
                permNum = "4";
517
            }
518
            else if(permission.equals("write"))
519
            {
520
                permNum = "6";
521
            }
522
            System.out.println("user " + sessionData.getUserName() + 
523
                    " is setting access level " + permNum + " for permission " + 
524
                    permissionType + " on doc with localid " + docid);
525
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
526
                    principal, permNum, permissionType, permissionOrder);
527
            if(setSystemMetadata)
528
            {
529
                //set the same perms on the system metadata doc
530
                String smlocalid = im.getSystemMetadataLocalId(id.getValue());
531
                System.out.println("setting access on SM doc with localid " + smlocalid);
532
                //cs.setAccess(token, smid, principal, permission, permissionType, permissionOrder);
533
                handler.setAccess(metacatUrl, sessionData.getUserName(), smlocalid,
534
                        principal, permNum, permissionType, permissionOrder);
535
            }
536
            String username = "public";
537
            if(sessionData != null)
538
            {
539
                username = sessionData.getUserName();
540
            }
541
            EventLog.getInstance().log(metacatUrl,
542
                    username, im.getLocalId(id.getValue()), "setAccess");
543
            logCrud.info("setAccess");
544
        }
545
        catch(Exception e)
546
        {
547
            e.printStackTrace();
548
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
549
        }
550
    }
551
    
552
    /**
553
     *  Retrieve the list of objects present on the MN that match the calling 
554
     *  parameters. This method is required to support the process of Member 
555
     *  Node synchronization. At a minimum, this method should be able to 
556
     *  return a list of objects that match:
557
     *  startTime <= SystemMetadata.dateSysMetadataModified
558
     *  but is expected to also support date range (by also specifying endTime), 
559
     *  and should also support slicing of the matching set of records by 
560
     *  indicating the starting index of the response (where 0 is the index 
561
     *  of the first item) and the count of elements to be returned.
562
     *  
563
     *  If startTime or endTime is null, the query is not restricted by that parameter.
564
     *  
565
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
566
     * @param token
567
     * @param startTime
568
     * @param endTime
569
     * @param objectFormat
570
     * @param replicaStatus
571
     * @param start
572
     * @param count
573
     * @return ObjectList
574
     * @throws NotAuthorized
575
     * @throws InvalidRequest
576
     * @throws NotImplemented
577
     * @throws ServiceFailure
578
     * @throws InvalidToken
579
     */
580
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
581
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
582
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
583
    {
584
      ObjectList ol = new ObjectList();
585
      final SessionData sessionData = getSessionData(token);
586
      int totalAfterQuery = 0;
587
      
588
      try
589
      {
590
          if (PropertyService.getProperty("database.queryCacheOn").equals("true"))
591
          {
592
              //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
593
              DBQuery.clearQueryResultCache();
594
          }
595
      }
596
      catch (PropertyNotFoundException e1)
597
      {
598
          //just don't do anything
599
      }
600
      
601
      try
602
      {
603
          //TODO: Milliseconds need to be added to the dateFormat
604
          System.out.println("=========== Listing Objects =============");
605
          System.out.println("Current server time is: " + new Date());
606
          if(startTime != null)
607
          {
608
              System.out.println("query start time is " + startTime);
609
          }
610
          if(endTime != null)
611
          {
612
              System.out.println("query end time is " + endTime);
613
          }
614
          params.clear();
615
          /* TODO:
616
           * These metacat queries should not be hard coded here.  They
617
           * should be accessed from within a .properties file
618
           */
619
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
620
          params.put("qformat", new String[] {"xml"});
621
          params.put("returnfield", new String[] {"size", "originMemberNode", 
622
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "checksum/@algorithm"});
623
          params.put("anyfield", new String[] {"%"});
624
          
625
          //System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
626
          //    " sessionid: " + sessionData.getId() + " params: " + params.toString());
627
          String username = "public";
628
          String[] groups = null;
629
          String sessionid = "";
630
          if(sessionData != null)
631
          {
632
              username = sessionData.getUserName();
633
              groups = sessionData.getGroupNames();
634
              sessionid = sessionData.getId();
635
          }
636
          
637
          MetacatResultSet rs = handler.query(metacatUrl, params, username, 
638
                  groups, sessionid);
639
          List docs = rs.getDocuments();
640
          
641
          System.out.println("query returned " + docs.size() + " documents.");
642
          Vector<Document> docCopy = new Vector<Document>();
643
          
644
          //preparse the list to remove any that don't match the query params
645
          /* TODO: this type of query/subquery processing is probably not scalable
646
           * to larger object stores.  This code should be revisited.  The metacat
647
           * query handler should probably be altered to handle the type of query 
648
           * done here.
649
           */ 
650
          for(int i=0; i<docs.size(); i++)
651
          {
652
              Document d = (Document)docs.get(i);
653
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
654
              
655
              if(returnedObjectFormat != null && 
656
                 objectFormat != null && 
657
                 !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
658
              { //make sure the objectFormat is the one specified
659
                  continue;
660
              }
661
              
662
              String dateSMM = d.getField("dateSysMetadataModified");
663
              if((startTime != null || endTime != null) && dateSMM == null)
664
              {  //if startTime or endTime are not null, we need a date to compare to
665
                  continue;
666
              }
667
              
668
              //date parse
669
              Date dateSysMetadataModified = null;
670
              if(dateSMM != null)
671
              {
672
                  //dateSysMetadataModified = parseDate(dateSMM);
673
                  if(dateSMM.indexOf(".") != -1)
674
                  {  //strip the milliseconds
675
                      //TODO: don't do this. we need milliseconds now.
676
                      //TODO: explore ISO 8601 to figure out milliseconds
677
                      dateSMM = dateSMM.substring(0, dateSMM.indexOf(".")) + 'Z';
678
                  }
679
                  //System.out.println("dateSMM: " + dateSMM);
680
                  //dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-0"));
681
                  try
682
                  {   //the format we want
683
                      dateSysMetadataModified = dateFormat.parse(dateSMM);
684
                  }
685
                  catch(java.text.ParseException pe)
686
                  {   //try another legacy format
687
                      DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
688
                      dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
689
                      dateSysMetadataModified = dateFormat2.parse(dateSMM);
690
                  }                  
691
              }
692
              
693
              /*System.out.println("====================================");
694
              System.out.println("doc number " + i);
695
              System.out.println("docid: " + d.docid);
696
              System.out.println("dateSysMetadataModified: " + dateSysMetadataModified);
697
              System.out.println("startTime: " + startTime);
698
              System.out.println("endtime: " + endTime);*/
699
              
700
              int startDateComparison = 0;
701
              int endDateComparison = 0;
702
              if(startTime != null)
703
              {
704
                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
705
                  zTime.setTime(startTime);
706
                  startTime = zTime.getTime();
707
                  
708
                  if(dateSysMetadataModified == null)
709
                  {
710
                      startDateComparison = -1;
711
                  }
712
                  else
713
                  {
714
                      startDateComparison = dateSysMetadataModified.compareTo(startTime);
715
                  }
716
                  //System.out.println("startDateCom: " + startDateComparison);
717
              }
718
              else
719
              {
720
                  startDateComparison = 1;
721
              }
722
              
723
              if(endTime != null)
724
              {
725
                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
726
                  zTime.setTime(endTime);
727
                  endTime = zTime.getTime();
728
                  
729
                  if(dateSysMetadataModified == null)
730
                  {
731
                      endDateComparison = 1;
732
                  }
733
                  else
734
                  {
735
                      endDateComparison = dateSysMetadataModified.compareTo(endTime);
736
                  }
737
                  //System.out.println("endDateCom: " + endDateComparison);
738
              }
739
              else
740
              {
741
                  endDateComparison = -1;
742
              }
743
              
744
              
745
              if(startDateComparison < 0 || endDateComparison > 0)
746
              { 
747
                  continue;                  
748
              }
749
              
750
              docCopy.add((Document)docs.get(i));
751
          } //end pre-parse
752
          
753
          docs = docCopy;
754
          totalAfterQuery = docs.size();
755
          //System.out.println("total after subquery: " + totalAfterQuery);
756
          
757
          //make sure we don't run over the end
758
          int end = start + count;
759
          if(end > docs.size())
760
          {
761
              end = docs.size();
762
          }
763
          
764
          for(int i=start; i<end; i++)
765
          {
766
              //get the document from the result
767
              Document d = (Document)docs.get(i);
768
              //System.out.println("processing doc " + d.docid);
769
              
770
              String dateSMM = d.getField("dateSysMetadataModified");
771
              Date dateSysMetadataModified = null;
772
              if(dateSMM != null)
773
              {
774
                  try
775
                  {
776
                      dateSysMetadataModified = parseDate(dateSMM);
777
                  }
778
                  catch(Exception e)
779
                  { //if we fail to parse the date, just ignore the value
780
                      dateSysMetadataModified = null;
781
                  }
782
              }
783
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
784
                
785
              
786
              ObjectInfo info = new ObjectInfo();
787
              //add the fields to the info object
788
              Checksum cs = new Checksum();
789
              cs.setValue(d.getField("checksum"));
790
              String csalg = d.getField("algorithm");
791
              if(csalg == null)
792
              {
793
                  csalg = "MD5";
794
              }
795
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
796
              cs.setAlgorithm(ca);
797
              info.setChecksum(cs);
798
              info.setDateSysMetadataModified(dateSysMetadataModified);
799
              Identifier id = new Identifier();
800
              id.setValue(d.getField("identifier").trim());
801
              info.setIdentifier(id);
802
              info.setObjectFormat(returnedObjectFormat);
803
              String size = d.getField("size");
804
              if(size != null)
805
              {
806
                  info.setSize(new Long(size.trim()).longValue());
807
              }
808
              //add the ObjectInfo to the ObjectList
809
              if(info.getIdentifier().getValue() != null || 
810
                 (info.getObjectFormat() != null && 
811
                  !info.getObjectFormat().toString().trim().equals("")))
812
              { //id can be null from tests.  should not happen in production.
813
                  ol.addObjectInfo(info);
814
              }
815
             
816
          }
817
      }
818
      catch(Exception e)
819
      {
820
          e.printStackTrace();
821
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
822
      }
823
      String username = "public";
824
      if(sessionData != null)
825
      {
826
          username = sessionData.getUserName();
827
      }
828
      EventLog.getInstance().log(metacatUrl,
829
              username, null, "read");
830
      logCrud.info("listObjects");
831
      ol.setCount(count);
832
      ol.setStart(start);
833
      ol.setTotal(totalAfterQuery);
834
      return ol;
835
    }
836
    
837
    /**
838
     * Call listObjects with the default values for replicaStatus (true), start (0),
839
     * and count (1000).
840
     * @param token
841
     * @param startTime
842
     * @param endTime
843
     * @param objectFormat
844
     * @return
845
     * @throws NotAuthorized
846
     * @throws InvalidRequest
847
     * @throws NotImplemented
848
     * @throws ServiceFailure
849
     * @throws InvalidToken
850
     */
851
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
852
        ObjectFormat objectFormat)
853
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
854
    {
855
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
856
    }
857

    
858
    /**
859
     * Delete a document.  NOT IMPLEMENTED
860
     */
861
    public Identifier delete(AuthToken token, Identifier guid)
862
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
863
            NotImplemented {
864
        logCrud.info("delete");
865
        throw new NotImplemented("1000", "This method not yet implemented.");
866
    }
867

    
868
    /**
869
     * describe a document.  NOT IMPLEMENTED
870
     */
871
    public DescribeResponse describe(AuthToken token, Identifier guid)
872
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
873
            NotImplemented {
874
        logCrud.info("describe");
875
        throw new NotImplemented("1000", "This method not yet implemented.");
876
    }
877
    
878
    /**
879
     * get a document with a specified guid.
880
     */
881
    public InputStream get(AuthToken token, Identifier guid)
882
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
883
            NotImplemented {
884
        
885
        // Retrieve the session information from the AuthToken
886
        // If the session is expired, then the user is 'public'
887
        if(token == null)
888
        {
889
            token = new AuthToken("Public");
890
        }
891
        final SessionData sessionData = getSessionData(token);
892
        
893
        // Look up the localId for this global identifier
894
        IdentifierManager im = IdentifierManager.getInstance();
895
        try {
896
            final String localId = im.getLocalId(guid.getValue());
897

    
898
            final InputStreamFromOutputStream<String> objectStream = 
899
                new InputStreamFromOutputStream<String>() {
900
                
901
                @Override
902
                public String produce(final OutputStream dataSink) throws Exception {
903

    
904
                    try {
905
                        String username = "public";
906
                        String[] groups = new String[0];
907
                        if(sessionData != null)
908
                        {
909
                            username = sessionData.getUserName();
910
                            groups = sessionData.getGroupNames();
911
                        }
912
                        /*System.out.println("metacatUrl: " + metacatUrl + 
913
                            " dataSink: " + dataSink + " localId: " + localId + 
914
                            " username: " + username + " params: " + params.toString());
915
                        */    
916
                        /* TODO:
917
                         * This multithreaded approach to getting data without
918
                         * being memory bound causes problems with exception 
919
                         * handling.  The only exception the produce method
920
                         * will return is an IOException, rendering all of the 
921
                         * catch blocks below mute.  This should probably be changed
922
                         * to use a memory mapped solution instead so that we
923
                         * can properly pass exceptions to the client.
924
                         * see https://trac.dataone.org/ticket/706
925
                         */
926
                        handler.readFromMetacat(metacatUrl, null, 
927
                                dataSink, localId, "xml",
928
                                username, 
929
                                groups, true, params);
930
                    } catch (PropertyNotFoundException e) {
931
                        e.printStackTrace();
932
                        throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
933
                    } catch (ClassNotFoundException e) {
934
                        e.printStackTrace();
935
                        throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
936
                    } catch (IOException e) {
937
                        e.printStackTrace();
938
                        throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
939
                    } catch (SQLException e) {
940
                        e.printStackTrace();
941
                        throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
942
                    } catch (McdbException e) {
943
                        e.printStackTrace();
944
                        throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
945
                    } catch (ParseLSIDException e) {
946
                        e.printStackTrace();
947
                        throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
948
                    } catch (InsufficientKarmaException e) {
949
                        e.printStackTrace();
950
                        throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
951
                    }
952

    
953
                    return "Completed";
954
                }
955
            };
956
            String username = "public";
957
            if(sessionData != null)
958
            {
959
                username = sessionData.getUserName();
960
            }
961
            
962
            EventLog.getInstance().log(metacatUrl,
963
                    username, im.getLocalId(guid.getValue()), "read");
964
            logCrud.info("get D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
965
                    ":");
966
            return objectStream;
967

    
968
        } catch (McdbDocNotFoundException e) {
969
            throw new NotFound("1020", e.getMessage());
970
        }
971
    }
972

    
973
    /**
974
     * get the checksum for a document.  NOT IMPLEMENTED
975
     */
976
    public Checksum getChecksum(AuthToken token, Identifier guid)
977
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
978
            InvalidRequest, NotImplemented {
979
        logCrud.info("getChecksum");
980
        //TODO: this could now easily be implemented
981
        throw new NotImplemented("1000", "This method not yet implemented.");
982
    }
983

    
984
    /**
985
     * get the checksum for a document.  NOT IMPLEMENTED
986
     */
987
    public Checksum getChecksum(AuthToken token, Identifier guid, 
988
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
989
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
990
        logCrud.info("getChecksum");
991
        //TODO: this could now easily be implemented
992
        throw new NotImplemented("1000", "This method not yet implemented.");
993
    }
994

    
995
    /**
996
     * get log records.  
997
     */
998
    public Log getLogRecords(AuthToken token, Date fromDate, Date toDate, Event event)
999
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
1000
            NotImplemented 
1001
    {
1002
        System.out.println("=================== Getting log records ===================");
1003
        System.out.println("Current server time is: " + new Date());
1004
        if(fromDate != null)
1005
        {
1006
          System.out.println("query start time is " + fromDate);
1007
        }
1008
        if(toDate != null)
1009
        {
1010
          System.out.println("query end time is " + toDate);
1011
        }
1012
        Log log = new Log();
1013
        Vector<LogEntry> logs = new Vector<LogEntry>();
1014
        IdentifierManager im = IdentifierManager.getInstance();
1015
        EventLog el = EventLog.getInstance();
1016
        if(fromDate == null)
1017
        {
1018
            System.out.println("setting fromdate from null");
1019
            fromDate = new Date(1);
1020
        }
1021
        if(toDate == null)
1022
        {
1023
            System.out.println("setting todate from null");
1024
            toDate = new Date();
1025
        }
1026
        
1027
        System.out.println("fromDate: " + fromDate);
1028
        System.out.println("toDate: " + toDate);
1029
        
1030
        String report = el.getReport(null, null, null, null, 
1031
                new java.sql.Timestamp(fromDate.getTime()), 
1032
                new java.sql.Timestamp(toDate.getTime()));
1033
        
1034
        //System.out.println("report: " + report);
1035
        
1036
        String logEntry = "<logEntry>";
1037
        String endLogEntry = "</logEntry>";
1038
        int startIndex = 0;
1039
        int foundIndex = report.indexOf(logEntry, startIndex);
1040
        while(foundIndex != -1)
1041
        {
1042
            //parse out each entry
1043
            int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
1044
            String entry = report.substring(foundIndex, endEntryIndex);
1045
            //System.out.println("entry: " + entry);
1046
            startIndex = endEntryIndex + endLogEntry.length();
1047
            foundIndex = report.indexOf(logEntry, startIndex);
1048
            
1049
            String entryId = getLogEntryField("entryid", entry);
1050
            String ipAddress = getLogEntryField("ipAddress", entry);
1051
            String principal = getLogEntryField("principal", entry);
1052
            String docid = getLogEntryField("docid", entry);
1053
            String eventS = getLogEntryField("event", entry);
1054
            String dateLogged = getLogEntryField("dateLogged", entry);
1055
            
1056
            LogEntry le = new LogEntry();
1057
            
1058
            Event e = Event.convert(eventS);
1059
            if(e == null)
1060
            { //skip any events that are not Dataone Crud events
1061
                continue;
1062
            }
1063
            le.setEvent(e);
1064
            Identifier entryid = new Identifier();
1065
            entryid.setValue(entryId);
1066
            le.setEntryId(entryid);
1067
            Identifier identifier = new Identifier();
1068
            try
1069
            {
1070
                //System.out.println("converting docid '" + docid + "' to a guid.");
1071
                if(docid == null || docid.trim().equals("") || docid.trim().equals("null"))
1072
                {
1073
                    continue;
1074
                }
1075
                docid = docid.substring(0, docid.lastIndexOf("."));
1076
                identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
1077
            }
1078
            catch(Exception ex)
1079
            { //try to get the guid, if that doesn't work, just use the local id
1080
                //throw new ServiceFailure("1030", "Error getting guid for localId " + 
1081
                //        docid + ": " + ex.getMessage());\
1082
                
1083
                //skip it if the guid can't be found
1084
                continue;
1085
            }
1086
            
1087
            le.setIdentifier(identifier);
1088
            le.setIpAddress(ipAddress);
1089
            Calendar c = Calendar.getInstance();
1090
            String year = dateLogged.substring(0, 4);
1091
            String month = dateLogged.substring(5, 7);
1092
            String date = dateLogged.substring(8, 10);
1093
            //System.out.println("year: " + year + " month: " + month + " day: " + date);
1094
            c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
1095
            Date logDate = c.getTime();
1096
            le.setDateLogged(logDate);
1097
            NodeReference memberNode = new NodeReference();
1098
            memberNode.setValue(ipAddress);
1099
            le.setMemberNode(memberNode);
1100
            Principal princ = new Principal();
1101
            princ.setValue(principal);
1102
            le.setPrincipal(princ);
1103
            le.setUserAgent("metacat/RESTService");
1104
            
1105
            if(event == null)
1106
            {
1107
                logs.add(le);
1108
            }
1109
            
1110
            if(event != null &&
1111
               e.toString().toLowerCase().trim().equals(event.toString().toLowerCase().trim()))
1112
            {
1113
              logs.add(le);
1114
            }
1115
        }
1116
        
1117
        log.setLogEntryList(logs);
1118
        logCrud.info("getLogRecords");
1119
        return log;
1120
    }
1121
    
1122
    /**
1123
     * parse a logEntry and get the relavent field from it
1124
     * @param fieldname
1125
     * @param entry
1126
     * @return
1127
     */
1128
    private String getLogEntryField(String fieldname, String entry)
1129
    {
1130
        String begin = "<" + fieldname + ">";
1131
        String end = "</" + fieldname + ">";
1132
        //System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
1133
        String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
1134
        //System.out.println("entry " + fieldname + " : " + s);
1135
        return s;
1136
    }
1137

    
1138
    /**
1139
     * get the system metadata for a document with a specified guid.
1140
     */
1141
public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
1142
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1143
            InvalidRequest, NotImplemented {
1144
        
1145
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
1146
        
1147
        // Retrieve the session information from the AuthToken
1148
        // If the session is expired, then the user is 'public'
1149
        final SessionData sessionData = getSessionData(token);
1150
                
1151
        try {
1152
            IdentifierManager im = IdentifierManager.getInstance();
1153
            final String localId = im.getSystemMetadataLocalId(guid.getValue());
1154
            
1155
            // Read system metadata from metacat's db
1156
            final InputStreamFromOutputStream<String> objectStream = 
1157
                new InputStreamFromOutputStream<String>() {
1158
                
1159
                @Override
1160
                public String produce(final OutputStream dataSink) throws Exception {
1161
                    //TODO: change to memory mapped IO so that exceptions get 
1162
                    //passed to the response correctly.
1163
                    try {
1164
                        String username = "public";
1165
                        String[] groupnames = null;
1166
                        if(sessionData != null)
1167
                        {
1168
                            username = sessionData.getUserName();
1169
                            groupnames = sessionData.getGroupNames();
1170
                        }
1171
                        
1172
                        handler.readFromMetacat(metacatUrl, null, 
1173
                                dataSink, localId, "xml",
1174
                                username, 
1175
                                groupnames, true, params);
1176
                    } catch (PropertyNotFoundException e) {
1177
                        e.printStackTrace();
1178
                        throw new ServiceFailure("1030", "Property not found while reading system metadata from metacat: " + e.getMessage());
1179
                    } catch (ClassNotFoundException e) {
1180
                        e.printStackTrace();
1181
                        throw new ServiceFailure("1030", "Class not found while reading system metadata from metacat: " + e.getMessage());
1182
                    } catch (IOException e) {
1183
                        e.printStackTrace();
1184
                        throw new ServiceFailure("1030", "IOException while reading system metadata from metacat: " + e.getMessage());
1185
                    } catch (SQLException e) {
1186
                        e.printStackTrace();
1187
                        throw new ServiceFailure("1030", "SQLException while reading system metadata from metacat: " + e.getMessage());
1188
                    } catch (McdbException e) {
1189
                        e.printStackTrace();
1190
                        throw new ServiceFailure("1030", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
1191
                    } catch (ParseLSIDException e) {
1192
                        e.printStackTrace();
1193
                        throw new NotFound("1020", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
1194
                    } catch (InsufficientKarmaException e) {
1195
                        e.printStackTrace();
1196
                        throw new NotAuthorized("1000", "User not authorized for get() on system metadata: " + e.getMessage());
1197
                    }
1198

    
1199
                    return "Completed";
1200
                }
1201
            };
1202
            
1203
            // Deserialize the xml to create a SystemMetadata object
1204
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
1205
            String username = "public";
1206
            if(sessionData != null)
1207
            {
1208
                username = sessionData.getUserName();
1209
            }
1210
            EventLog.getInstance().log(metacatUrl,
1211
                    username, im.getLocalId(guid.getValue()), "read");
1212
            logCrud.info("getsystemmetadata D1GUID:" + guid.getValue()  + 
1213
                    ":D1SYSMETA:"+ localId + ":");
1214
            return sysmeta;
1215
            
1216
        } catch (McdbDocNotFoundException e) {
1217
            //e.printStackTrace();
1218
            throw new NotFound("1000", e.getMessage());
1219
        }                
1220
    }
1221
    
1222
    /**
1223
     * parse the date in the systemMetadata
1224
     * @param s
1225
     * @return
1226
     * @throws Exception
1227
     */
1228
    public Date parseDate(String s)
1229
      throws Exception
1230
    {
1231
        /* TODO:
1232
         * This method should be replaced by a DateFormatter
1233
         */
1234
        Date d = null;
1235
        int tIndex = s.indexOf("T");
1236
        int zIndex = s.indexOf("Z");
1237
        if(tIndex != -1 && zIndex != -1)
1238
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
1239
            //System.out.println("original date: " + s);
1240
            
1241
            String date = s.substring(0, tIndex);
1242
            String year = date.substring(0, date.indexOf("-"));
1243
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
1244
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
1245
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
1246
                    " month: " + new Integer(month).intValue() + " day: " + 
1247
                    new Integer(day).intValue());
1248
            */
1249
            String time = s.substring(tIndex + 1, zIndex);
1250
            String hour = time.substring(0, time.indexOf(":"));
1251
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
1252
            String seconds = "00";
1253
            String milliseconds = "00";
1254
            if(time.indexOf(".") != -1)
1255
            {
1256
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
1257
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
1258
            }
1259
            else
1260
            {
1261
                seconds = time.substring(time.lastIndexOf(":") + 1, time.length());
1262
            }
1263
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
1264
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
1265
                    new Integer(seconds).intValue() + " milli: " + 
1266
                    new Integer(milliseconds).intValue());*/
1267
            
1268
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
1269
            Calendar c = Calendar.getInstance(/*TimeZone.getTimeZone("GMT-0")*/TimeZone.getDefault());
1270
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
1271
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
1272
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
1273
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
1274
            d = new Date(c.getTimeInMillis());
1275
            //System.out.println("d: " + d);
1276
            return d;
1277
        }
1278
        else
1279
        {  //if it's not in the expected format, try the formatter
1280
            return DateFormat.getDateTimeInstance().parse(s);
1281
        }
1282
    }
1283

    
1284
    /*
1285
     * Look up the information on the session using the token provided in
1286
     * the AuthToken.  The Session should have all relevant user information.
1287
     * If the session has expired or is invalid, the 'public' session will
1288
     * be returned, giving the user anonymous access.
1289
     */
1290
    public static SessionData getSessionData(AuthToken token) {
1291
        SessionData sessionData = null;
1292
        String sessionId = "PUBLIC";
1293
        if (token != null) {
1294
            sessionId = token.getToken();
1295
        }
1296
        
1297
        // if the session id is registered in SessionService, get the
1298
        // SessionData for it. Otherwise, use the public session.
1299
        //System.out.println("sessionid: " + sessionId);
1300
        if (sessionId != null &&
1301
            !sessionId.toLowerCase().equals("public") &&
1302
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1303
        {
1304
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1305
        } else {
1306
            sessionData = SessionService.getInstance().getPublicSession();
1307
        }
1308
        
1309
        return sessionData;
1310
    }
1311

    
1312
    /** 
1313
     * Determine if a given object should be treated as an XML science metadata
1314
     * object. 
1315
     * 
1316
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1317
     * 
1318
     * @param sysmeta the SystemMetadata describig the object
1319
     * @return true if the object should be treated as science metadata
1320
     */
1321
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1322
        /*boolean scimeta = false;
1323
        //TODO: this should be read from a .properties file instead of being hard coded
1324
        switch (sysmeta.getObjectFormat()) {
1325
            case EML_2_1_0: scimeta = true; break;
1326
            case EML_2_0_1: scimeta = true; break;
1327
            case EML_2_0_0: scimeta = true; break;
1328
            case FGDC_STD_001_1_1999: scimeta = true; break;
1329
            case FGDC_STD_001_1998: scimeta = true; break;
1330
            case NCML_2_2: scimeta = true; break;
1331
            case DSPACE_METS_SIP_1_0: scimeta = true; break;
1332
        }
1333
        
1334
        return scimeta;*/
1335
        
1336
        return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
1337
    }
1338

    
1339
    /**
1340
     * insert a data doc
1341
     * @param object
1342
     * @param guid
1343
     * @param sessionData
1344
     * @throws ServiceFailure
1345
     * @returns localId of the data object inserted
1346
     */
1347
    private String insertDataObject(InputStream object, Identifier guid, 
1348
            SessionData sessionData) throws ServiceFailure {
1349
        
1350
        String username = "public";
1351
        String[] groups = null;
1352
        if(sessionData != null)
1353
        {
1354
          username = sessionData.getUserName();
1355
          groups = sessionData.getGroupNames();
1356
        }
1357

    
1358
        // generate guid/localId pair for object
1359
        logMetacat.debug("Generating a guid/localId mapping");
1360
        IdentifierManager im = IdentifierManager.getInstance();
1361
        String localId = im.generateLocalId(guid.getValue(), 1);
1362

    
1363
        try {
1364
            logMetacat.debug("Case DATA: starting to write to disk.");
1365
            if (DocumentImpl.getDataFileLockGrant(localId)) {
1366
    
1367
                // Save the data file to disk using "localId" as the name
1368
                try {
1369
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
1370
    
1371
                    File dataDirectory = new File(datafilepath);
1372
                    dataDirectory.mkdirs();
1373
    
1374
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
1375
    
1376
                    // TODO: Check that the file size matches SystemMetadata
1377
                    //                        long size = newFile.length();
1378
                    //                        if (size == 0) {
1379
                    //                            throw new IOException("Uploaded file is 0 bytes!");
1380
                    //                        }
1381
    
1382
                    // Register the file in the database (which generates an exception
1383
                    // if the localId is not acceptable or other untoward things happen
1384
                    try {
1385
                        logMetacat.debug("Registering document...");
1386
                        DocumentImpl.registerDocument(localId, "BIN", localId,
1387
                                username, groups);
1388
                        logMetacat.debug("Registration step completed.");
1389
                    } catch (SQLException e) {
1390
                        //newFile.delete();
1391
                        logMetacat.debug("SQLE: " + e.getMessage());
1392
                        e.printStackTrace(System.out);
1393
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1394
                    } catch (AccessionNumberException e) {
1395
                        //newFile.delete();
1396
                        logMetacat.debug("ANE: " + e.getMessage());
1397
                        e.printStackTrace(System.out);
1398
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1399
                    } catch (Exception e) {
1400
                        //newFile.delete();
1401
                        logMetacat.debug("Exception: " + e.getMessage());
1402
                        e.printStackTrace(System.out);
1403
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1404
                    }
1405
    
1406
                    logMetacat.debug("Logging the creation event.");
1407
                    EventLog.getInstance().log(metacatUrl,
1408
                            username, localId, "create");
1409
    
1410
                    // Schedule replication for this data file
1411
                    logMetacat.debug("Scheduling replication.");
1412
                    ForceReplicationHandler frh = new ForceReplicationHandler(
1413
                            localId, "create", false, null);
1414
    
1415
                } catch (PropertyNotFoundException e) {
1416
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1417
                }
1418
            }
1419
            return localId;
1420
        } catch (Exception e) {
1421
            // Could not get a lock on the document, so we can not update the file now
1422
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1423
        }
1424
    }
1425

    
1426
    /**
1427
     * write a file to a stream
1428
     * @param dir
1429
     * @param fileName
1430
     * @param data
1431
     * @return
1432
     * @throws ServiceFailure
1433
     */
1434
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1435
        throws ServiceFailure {
1436
        
1437
        File newFile = new File(dir, fileName);
1438
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1439

    
1440
        try {
1441
            if (newFile.createNewFile()) {
1442
                // write data stream to desired file
1443
                OutputStream os = new FileOutputStream(newFile);
1444
                long length = IOUtils.copyLarge(data, os);
1445
                os.flush();
1446
                os.close();
1447
            } else {
1448
                logMetacat.debug("File creation failed, or file already exists.");
1449
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1450
            }
1451
        } catch (FileNotFoundException e) {
1452
            logMetacat.debug("FNF: " + e.getMessage());
1453
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1454
                    + e.getMessage());
1455
        } catch (IOException e) {
1456
            logMetacat.debug("IOE: " + e.getMessage());
1457
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1458
                    + " " + e.getMessage());
1459
        }
1460

    
1461
        return newFile;
1462
    }
1463

    
1464
    /**
1465
     * insert a systemMetadata doc, return the localId of the sysmeta
1466
     */
1467
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1468
        throws ServiceFailure 
1469
    {
1470
        logMetacat.debug("Starting to insert SystemMetadata...");
1471
    
1472
        // generate guid/localId pair for sysmeta
1473
        Identifier sysMetaGuid = new Identifier();
1474
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1475
        sysmeta.setDateSysMetadataModified(new Date());
1476
        System.out.println("****inserting new system metadata with modified date " + 
1477
                sysmeta.getDateSysMetadataModified());
1478

    
1479
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
1480
        System.out.println("sysmeta: " + xml);
1481
        String localId = insertDocument(xml, sysMetaGuid, sessionData, true);
1482
        System.out.println("sysmeta inserted with localId " + localId);
1483
        //insert the system metadata doc id into the systemmetadata table to 
1484
        //link it to the data or metadata document
1485
        IdentifierManager.getInstance().createSystemMetadataMapping(
1486
                sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
1487
        return localId;
1488
    }
1489
    
1490
    /**
1491
     * update a systemMetadata doc
1492
     */
1493
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1494
      throws ServiceFailure
1495
    {
1496
        try
1497
        {
1498
            String smId = IdentifierManager.getInstance().getSystemMetadataLocalId(sm.getIdentifier().getValue());
1499
            sm.setDateSysMetadataModified(new Date());
1500
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
1501
            String localId = updateDocument(xml, sm.getIdentifier(), null, sessionData, true);
1502
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
1503
        }
1504
        catch(Exception e)
1505
        {
1506
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
1507
        }
1508
    }
1509
    
1510
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1511
        throws ServiceFailure
1512
    {
1513
        return insertDocument(xml, guid, sessionData, false);
1514
    }
1515
    
1516
    /**
1517
     * insert a document
1518
     * NOTE: this method shouldn't be used from the update or create() methods.  
1519
     * we shouldn't be putting the science metadata or data objects into memory.
1520
     */
1521
    private String insertDocument(String xml, Identifier guid, SessionData sessionData,
1522
            boolean isSystemMetadata)
1523
        throws ServiceFailure
1524
    {
1525
        return insertOrUpdateDocument(xml, guid, sessionData, "insert", isSystemMetadata);
1526
    }
1527
    
1528
    /**
1529
     * insert a document from a stream
1530
     */
1531
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1532
      throws IOException, ServiceFailure
1533
    {
1534
        //HACK: change this eventually.  we should not be converting the stream to a string
1535
        String xml = IOUtils.toString(is);
1536
        return insertDocument(xml, guid, sessionData);
1537
    }
1538
    
1539
    /**
1540
     * update a document
1541
     * NOTE: this method shouldn't be used from the update or create() methods.  
1542
     * we shouldn't be putting the science metadata or data objects into memory.
1543
     */
1544
    private String updateDocument(String xml, Identifier obsoleteGuid, 
1545
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1546
        throws ServiceFailure
1547
    {
1548
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update", isSystemMetadata);
1549
    }
1550
    
1551
    /**
1552
     * update a document from a stream
1553
     */
1554
    private String updateDocument(InputStream is, Identifier obsoleteGuid, 
1555
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1556
      throws IOException, ServiceFailure
1557
    {
1558
        //HACK: change this eventually.  we should not be converting the stream to a string
1559
        String xml = IOUtils.toString(is);
1560
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData, isSystemMetadata);
1561
        IdentifierManager im = IdentifierManager.getInstance();
1562
        if(guid != null)
1563
        {
1564
          im.createMapping(guid.getValue(), localId);
1565
        }
1566
        return localId;
1567
    }
1568
    
1569
    /**
1570
     * insert a document, return the id of the document that was inserted
1571
     */
1572
    protected String insertOrUpdateDocument(String xml, Identifier guid, 
1573
            SessionData sessionData, String insertOrUpdate, boolean isSystemMetadata) 
1574
        throws ServiceFailure {
1575
        logMetacat.debug("Starting to insert xml document...");
1576
        IdentifierManager im = IdentifierManager.getInstance();
1577

    
1578
        // generate guid/localId pair for sysmeta
1579
        String localId = null;
1580
        if(insertOrUpdate.equals("insert"))
1581
        {
1582
            localId = im.generateLocalId(guid.getValue(), 1, isSystemMetadata);
1583
        }
1584
        else
1585
        {
1586
            //localid should already exist in the identifier table, so just find it
1587
            try
1588
            {
1589
                System.out.println("updating guid " + guid.getValue());
1590
                if(!isSystemMetadata)
1591
                {
1592
                    System.out.println("looking in identifier table for guid " + guid.getValue());
1593
                    localId = im.getLocalId(guid.getValue());
1594
                }
1595
                else
1596
                {
1597
                    System.out.println("looking in systemmetadata table for guid " + guid.getValue());
1598
                    localId = im.getSystemMetadataLocalId(guid.getValue());
1599
                }
1600
                System.out.println("localId: " + localId);
1601
                //increment the revision
1602
                String docid = localId.substring(0, localId.lastIndexOf("."));
1603
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1604
                int rev = new Integer(revS).intValue();
1605
                rev++;
1606
                docid = docid + "." + rev;
1607
                localId = docid;
1608
                System.out.println("incremented localId: " + localId);
1609
            }
1610
            catch(McdbDocNotFoundException e)
1611
            {
1612
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1613
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1614
            }
1615
        }
1616
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1617
                localId);
1618

    
1619
        String[] action = new String[1];
1620
        action[0] = insertOrUpdate;
1621
        params.put("action", action);
1622
        String[] docid = new String[1];
1623
        docid[0] = localId;
1624
        params.put("docid", docid);
1625
        String[] doctext = new String[1];
1626
        doctext[0] = xml;
1627
        logMetacat.debug(doctext[0]);
1628
        params.put("doctext", doctext);
1629
        
1630
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1631
        // onto output stream, or alternatively, capture that and parse it to 
1632
        // generate the right exceptions
1633
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1634
        //PrintWriter pw = new PrintWriter(output);
1635
        String username = "public";
1636
        String[] groupnames = null;
1637
        if(sessionData != null)
1638
        {
1639
            username = sessionData.getUserName();
1640
            groupnames = sessionData.getGroupNames();
1641
        }
1642
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1643
                            null, params, username, groupnames);
1644
        if(result.indexOf("<error>") != -1)
1645
        {
1646
            throw new ServiceFailure("1000", "Error inserting or updating document: " + result);
1647
        }
1648
        //String outputS = new String(output.toByteArray());
1649
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1650
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1651
        return localId;
1652
    }
1653
    
1654
    /**
1655
     * serialize an ObjectInfo object
1656
     * @param info
1657
     * @return
1658
     * @throws ServiceFailure
1659
     */
1660
    public static ByteArrayOutputStream serializeObjectInfo(ObjectInfo info)
1661
      throws ServiceFailure
1662
    {
1663
        IBindingFactory bfact;
1664
        ByteArrayOutputStream sysmetaOut = null;
1665
        try {
1666
            bfact = BindingDirectory.getFactory(ObjectInfo.class);
1667
            IMarshallingContext mctx = bfact.createMarshallingContext();
1668
            sysmetaOut = new ByteArrayOutputStream();
1669
            mctx.marshalDocument(info, "UTF-8", null, sysmetaOut);
1670
        } catch (JiBXException e) {
1671
            e.printStackTrace();
1672
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1673
        }
1674
        
1675
        return sysmetaOut;
1676
    }
1677
    
1678
    /**
1679
     * serialize a system metadata doc
1680
     * @param sysmeta
1681
     * @return
1682
     * @throws ServiceFailure
1683
     */
1684
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1685
        throws ServiceFailure {
1686
        IBindingFactory bfact;
1687
        ByteArrayOutputStream sysmetaOut = null;
1688
        try {
1689
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1690
            IMarshallingContext mctx = bfact.createMarshallingContext();
1691
            sysmetaOut = new ByteArrayOutputStream();
1692
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1693
        } catch (JiBXException e) {
1694
            e.printStackTrace();
1695
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1696
        }
1697
        
1698
        return sysmetaOut;
1699
    }
1700
    
1701
    /**
1702
     * deserialize a system metadata doc
1703
     * @param xml
1704
     * @return
1705
     * @throws ServiceFailure
1706
     */
1707
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1708
        throws ServiceFailure {
1709
        try {
1710
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1711
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1712
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1713
            return sysmeta;
1714
        } catch (JiBXException e) {
1715
            e.printStackTrace();
1716
            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1717
        }    
1718
    }
1719
    
1720
    /**
1721
     * produce an md5 checksum for item
1722
     */
1723
    private String checksum(InputStream is)
1724
      throws Exception
1725
    {        
1726
        byte[] buffer = new byte[1024];
1727
        MessageDigest complete = MessageDigest.getInstance("MD5");
1728
        int numRead;
1729
        
1730
        do 
1731
        {
1732
          numRead = is.read(buffer);
1733
          if (numRead > 0) 
1734
          {
1735
            complete.update(buffer, 0, numRead);
1736
          }
1737
        } while (numRead != -1);
1738
        
1739
        
1740
        return getHex(complete.digest());
1741
    }
1742
    
1743
    /**
1744
     * convert a byte array to a hex string
1745
     */
1746
    private static String getHex( byte [] raw ) 
1747
    {
1748
        final String HEXES = "0123456789ABCDEF";
1749
        if ( raw == null ) {
1750
          return null;
1751
        }
1752
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
1753
        for ( final byte b : raw ) {
1754
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
1755
             .append(HEXES.charAt((b & 0x0F)));
1756
        }
1757
        return hex.toString();
1758
    }
1759
    
1760
    /**
1761
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
1762
     * a proper date object
1763
     * @param date
1764
     * @return
1765
     */
1766
    private Date parseMetacatDate(String date)
1767
    {
1768
        String year = date.substring(0, 4);
1769
        String month = date.substring(5, 7);
1770
        String day = date.substring(8, 10);
1771
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
1772
        c.set(new Integer(year).intValue(), 
1773
              new Integer(month).intValue(), 
1774
              new Integer(day).intValue());
1775
        System.out.println("time in parseMetacatDate: " + c.getTime());
1776
        return c.getTime();
1777
    }
1778
    
1779
    /**
1780
     * find the size (in bytes) of a stream
1781
     * @param is
1782
     * @return
1783
     * @throws IOException
1784
     */
1785
    private long sizeOfStream(InputStream is)
1786
        throws IOException
1787
    {
1788
        long size = 0;
1789
        byte[] b = new byte[1024];
1790
        int numread = is.read(b, 0, 1024);
1791
        while(numread != -1)
1792
        {
1793
            size += numread;
1794
            numread = is.read(b, 0, 1024);
1795
        }
1796
        return size;
1797
    }
1798
    
1799
    /**
1800
     * create system metadata with a specified id, doc and format
1801
     */
1802
    private SystemMetadata createSystemMetadata(String localId, AuthToken token)
1803
      throws Exception
1804
    {
1805
        IdentifierManager im = IdentifierManager.getInstance();
1806
        Hashtable<String, Object> docInfo = im.getDocumentInfo(localId);
1807
        
1808
        //get the document text
1809
        int rev = im.getLatestRevForLocalId(localId);
1810
        Identifier identifier = new Identifier();
1811
        identifier.setValue(im.getGUID(localId, rev));
1812
        InputStream is = this.get(token, identifier);
1813
        
1814
        SystemMetadata sm = new SystemMetadata();
1815
        //set the id
1816
        sm.setIdentifier(identifier);
1817
        
1818
        //set the object format
1819
        String doctype = (String)docInfo.get("doctype");
1820
        ObjectFormat format = ObjectFormat.convert((String)docInfo.get("doctype"));
1821
        if(format == null)
1822
        {
1823
            if(doctype.trim().equals("BIN"))
1824
            {
1825
                format = ObjectFormat.OCTET_STREAM;
1826
            }
1827
            else
1828
            {
1829
                format = ObjectFormat.convert("text/plain");
1830
            }
1831
        }
1832
        sm.setObjectFormat(format);
1833
        
1834
        //create the checksum
1835
        String checksumS = checksum(is);
1836
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
1837
        Checksum checksum = new Checksum();
1838
        checksum.setValue(checksumS);
1839
        checksum.setAlgorithm(ca);
1840
        sm.setChecksum(checksum);
1841
        
1842
        //set the size
1843
        is = this.get(token, identifier);
1844
        sm.setSize(sizeOfStream(is));
1845
        
1846
        //submitter
1847
        Principal p = new Principal();
1848
        p.setValue((String)docInfo.get("user_owner"));
1849
        sm.setSubmitter(p);
1850
        sm.setRightsHolder(p);
1851
        try
1852
        {
1853
            Date dateCreated = parseMetacatDate((String)docInfo.get("date_created"));
1854
            sm.setDateUploaded(dateCreated);
1855
            Date dateUpdated = parseMetacatDate((String)docInfo.get("date_updated"));
1856
            sm.setDateSysMetadataModified(dateUpdated);
1857
        }
1858
        catch(Exception e)
1859
        {
1860
            System.out.println("POSSIBLE ERROR: couldn't parse a date: " + e.getMessage());
1861
            Date dateCreated = new Date();
1862
            sm.setDateUploaded(dateCreated);
1863
            Date dateUpdated = new Date();
1864
            sm.setDateSysMetadataModified(dateUpdated);
1865
        }
1866
        NodeReference nr = new NodeReference();
1867
        //TODO: this should be set to be something more meaningful once the registry is up
1868
        nr.setValue("metacat");
1869
        sm.setOriginMemberNode(nr);
1870
        sm.setAuthoritativeMemberNode(nr);
1871
        return sm;
1872
    }
1873
}
(1-1/3)