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:ss.SZ");
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("1620", "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("1100", "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
        if (isScienceMetadata) {
319
            // CASE METADATA:
320
            try {
321
                //System.out.println("CrudService: inserting document with guid " + guid.getValue());
322
                this.insertDocument(object, guid, sessionData);
323
                localId = im.getLocalId(guid.getValue());
324
            } catch (IOException e) {
325
                String msg = "Could not create string from XML stream: " +
326
                    " " + e.getMessage();
327
                logMetacat.debug(msg);
328
                throw new ServiceFailure("1190", msg);
329
            } catch(Exception e) {
330
                String msg = "Unexpected error in CrudService.create: " + e.getMessage();
331
                logMetacat.debug(msg);
332
                throw new ServiceFailure("1190", msg);
333
            }
334
            
335

    
336
        } else {
337
            // DEFAULT CASE: DATA (needs to be checked and completed)
338
            localId = insertDataObject(object, guid, sessionData);
339
            
340
        }
341

    
342
        // For Metadata and Data, insert the system metadata into the object store too
343
        String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
344
        //get the document info.  add any access params for the sysmeta too
345
        //System.out.println("looking for access records to add for system " +
346
        //    "metadata who's parent doc's  local id is " + localId);
347
        try
348
        {
349
            Hashtable<String, Object> h = im.getDocumentInfo(localId.substring(0, localId.lastIndexOf(".")));
350
            Vector v = (Vector)h.get("access");
351
            for(int i=0; i<v.size(); i++)
352
            {
353
                Hashtable ah = (Hashtable)v.elementAt(i);
354
                String principal = (String)ah.get("principal_name");
355
                String permission = (String)ah.get("permission");
356
                String permissionType = (String)ah.get("permission_type");
357
                String permissionOrder = (String)ah.get("permission_order");
358
                int perm = new Integer(permission).intValue();
359
                //System.out.println("found access record for principal " + principal);
360
                //System.out.println("permission: " + perm + " perm_type: " + permissionType + 
361
                //    " perm_order: " + permissionOrder);
362
                this.setAccess(token, guid, principal, perm, permissionType, permissionOrder, true);
363
            }
364
        }
365
        catch(Exception e)
366
        {
367
            logMetacat.error("Error setting permissions on System Metadata object " + 
368
                    " with id " + sysMetaLocalId + ": " + e.getMessage());
369
            //TODO: decide if this error should cancel the entire create or
370
            //if it should continue with just a logged error.
371
        }
372
        
373
        
374
        logMetacat.debug("Returning from CrudService.create()");
375
        EventLog.getInstance().log(metacatUrl,
376
                username, localId, "create");
377
        logCrud.info("create D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
378
                ":D1SYSMETADATA:"+ sysMetaLocalId + ":");
379
        return guid;
380
    }
381
    
382
    /**
383
     * update an existing object with a new object.  Change the system metadata
384
     * to reflect the changes and update it as well.
385
     */
386
    public Identifier update(AuthToken token, Identifier guid, 
387
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
388
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
389
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
390
            NotImplemented {
391
        try
392
        {
393
            SessionData sessionData = getSessionData(token);
394
            
395
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
396
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
397
            //change sm.old's obsoletedBy field 
398
            List l = sm.getObsoletedByList();
399
            l.add(guid);
400
            sm.setObsoletedByList(l);
401
            //update sm.old
402
            updateSystemMetadata(sm, sessionData);
403
            
404
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
405
            sysmeta.addObsolete(obsoletedGuid);
406
            //insert sm.new
407
            String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
408
            String localId;
409
            
410
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
411
            if(isScienceMetadata)
412
            {
413
                //update the doc
414
                localId = updateDocument(object, obsoletedGuid, guid, sessionData, false);
415
            }
416
            else
417
            {
418
                //update a data file, not xml
419
                localId = insertDataObject(object, guid, sessionData);
420
            }
421
            
422
            IdentifierManager im = IdentifierManager.getInstance();
423
            String username = "public";
424
            if(sessionData != null)
425
            {
426
                username = sessionData.getUserName();
427
            }
428
            EventLog.getInstance().log(metacatUrl,
429
                    username, im.getLocalId(guid.getValue()), "update");
430
            logCrud.info("update D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
431
                    ":D1SYSMETADATA:"+ sysMetaLocalId + ":");
432
            return guid;
433
        }
434
        catch(Exception e)
435
        {
436
            throw new ServiceFailure("1310", "Error updating document in CrudService: " + e.getMessage());
437
        }
438
    }
439
    
440
    /**
441
     * set access permissions on both the science metadata and system metadata
442
     */
443
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
444
            String permissionType, String permissionOrder)
