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
                ":D1SYSMETADATA:"+ 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
                    ":D1SYSMETADATA:"+ 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
              //logCrud.info("objectFormat: " + info.getObjectFormat().toString());
810
              //logCrud.info("id: " + info.getIdentifier().getValue());
811
              
812
              if(info.getIdentifier().getValue() != null)
813
              { //id can be null from tests.  should not happen in production.
814
                  if((info.getObjectFormat() != null && !info.getObjectFormat().toString().trim().equals("")))
815
                  { //objectFormat needs to not be null and not be an empty string
816
                    ol.addObjectInfo(info);
817
                  }
818
                  else
819
                  {
820
                      logCrud.info("Not adding object with null objectFormat" + info.getIdentifier().getValue().toString());
821
                  }
822
              }
823
             
824
          }
825
      }
826
      catch(Exception e)
827
      {
828
          e.printStackTrace();
829
          logCrud.error("Error creating ObjectList: " + e.getMessage() + " cause: " + e.getCause());
830
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
831
      }
832
      String username = "public";
833
      if(sessionData != null)
834
      {
835
          username = sessionData.getUserName();
836
      }
837
      EventLog.getInstance().log(metacatUrl,
838
              username, null, "read");
839
      logCrud.info("listObjects");
840
      if(totalAfterQuery < count)
841
      {
842
          count = totalAfterQuery;
843
      }
844
      ol.setCount(count);
845
      ol.setStart(start);
846
      ol.setTotal(totalAfterQuery);
847
      return ol;
848
    }
849
    
850
    /**
851
     * Call listObjects with the default values for replicaStatus (true), start (0),
852
     * and count (1000).
853
     * @param token
854
     * @param startTime
855
     * @param endTime
856
     * @param objectFormat
857
     * @return
858
     * @throws NotAuthorized
859
     * @throws InvalidRequest
860
     * @throws NotImplemented
861
     * @throws ServiceFailure
862
     * @throws InvalidToken
863
     */
864
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
865
        ObjectFormat objectFormat)
866
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
867
    {
868
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
869
    }
870

    
871
    /**
872
     * Delete a document.  NOT IMPLEMENTED
873
     */
874
    public Identifier delete(AuthToken token, Identifier guid)
875
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
876
            NotImplemented {
877
        logCrud.info("delete");
878
        throw new NotImplemented("1000", "This method not yet implemented.");
879
    }
880

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

    
911
            final InputStreamFromOutputStream<String> objectStream = 
912
                new InputStreamFromOutputStream<String>() {
913
                
914
                @Override
915
                public String produce(final OutputStream dataSink) throws Exception {
916

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

    
966
                    return "Completed";
967
                }
968
            };
969
            String username = "public";
970
            if(sessionData != null)
971
            {
972
                username = sessionData.getUserName();
973
            }
974
            
975
            EventLog.getInstance().log(metacatUrl,
976
                    username, im.getLocalId(guid.getValue()), "read");
977
            logCrud.info("get D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
978
                    ":");
979
            return objectStream;
980

    
981
        } catch (McdbDocNotFoundException e) {
982
            throw new NotFound("1020", e.getMessage());
983
        } 
984
    }
985

    
986
    /**
987
     * get the checksum for a document.  defaults to MD5.
988
     */
989
    public Checksum getChecksum(AuthToken token, Identifier guid)
990
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
991
            InvalidRequest, NotImplemented 
992
    {
993
        logCrud.info("getChecksum");
994
        return getChecksum(token, guid, "MD5");
995
    }
996

    
997
    /**
998
     * get the checksum for a document with the given algorithm
999
     */
