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
              { //id can be null from tests.  should not happen in production.
811
                  try
812
                  { //try to serialize info.  if it cannot be serialized, then
813
                    //don't add it to the info.  bad SM can be added via tests
814
                    //which can break this code.
815
                      serializeObjectInfo(info);
816
                      ol.addObjectInfo(info);
817
                  }
818
                  catch(Exception e)
819
                  {} //don't do anything
820
                  
821
              }
822
             
823
          }
824
      }
825
      catch(Exception e)
826
      {
827
          e.printStackTrace();
828
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
829
      }
830
      String username = "public";
831
      if(sessionData != null)
832
      {
833
          username = sessionData.getUserName();
834
      }
835
      EventLog.getInstance().log(metacatUrl,
836
              username, null, "read");
837
      logCrud.info("listObjects");
838
      ol.setCount(count);
839
      ol.setStart(start);
840
      ol.setTotal(totalAfterQuery);
841
      return ol;
842
    }
843
    
844
    /**
845
     * Call listObjects with the default values for replicaStatus (true), start (0),
846
     * and count (1000).
847
     * @param token
848
     * @param startTime
849
     * @param endTime
850
     * @param objectFormat
851
     * @return
852
     * @throws NotAuthorized
853
     * @throws InvalidRequest
854
     * @throws NotImplemented
855
     * @throws ServiceFailure
856
     * @throws InvalidToken
857
     */
858
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
859
        ObjectFormat objectFormat)
860
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
861
    {
862
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
863
    }
864

    
865
    /**
866
     * Delete a document.  NOT IMPLEMENTED
867
     */
868
    public Identifier delete(AuthToken token, Identifier guid)
869
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
870
            NotImplemented {
871
        logCrud.info("delete");
872
        throw new NotImplemented("1000", "This method not yet implemented.");
873
    }
874

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

    
905
            final InputStreamFromOutputStream<String> objectStream = 
906
                new InputStreamFromOutputStream<String>() {
907
                
908
                @Override
909
                public String produce(final OutputStream dataSink) throws Exception {
910

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

    
960
                    return "Completed";
961
                }
962
            };
963
            String username = "public";
964
            if(sessionData != null)
965
            {
966
                username = sessionData.getUserName();
967
            }
968
            
969
            EventLog.getInstance().log(metacatUrl,
970
                    username, im.getLocalId(guid.getValue()), "read");
971
            logCrud.info("get D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
972
                    ":");
973
            return objectStream;
974

    
975
        } catch (McdbDocNotFoundException e) {
976
            throw new NotFound("1020", e.getMessage());
977
        }
978
    }
979

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

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

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

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

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

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

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

    
1346
    /**
1347
     * insert a data doc
1348
     * @param object
1349
     * @param guid
1350
     * @param sessionData
1351
     * @throws ServiceFailure
1352
     * @returns localId of the data object inserted
1353
     */
1354
    private String insertDataObject(InputStream object, Identifier guid, 
1355
            SessionData sessionData) throws ServiceFailure {
1356
        
1357
        String username = "public";
1358
        String[] groups = null;
1359
        if(sessionData != null)
1360
        {
1361
          username = sessionData.getUserName();
1362
          groups = sessionData.getGroupNames();
1363
        }
1364

    
1365
        // generate guid/localId pair for object
1366
        logMetacat.debug("Generating a guid/localId mapping");
1367
        IdentifierManager im = IdentifierManager.getInstance();
1368
        String localId = im.generateLocalId(guid.getValue(), 1);
1369

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

    
1433
    /**
1434
     * write a file to a stream
1435
     * @param dir
1436
     * @param fileName
1437
     * @param data
1438
     * @return
1439
     * @throws ServiceFailure
1440
     */
1441
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1442
        throws ServiceFailure {
1443
        
1444
        File newFile = new File(dir, fileName);
1445
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1446

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

    
1468
        return newFile;
1469
    }
1470

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

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

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

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