445
      throws ServiceFailure
446
    {
447
        setAccess(token, id, principal, permission, permissionType, permissionOrder, true);
448
    }
449
    
450
    /**
451
     * set access control on the doc
452
     * @param token
453
     * @param id
454
     * @param principal
455
     * @param permission
456
     */
457
    public void setAccess(AuthToken token, Identifier id, String principal, int permission,
458
      String permissionType, String permissionOrder, boolean setSystemMetadata)
459
      throws ServiceFailure
460
    {
461
        String perm = "";
462
        if(permission >= 4)
463
        {
464
            perm = "read";
465
        }
466
        if(permission >= 6)
467
        {
468
            perm = "write";
469
        }
470
        //System.out.println("perm in setAccess: " + perm);
471
        //System.out.println("permission in setAccess: " + permission);
472
        setAccess(token, id, principal, perm, permissionType, permissionOrder,
473
                setSystemMetadata);
474
       
475
    }
476
    
477
    /**
478
     * set the permission on the document
479
     * @param token
480
     * @param principal
481
     * @param permission
482
     * @param permissionType
483
     * @param permissionOrder
484
     * @return
485
     */
486
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
487
            String permissionType, String permissionOrder, boolean setSystemMetadata)
488
      throws ServiceFailure
489
    {
490
        /* TODO:
491
         * This is also not part of the D1 Crud spec.  This method is needed for
492
         * systems such as metacat where access to objects is controlled by
493
         * and ACL.  Higher level decisions need to be made about how this
494
         * should work within D1.
495
         */
496
        try
497
        {
498
            final SessionData sessionData = getSessionData(token);
499
            if(sessionData == null)
500
            {
501
                throw new ServiceFailure("1000", "User must be logged in to set access.");
502
            }
503
            IdentifierManager im = IdentifierManager.getInstance();
504
            String docid = im.getLocalId(id.getValue());
505
        
506
            String permNum = "0";
507
            if(permission.equals("read"))
508
            {
509
                permNum = "4";
510
            }
511
            else if(permission.equals("write"))
512
            {
513
                permNum = "6";
514
            }
515
            System.out.println("user " + sessionData.getUserName() + 
516
                    " is setting access level " + permNum + " for permission " + 
517
                    permissionType + " on doc with localid " + docid);
518
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
519
                    principal, permNum, permissionType, permissionOrder);
520
            if(setSystemMetadata)
521
            {
522
                //set the same perms on the system metadata doc
523
                String smlocalid = im.getSystemMetadataLocalId(id.getValue());
524
                System.out.println("setting access on SM doc with localid " + smlocalid);
525
                //cs.setAccess(token, smid, principal, permission, permissionType, permissionOrder);
526
                handler.setAccess(metacatUrl, sessionData.getUserName(), smlocalid,
527
                        principal, permNum, permissionType, permissionOrder);
528
            }
529
            String username = "public";
530
            if(sessionData != null)
531
            {
532
                username = sessionData.getUserName();
533
            }
534
            EventLog.getInstance().log(metacatUrl,
535
                    username, im.getLocalId(id.getValue()), "setAccess");
536
            logCrud.info("setAccess");
537
        }
538
        catch(Exception e)
539
        {
540
            e.printStackTrace();
541
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
542
        }
543
    }
544
    