1000
    public Checksum getChecksum(AuthToken token, Identifier guid, 
1001
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
1002
            NotAuthorized, NotFound, InvalidRequest, NotImplemented 
1003
    {
1004
        logCrud.info("getChecksum");
1005
        InputStream docStream = get(token, guid);
1006
        String checksum;
1007
        try
1008
        {
1009
            checksum = checksum(docStream, checksumAlgorithm);
1010
        }
1011
        catch(Exception e)
1012
        {
1013
            throw new ServiceFailure("1000", "Error getting checksum: " + e.getMessage());
1014
        }
1015
        Checksum c = new Checksum();
1016
        c.setAlgorithm(ChecksumAlgorithm.convert(checksumAlgorithm));
1017
        c.setValue(checksum);
1018
        return c;
1019
    }
1020

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

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

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

    
1310
    /*
1311
     * Look up the information on the session using the token provided in
1312
     * the AuthToken.  The Session should have all relevant user information.
1313
     * If the session has expired or is invalid, the 'public' session will
1314
     * be returned, giving the user anonymous access.
1315
     */
1316
    public static SessionData getSessionData(AuthToken token) {
1317
        SessionData sessionData = null;
1318
        String sessionId = "PUBLIC";
1319
        if (token != null) {
1320
            sessionId = token.getToken();
1321
        }
1322
        
1323
        // if the session id is registered in SessionService, get the
1324
        // SessionData for it. Otherwise, use the public session.
1325
        //System.out.println("sessionid: " + sessionId);
1326
        if (sessionId != null &&
1327
            !sessionId.toLowerCase().equals("public") &&
1328
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1329
        {
1330
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1331
        } else {
1332
            sessionData = SessionService.getInstance().getPublicSession();
1333
        }
1334
        
1335
        return sessionData;
1336
    }
1337

    
1338
    /** 
1339
     * Determine if a given object should be treated as an XML science metadata
1340
     * object. 
1341
     * 
1342
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1343
     * 
1344
     * @param sysmeta the SystemMetadata describig the object
1345
     * @return true if the object should be treated as science metadata
1346
     */
1347
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1348
        /*boolean scimeta = false;
1349
        //TODO: this should be read from a .properties file instead of being hard coded
1350
        switch (sysmeta.getObjectFormat()) {
1351
            case EML_2_1_0: scimeta = true; break;
1352
            case EML_2_0_1: scimeta = true; break;
1353
            case EML_2_0_0: scimeta = true; break;
1354
            case FGDC_STD_001_1_1999: scimeta = true; break;
1355
            case FGDC_STD_001_1998: scimeta = true; break;
1356
            case NCML_2_2: scimeta = true; break;
1357
            case DSPACE_METS_SIP_1_0: scimeta = true; break;
1358
        }
1359
        
1360
        return scimeta;*/
1361
        
1362
        return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
1363
    }
1364

    
1365
    /**
1366
     * insert a data doc
1367
     * @param object
1368
     * @param guid
1369
     * @param sessionData
1370
     * @throws ServiceFailure
1371
     * @returns localId of the data object inserted
1372
     */
1373
    private String insertDataObject(InputStream object, Identifier guid, 
1374
            SessionData sessionData) throws ServiceFailure {
1375
        
1376
        String username = "public";
1377
        String[] groups = null;
1378
        if(sessionData != null)
1379
        {
1380
          username = sessionData.getUserName();
1381
          groups = sessionData.getGroupNames();
1382
        }
1383

    
1384
        // generate guid/localId pair for object
1385
        logMetacat.debug("Generating a guid/localId mapping");
1386
        IdentifierManager im = IdentifierManager.getInstance();
1387
        String localId = im.generateLocalId(guid.getValue(), 1);
1388

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

    
1452
    /**
1453
     * write a file to a stream
1454
     * @param dir
1455
     * @param fileName
1456
     * @param data
1457
     * @return
1458
     * @throws ServiceFailure
1459
     */
1460
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1461
        throws ServiceFailure {
1462
        
1463
        File newFile = new File(dir, fileName);
1464
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1465

    
1466
        try {
1467
            if (newFile.createNewFile()) {
1468
                // write data stream to desired file
1469
                OutputStream os = new FileOutputStream(newFile);
1470
                long length = IOUtils.copyLarge(data, os);
1471
                os.flush();
1472
                os.close();
1473
            } else {
1474
                logMetacat.debug("File creation failed, or file already exists.");
1475
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1476
            }
1477
        } catch (FileNotFoundException e) {
1478
            logMetacat.debug("FNF: " + e.getMessage());
1479
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1480
                    + e.getMessage());
1481
        } catch (IOException e) {
1482
            logMetacat.debug("IOE: " + e.getMessage());
1483
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1484
                    + " " + e.getMessage());
1485
        }
1486

    
1487
        return newFile;
1488
    }
1489

    
1490
    /**
1491
     * insert a systemMetadata doc, return the localId of the sysmeta
1492
     */
1493
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1494
        throws ServiceFailure 
1495
    {
1496
        logMetacat.debug("Starting to insert SystemMetadata...");
1497
    
1498
        // generate guid/localId pair for sysmeta
1499
        Identifier sysMetaGuid = new Identifier();
1500
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1501
        sysmeta.setDateSysMetadataModified(new Date());
1502
        System.out.println("****inserting new system metadata with modified date " + 
1503
                sysmeta.getDateSysMetadataModified());
1504

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

    
1604
        // generate guid/localId pair for sysmeta
1605
        String localId = null;
1606
        if(insertOrUpdate.equals("insert"))
1607
        {
1608
            localId = im.generateLocalId(guid.getValue(), 1, isSystemMetadata);
1609
        }
1610
        else
1611
        {
1612
            //localid should already exist in the identifier table, so just find it
1613
            try
1614
            {
1615
                System.out.println("updating guid " + guid.getValue());
1616
                if(!isSystemMetadata)
1617
                {
1618
                    System.out.println("looking in identifier table for guid " + guid.getValue());
1619
                    localId = im.getLocalId(guid.getValue());
1620
                }
1621
                else
1622
                {
1623
                    System.out.println("looking in systemmetadata table for guid " + guid.getValue());
1624
                    localId = im.getSystemMetadataLocalId(guid.getValue());
1625
                }
1626
                System.out.println("localId: " + localId);
1627
                //increment the revision
1628
                String docid = localId.substring(0, localId.lastIndexOf("."));
1629
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1630
                int rev = new Integer(revS).intValue();
1631
                rev++;
1632
                docid = docid + "." + rev;
1633
                localId = docid;
1634
                System.out.println("incremented localId: " + localId);
1635
            }
1636
            catch(McdbDocNotFoundException e)
1637
            {
1638
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1639
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1640
            }
1641
        }
1642
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1643
                localId);
1644

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