545
    /**
546
     *  Retrieve the list of objects present on the MN that match the calling 
547
     *  parameters. This method is required to support the process of Member 
548
     *  Node synchronization. At a minimum, this method should be able to 
549
     *  return a list of objects that match:
550
     *  startTime <= SystemMetadata.dateSysMetadataModified
551
     *  but is expected to also support date range (by also specifying endTime), 
552
     *  and should also support slicing of the matching set of records by 
553
     *  indicating the starting index of the response (where 0 is the index 
554
     *  of the first item) and the count of elements to be returned.
555
     *  
556
     *  If startTime or endTime is null, the query is not restricted by that parameter.
557
     *  
558
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
559
     * @param token
560
     * @param startTime
561
     * @param endTime
562
     * @param objectFormat
563
     * @param replicaStatus
564
     * @param start
565
     * @param count
566
     * @return ObjectList
567
     * @throws NotAuthorized
568
     * @throws InvalidRequest
569
     * @throws NotImplemented
570
     * @throws ServiceFailure
571
     * @throws InvalidToken
572
     */
573
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
574
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
575
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
576
    {
577
      ObjectList ol = new ObjectList();
578
      final SessionData sessionData = getSessionData(token);
579
      int totalAfterQuery = 0;
580
      
581
      try
582
      {
583
          if (PropertyService.getProperty("database.queryCacheOn").equals("true"))
584
          {
585
              //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
586
              DBQuery.clearQueryResultCache();
587
          }
588
      }
589
      catch (PropertyNotFoundException e1)
590
      {
591
          //just don't do anything
592
      }
593
      
594
      try
595
      {
596
          //TODO: Milliseconds need to be added to the dateFormat
597
          System.out.println("=========== Listing Objects =============");
598
          System.out.println("Current server time is: " + new Date());
599
          if(startTime != null)
600
          {
601
              System.out.println("query start time is " + startTime);
602
          }
603
          if(endTime != null)
604
          {
605
              System.out.println("query end time is " + endTime);
606
          }
607
          params.clear();
608
          params.put("returndoctype", new String[] {PropertyService.getProperty("crudService.listObjects.ReturnDoctype")});
609
          params.put("qformat", new String[] {PropertyService.getProperty("crudService.listObjects.QFormat")});
610
          params.put("returnfield", new String[] {
611
                  PropertyService.getProperty("crudService.listObjects.ReturnField.1"), 
612
                  PropertyService.getProperty("crudService.listObjects.ReturnField.2"),
613
                  PropertyService.getProperty("crudService.listObjects.ReturnField.3"),
614
                  PropertyService.getProperty("crudService.listObjects.ReturnField.4"),
615
                  PropertyService.getProperty("crudService.listObjects.ReturnField.5"),
616
                  PropertyService.getProperty("crudService.listObjects.ReturnField.6"),
617
                  PropertyService.getProperty("crudService.listObjects.ReturnField.7"),
618
                  });
619
          params.put("anyfield", new String[] {PropertyService.getProperty("crudService.listObjects.anyfield")});
620
          
621
          /*System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
622
                  " sessionid: " + sessionData.getId() + " params: ");
623
          String url = metacatUrl + "/metacat?action=query&sessionid=" + sessionData.getId();
624
          Enumeration keys = params.keys();
625
          while(keys.hasMoreElements())
626
          {
627
              String key = (String)keys.nextElement();
628
              String[] parr = params.get(key);
629
              for(int i=0; i<parr.length; i++)
630
              {
631
                  System.out.println("param " + key + ": " + parr[i]);
632
                  url += "&" + key + "=" + parr[i] ;
633
              }
634
          }
635
          System.out.println("query url: " + url);
636
          */
637
          String username = "public";
638
          String[] groups = null;
639
          String sessionid = "";
640
          if(sessionData != null)
641
          {
642
              username = sessionData.getUserName();
643
              groups = sessionData.getGroupNames();
644
              sessionid = sessionData.getId();
645
          }
646
          
647
          MetacatResultSet rs = handler.query(metacatUrl, params, username, 
648
                  groups, sessionid);
649
          List docs = rs.getDocuments();
650
          
651
          System.out.println("query returned " + docs.size() + " documents.");
652
          Vector<Document> docCopy = new Vector<Document>();
653
          
654
          //preparse the list to remove any that don't match the query params
655
          /* TODO: this type of query/subquery processing is probably not scalable
656
           * to larger object stores.  This code should be revisited.  The metacat
657
           * query handler should probably be altered to handle the type of query 
658
           * done here.
659
           */ 
660
          for(int i=0; i<docs.size(); i++)
661
          {
662
              Document d = (Document)docs.get(i);
663
              
664
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
665
              
666
              if(returnedObjectFormat != null && 
667
                 objectFormat != null && 
668
                 !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
669
              { //make sure the objectFormat is the one specified
670
                  continue;
671
              }
672
              
673
              String dateSMM = d.getField("dateSysMetadataModified");
674
              if((startTime != null || endTime != null) && dateSMM == null)
675
              {  //if startTime or endTime are not null, we need a date to compare to
676
                  continue;
677
              }
678
              
679
              //date parse
680
              Date dateSysMetadataModified = null;
681
              if(dateSMM != null)
682
              {
683

    
684
                  /*                  
685
                  if(dateSMM.indexOf(".") != -1)
686
                  {  //strip the milliseconds
687
                      //TODO: don't do this. we need milliseconds now.
688
                      //TODO: explore ISO 8601 to figure out milliseconds
689
                      dateSMM = dateSMM.substring(0, dateSMM.indexOf(".")) + 'Z';
690
                  }
691
                  */
692
                  //System.out.println("dateSMM: " + dateSMM);
693
                  //dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-0"));
694
                  try
695
                  {   //the format we want
696
                      dateSysMetadataModified = dateFormat.parse(dateSMM);
697
                  }
698
                  catch(java.text.ParseException pe)
699
                  {   //try another legacy format
700
                      DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S'Z'");
701
                      dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
702
                      dateSysMetadataModified = dateFormat2.parse(dateSMM);
703
                  }                  
704
              }
705
              
706
              /*System.out.println("====================================");
707
              System.out.println("doc number " + i);
708
              System.out.println("docid: " + d.docid);
709
              System.out.println("guid: " + d.getField("identifier").trim());
710
              System.out.println("dateSMM: " + dateSMM);
711
              System.out.println("dateSysMetadataModified: " + dateSysMetadataModified);
712
              System.out.println("startTime: " + startTime);
713
              System.out.println("endtime: " + endTime);*/
714
              
715
              int startDateComparison = 0;
716
              int endDateComparison = 0;
717
              if(startTime != null)
718
              {
719
                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
720
                  zTime.setTime(startTime);
721
                  startTime = zTime.getTime();
722
                  
723
                  if(dateSysMetadataModified == null)
724
                  {
725
                      startDateComparison = -1;
726
                  }
727
                  else
728
                  {
729
                      startDateComparison = dateSysMetadataModified.compareTo(startTime);
730
                  }
731
                  //System.out.println("startDateCom: " + startDateComparison);
732
              }
733
              else
734
              {
735
                  startDateComparison = 1;
736
              }
737
              
738
              if(endTime != null)
739
              {
740
                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
741
                  zTime.setTime(endTime);
742
                  endTime = zTime.getTime();
743
                  
744
                  if(dateSysMetadataModified == null)
745
                  {
746
                      endDateComparison = 1;
747
                  }
748
                  else
749
                  {
750
                      endDateComparison = dateSysMetadataModified.compareTo(endTime);
751
                  }
752
                  //System.out.println("endDateCom: " + endDateComparison);
753
              }
754
              else
755
              {
756
                  endDateComparison = -1;
757
              }
758
              
759
              
760
              if(startDateComparison < 0 || endDateComparison > 0)
761
              { 
762
                  continue;                  
763
              }
764
              
765
              docCopy.add((Document)docs.get(i));
766
          } //end pre-parse
767
          
768
          docs = docCopy;
769
          totalAfterQuery = docs.size();
770
          //System.out.println("total after subquery: " + totalAfterQuery);
771
          
772
          //make sure we don't run over the end
773
          int end = start + count;
774
          if(end > docs.size())
775
          {
776
              end = docs.size();
777
          }
778
          
779
          for(int i=start; i<end; i++)
780
          {
781
              //get the document from the result
782
              Document d = (Document)docs.get(i);
783
              //System.out.println("processing doc " + d.docid);
784
              
785
              String dateSMM = d.getField("dateSysMetadataModified");
786
              //System.out.println("dateSMM: " + dateSMM);
787
              //System.out.println("parsed date: " + parseDate(dateSMM));
788
              Date dateSysMetadataModified = null;
789
              if(dateSMM != null)
790
              {
791
                  try
792
                  {
793
                      dateSysMetadataModified = parseDate(dateSMM);
794
                  }
795
                  catch(Exception e)
796
                  { //if we fail to parse the date, just ignore the value
797
                      dateSysMetadataModified = null;
798
                  }
799
              }
800
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
801
                
802
              
803
              ObjectInfo info = new ObjectInfo();
804
              //add the fields to the info object
805
              Checksum cs = new Checksum();
806
              cs.setValue(d.getField("checksum"));
807
              String csalg = d.getField("algorithm");
808
              if(csalg == null)
809
              {
810
                  csalg = "MD5";
811
              }
812
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
813
              cs.setAlgorithm(ca);
814
              info.setChecksum(cs);
815
              info.setDateSysMetadataModified(dateSysMetadataModified);
816
              Identifier id = new Identifier();
817
              id.setValue(d.getField("identifier").trim());
818
              info.setIdentifier(id);
819
              info.setObjectFormat(returnedObjectFormat);
820
              String size = d.getField("size");
821
              if(size != null)
822
              {
823
                  info.setSize(new Long(size.trim()).longValue());
824
              }
825
              //add the ObjectInfo to the ObjectList
826
              //logCrud.info("objectFormat: " + info.getObjectFormat().toString());
827
              //logCrud.info("id: " + info.getIdentifier().getValue());
828
              
829
              if(info.getIdentifier().getValue() != null)
830
              { //id can be null from tests.  should not happen in production.
831
                  if((info.getObjectFormat() != null && !info.getObjectFormat().toString().trim().equals("")))
832
                  { //objectFormat needs to not be null and not be an empty string
833
                    ol.addObjectInfo(info);
834
                  }
835
                  else
836
                  {
837
                      logCrud.info("Not adding object with null objectFormat" + info.getIdentifier().getValue().toString());
838
                  }
839
              }
840
             
841
          }
842
      }
843
      catch(Exception e)
844
      {
845
          e.printStackTrace();
846
          logCrud.error("Error creating ObjectList: " + e.getMessage() + " cause: " + e.getCause());
847
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
848
      }
849
      String username = "public";
850
      if(sessionData != null)
851
      {
852
          username = sessionData.getUserName();
853
      }
854
      EventLog.getInstance().log(metacatUrl,
855
              username, null, "read");
856
      logCrud.info("listObjects");
857
      if(totalAfterQuery < count)
858
      {
859
          count = totalAfterQuery;
860
      }
861
      ol.setCount(count);
862
      ol.setStart(start);
863
      ol.setTotal(totalAfterQuery);
864
      return ol;
865
    }
866
    
867
    /**
868
     * Call listObjects with the default values for replicaStatus (true), start (0),
869
     * and count (1000).
870
     * @param token
871
     * @param startTime
872
     * @param endTime
873
     * @param objectFormat
874
     * @return
875
     * @throws NotAuthorized
876
     * @throws InvalidRequest
877
     * @throws NotImplemented
878
     * @throws ServiceFailure
879
     * @throws InvalidToken
880
     */
881
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
882
        ObjectFormat objectFormat)
883
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
884
    {
885
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
886
    }
887

    
888
    /**
889
     * Delete a document.  NOT IMPLEMENTED
890
     */
891
    public Identifier delete(AuthToken token, Identifier guid)
892
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
893
            NotImplemented {
894
        logCrud.info("delete");
895
        throw new NotImplemented("1321", "This method not yet implemented.");
896
    }
897

    
898
    /**
899
     * describe a document.  NOT IMPLEMENTED
900
     */
901
    public DescribeResponse describe(AuthToken token, Identifier guid)
902
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
903
            NotImplemented {
904
        logCrud.info("describe");
905
        throw new NotImplemented("1361", "This method not yet implemented.");
906
    }
907
    
908
    /**
909
     * get a document with a specified guid.
910
     */
911
    public InputStream get(AuthToken token, Identifier guid)
912
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
913
            NotImplemented {
914
        
915
        // Retrieve the session information from the AuthToken
916
        // If the session is expired, then the user is 'public'
917
        if(token == null)
918
        {
919
            token = new AuthToken("Public");
920
        }
921
        final SessionData sessionData = getSessionData(token);
922
        
923
        // Look up the localId for this global identifier
924
        IdentifierManager im = IdentifierManager.getInstance();
925
        try {
926
            final String localId = im.getLocalId(guid.getValue());
927

    
928
            final InputStreamFromOutputStream<String> objectStream = 
929
                new InputStreamFromOutputStream<String>() {
930
                
931
                @Override
932
                public String produce(final OutputStream dataSink) throws Exception {
933

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

    
983
                    return "Completed";
984
                }
985
            };
986
            String username = "public";
987
            if(sessionData != null)
988
            {
989
                username = sessionData.getUserName();
990
            }
991
            
992
            EventLog.getInstance().log(metacatUrl,
993
                    username, im.getLocalId(guid.getValue()), "read");
994
            logCrud.info("get D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
995
                    ":");
996
            return objectStream;
997

    
998
        } catch (McdbDocNotFoundException e) {
999
            throw new NotFound("1020", e.getMessage());
1000
        } 
1001
    }
1002

    
1003
    /**
1004
     * get the checksum for a document.  defaults to MD5.
1005
     */
1006
    public Checksum getChecksum(AuthToken token, Identifier guid)
1007
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1008
            InvalidRequest, NotImplemented 
1009
    {
1010
        logCrud.info("getChecksum");
1011
        return getChecksum(token, guid, "MD5");
1012
    }
1013

    
1014
    /**
1015
     * get the checksum for a document with the given algorithm
1016
     */
1017
    public Checksum getChecksum(AuthToken token, Identifier guid, 
1018
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
1019
            NotAuthorized, NotFound, InvalidRequest, NotImplemented 
1020
    {
1021
        logCrud.info("getChecksum");
1022
        if(checksumAlgorithm == null)
1023
        {
1024
            checksumAlgorithm = "MD5";
1025
        }
1026
        InputStream docStream = get(token, guid);
1027
        String checksum;
1028
        try
1029
        {
1030
            checksum = checksum(docStream, checksumAlgorithm);
1031
        }
1032
        catch(Exception e)
1033
        {
1034
            throw new ServiceFailure("1410", "Error getting checksum: " + e.getMessage());
1035
        }
1036
        Checksum c = new Checksum();
1037
        c.setAlgorithm(ChecksumAlgorithm.convert(checksumAlgorithm));
1038
        c.setValue(checksum);
1039
        return c;
1040
    }
1041

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

    
1185
    /**
1186
     * get the system metadata for a document with a specified guid.
1187
     */
1188
public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
1189
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1190
            InvalidRequest, NotImplemented {
1191
        
1192
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
1193
        
1194
        // Retrieve the session information from the AuthToken
1195
        // If the session is expired, then the user is 'public'
1196
        final SessionData sessionData = getSessionData(token);
1197
                
1198
        try {
1199
            IdentifierManager im = IdentifierManager.getInstance();
1200
            final String localId = im.getSystemMetadataLocalId(guid.getValue());
1201
            
1202
            // Read system metadata from metacat's db
1203
            final InputStreamFromOutputStream<String> objectStream = 
1204
                new InputStreamFromOutputStream<String>() {
1205
                
1206
                @Override
1207
                public String produce(final OutputStream dataSink) throws Exception {
1208
                    //TODO: change to memory mapped IO so that exceptions get 
1209
                    //passed to the response correctly.
1210
                    try {
1211
                        String username = "public";
1212
                        String[] groupnames = null;
1213
                        if(sessionData != null)
1214
                        {
1215
                            username = sessionData.getUserName();
1216
                            groupnames = sessionData.getGroupNames();
1217
                        }
1218
                        
1219
                        handler.readFromMetacat(metacatUrl, null, 
1220
                                dataSink, localId, "xml",
1221
                                username, 
1222
                                groupnames, true, params);
1223
                    } catch (PropertyNotFoundException e) {
1224
                        e.printStackTrace();
1225
                        throw new ServiceFailure("1090", "Property not found while reading system metadata from metacat: " + e.getMessage());
1226
                    } catch (ClassNotFoundException e) {
1227
                        e.printStackTrace();
1228
                        throw new ServiceFailure("1090", "Class not found while reading system metadata from metacat: " + e.getMessage());
1229
                    } catch (IOException e) {
1230
                        e.printStackTrace();
1231
                        throw new ServiceFailure("1090", "IOException while reading system metadata from metacat: " + e.getMessage());
1232
                    } catch (SQLException e) {
1233
                        e.printStackTrace();
1234
                        throw new ServiceFailure("1090", "SQLException while reading system metadata from metacat: " + e.getMessage());
1235
                    } catch (McdbException e) {
1236
                        e.printStackTrace();
1237
                        throw new ServiceFailure("1090", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
1238
                    } catch (ParseLSIDException e) {
1239
                        e.printStackTrace();
1240
                        throw new NotFound("1060", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
1241
                    } catch (InsufficientKarmaException e) {
1242
                        e.printStackTrace();
1243
                        throw new NotAuthorized("1040", "User not authorized for get() on system metadata: " + e.getMessage());
1244
                    }
1245

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

    
1331
    /*
1332
     * Look up the information on the session using the token provided in
1333
     * the AuthToken.  The Session should have all relevant user information.
1334
     * If the session has expired or is invalid, the 'public' session will
1335
     * be returned, giving the user anonymous access.
1336
     */
1337
    public static SessionData getSessionData(AuthToken token) {
1338
        SessionData sessionData = null;
1339
        String sessionId = "PUBLIC";
1340
        if (token != null) {
1341
            sessionId = token.getToken();
1342
        }
1343
        
1344
        // if the session id is registered in SessionService, get the
1345
        // SessionData for it. Otherwise, use the public session.
1346
        //System.out.println("sessionid: " + sessionId);
1347
        if (sessionId != null &&
1348
            !sessionId.toLowerCase().equals("public") &&
1349
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1350
        {
1351
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1352
        } else {
1353
            sessionData = SessionService.getInstance().getPublicSession();
1354
        }
1355
        
1356
        return sessionData;
1357
    }
1358

    
1359
    /** 
1360
     * Determine if a given object should be treated as an XML science metadata
1361
     * object. 
1362
     * 
1363
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1364
     * 
1365
     * @param sysmeta the SystemMetadata describig the object
1366
     * @return true if the object should be treated as science metadata
1367
     */
1368
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1369
        /*boolean scimeta = false;
1370
        //TODO: this should be read from a .properties file instead of being hard coded
1371
        switch (sysmeta.getObjectFormat()) {
1372
            case EML_2_1_0: scimeta = true; break;
1373
            case EML_2_0_1: scimeta = true; break;
1374
            case EML_2_0_0: scimeta = true; break;
1375
            case FGDC_STD_001_1_1999: scimeta = true; break;
1376
            case FGDC_STD_001_1998: scimeta = true; break;
1377
            case NCML_2_2: scimeta = true; break;
1378
            case DSPACE_METS_SIP_1_0: scimeta = true; break;
1379
        }
1380
        
1381
        return scimeta;*/
1382
        
1383
        return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
1384
    }
1385

    
1386
    /**
1387
     * insert a data doc
1388
     * @param object
1389
     * @param guid
1390
     * @param sessionData
1391
     * @throws ServiceFailure
1392
     * @returns localId of the data object inserted
1393
     */
1394
    private String insertDataObject(InputStream object, Identifier guid, 
1395
            SessionData sessionData) throws ServiceFailure {
1396
        
1397
        String username = "public";
1398
        String[] groups = null;
1399
        if(sessionData != null)
1400
        {
1401
          username = sessionData.getUserName();
1402
          groups = sessionData.getGroupNames();
1403
        }
1404

    
1405
        // generate guid/localId pair for object
1406
        logMetacat.debug("Generating a guid/localId mapping");
1407
        IdentifierManager im = IdentifierManager.getInstance();
1408
        String localId = im.generateLocalId(guid.getValue(), 1);
1409

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

    
1473
    /**
1474
     * write a file to a stream
1475
     * @param dir
1476
     * @param fileName
1477
     * @param data
1478
     * @return
1479
     * @throws ServiceFailure
1480
     */
1481
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1482
        throws ServiceFailure {
1483
        
1484
        File newFile = new File(dir, fileName);
1485
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1486

    
1487
        try {
1488
            if (newFile.createNewFile()) {
1489
                // write data stream to desired file
1490
                OutputStream os = new FileOutputStream(newFile);
1491
                long length = IOUtils.copyLarge(data, os);
1492
                os.flush();
1493
                os.close();
1494
            } else {
1495
                logMetacat.debug("File creation failed, or file already exists.");
1496
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1497
            }
1498
        } catch (FileNotFoundException e) {
1499
            logMetacat.debug("FNF: " + e.getMessage());
1500
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1501
                    + e.getMessage());
1502
        } catch (IOException e) {
1503
            logMetacat.debug("IOE: " + e.getMessage());
1504
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1505
                    + " " + e.getMessage());
1506
        }
1507

    
1508
        return newFile;
1509
    }
1510

    
1511
    /**
1512
     * insert a systemMetadata doc, return the localId of the sysmeta
1513
     */
1514
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1515
        throws ServiceFailure 
1516
    {
1517
        logMetacat.debug("Starting to insert SystemMetadata...");
1518
    
1519
        // generate guid/localId pair for sysmeta
1520
        Identifier sysMetaGuid = new Identifier();
1521
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1522
        sysmeta.setDateSysMetadataModified(new Date());
1523
        System.out.println("****inserting new system metadata with modified date " + 
1524
                sysmeta.getDateSysMetadataModified());
1525

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

    
1626
        // generate guid/localId pair for sysmeta
1627
        String localId = null;
1628
        if(insertOrUpdate.equals("insert"))
1629
        {
1630
            localId = im.generateLocalId(guid.getValue(), 1, isSystemMetadata);
1631
        }
1632
        else
1633
        {
1634
            //localid should already exist in the identifier table, so just find it
1635
            try
1636
            {
1637
                System.out.println("updating guid " + guid.getValue());
1638
                if(!isSystemMetadata)
1639
                {
1640
                    System.out.println("looking in identifier table for guid " + guid.getValue());
1641
                    localId = im.getLocalId(guid.getValue());
1642
                }
1643
                else
1644
                {
1645
                    System.out.println("looking in systemmetadata table for guid " + guid.getValue());
1646
                    localId = im.getSystemMetadataLocalId(guid.getValue());
1647
                }
1648
                System.out.println("localId: " + localId);
1649
                //increment the revision
1650
                String docid = localId.substring(0, localId.lastIndexOf("."));
1651
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1652
                int rev = new Integer(revS).intValue();
1653
                rev++;
1654
                docid = docid + "." + rev;
1655
                localId = docid;
1656
                System.out.println("incremented localId: " + localId);
1657
            }
1658
            catch(McdbDocNotFoundException e)
1659
            {
1660
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1661
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1662
            }
1663
        }
1664
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1665
                localId);
1666

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