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("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
          Enumeration keys = params.keys();
622
          while(keys.hasMoreElements())
623
          {
624
              String key = (String)keys.nextElement();
625
              String[] parr = params.get(key);
626
              for(int i=0; i<parr.length; i++)
627
              {
628
                  System.out.println("param " + key + ": " + parr[i]);
629
              }
630
          }
631
          
632
          //params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
633
          //params.put("qformat", new String[] {"xml"});
634
          //params.put("returnfield", new String[] {"size", "originMemberNode", 
635
          //        "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "checksum/@algorithm"});
636
          //params.put("anyfield", new String[] {"%"});
637
          
638
          System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
639
             " sessionid: " + sessionData.getId() + " params: " + params.toString());
640
          String username = "public";
641
          String[] groups = null;
642
          String sessionid = "";
643
          if(sessionData != null)
644
          {
645
              username = sessionData.getUserName();
646
              groups = sessionData.getGroupNames();
647
              sessionid = sessionData.getId();
648
          }
649
          
650
          MetacatResultSet rs = handler.query(metacatUrl, params, username, 
651
                  groups, sessionid);
652
          List docs = rs.getDocuments();
653
          
654
          System.out.println("query returned " + docs.size() + " documents.");
655
          Vector<Document> docCopy = new Vector<Document>();
656
          
657
          //preparse the list to remove any that don't match the query params
658
          /* TODO: this type of query/subquery processing is probably not scalable
659
           * to larger object stores.  This code should be revisited.  The metacat
660
           * query handler should probably be altered to handle the type of query 
661
           * done here.
662
           */ 
663
          for(int i=0; i<docs.size(); i++)
664
          {
665
              Document d = (Document)docs.get(i);
666
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
667
              
668
              if(returnedObjectFormat != null && 
669
                 objectFormat != null && 
670
                 !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
671
              { //make sure the objectFormat is the one specified
672
                  continue;
673
              }
674
              
675
              String dateSMM = d.getField("dateSysMetadataModified");
676
              if((startTime != null || endTime != null) && dateSMM == null)
677
              {  //if startTime or endTime are not null, we need a date to compare to
678
                  continue;
679
              }
680
              
681
              //date parse
682
              Date dateSysMetadataModified = null;
683
              if(dateSMM != null)
684
              {
685
                  //dateSysMetadataModified = parseDate(dateSMM);
686
                  if(dateSMM.indexOf(".") != -1)
687
                  {  //strip the milliseconds
688
                      //TODO: don't do this. we need milliseconds now.
689
                      //TODO: explore ISO 8601 to figure out milliseconds
690
                      dateSMM = dateSMM.substring(0, dateSMM.indexOf(".")) + 'Z';
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'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("dateSysMetadataModified: " + dateSysMetadataModified);
710
              System.out.println("startTime: " + startTime);
711
              System.out.println("endtime: " + endTime);*/
712
              
713
              int startDateComparison = 0;
714
              int endDateComparison = 0;
715
              if(startTime != null)
716
              {
717
                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
718
                  zTime.setTime(startTime);
719
                  startTime = zTime.getTime();
720
                  
721
                  if(dateSysMetadataModified == null)
722
                  {
723
                      startDateComparison = -1;
724
                  }
725
                  else
726
                  {
727
                      startDateComparison = dateSysMetadataModified.compareTo(startTime);
728
                  }
729
                  //System.out.println("startDateCom: " + startDateComparison);
730
              }
731
              else
732
              {
733
                  startDateComparison = 1;
734
              }
735
              
736
              if(endTime != null)
737
              {
738
                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
739
                  zTime.setTime(endTime);
740
                  endTime = zTime.getTime();
741
                  
742
                  if(dateSysMetadataModified == null)
743
                  {
744
                      endDateComparison = 1;
745
                  }
746
                  else
747
                  {
748
                      endDateComparison = dateSysMetadataModified.compareTo(endTime);
749
                  }
750
                  //System.out.println("endDateCom: " + endDateComparison);
751
              }
752
              else
753
              {
754
                  endDateComparison = -1;
755
              }
756
              
757
              
758
              if(startDateComparison < 0 || endDateComparison > 0)
759
              { 
760
                  continue;                  
761
              }
762
              
763
              docCopy.add((Document)docs.get(i));
764
          } //end pre-parse
765
          
766
          docs = docCopy;
767
          totalAfterQuery = docs.size();
768
          //System.out.println("total after subquery: " + totalAfterQuery);
769
          
770
          //make sure we don't run over the end
771
          int end = start + count;
772
          if(end > docs.size())
773
          {
774
              end = docs.size();
775
          }
776
          
777
          for(int i=start; i<end; i++)
778
          {
779
              //get the document from the result
780
              Document d = (Document)docs.get(i);
781
              //System.out.println("processing doc " + d.docid);
782
              
783
              String dateSMM = d.getField("dateSysMetadataModified");
784
              Date dateSysMetadataModified = null;
785
              if(dateSMM != null)
786
              {
787
                  try
788
                  {
789
                      dateSysMetadataModified = parseDate(dateSMM);
790
                  }
791
                  catch(Exception e)
792
                  { //if we fail to parse the date, just ignore the value
793
                      dateSysMetadataModified = null;
794
                  }
795
              }
796
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
797
                
798
              
799
              ObjectInfo info = new ObjectInfo();
800
              //add the fields to the info object
801
              Checksum cs = new Checksum();
802
              cs.setValue(d.getField("checksum"));
803
              String csalg = d.getField("algorithm");
804
              if(csalg == null)
805
              {
806
                  csalg = "MD5";
807
              }
808
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
809
              cs.setAlgorithm(ca);
810
              info.setChecksum(cs);
811
              info.setDateSysMetadataModified(dateSysMetadataModified);
812
              Identifier id = new Identifier();
813
              id.setValue(d.getField("identifier").trim());
814
              info.setIdentifier(id);
815
              info.setObjectFormat(returnedObjectFormat);
816
              String size = d.getField("size");
817
              if(size != null)
818
              {
819
                  info.setSize(new Long(size.trim()).longValue());
820
              }
821
              //add the ObjectInfo to the ObjectList
822
              //logCrud.info("objectFormat: " + info.getObjectFormat().toString());
823
              //logCrud.info("id: " + info.getIdentifier().getValue());
824
              
825
              if(info.getIdentifier().getValue() != null)
826
              { //id can be null from tests.  should not happen in production.
827
                  if((info.getObjectFormat() != null && !info.getObjectFormat().toString().trim().equals("")))
828
                  { //objectFormat needs to not be null and not be an empty string
829
                    ol.addObjectInfo(info);
830
                  }
831
                  else
832
                  {
833
                      logCrud.info("Not adding object with null objectFormat" + info.getIdentifier().getValue().toString());
834
                  }
835
              }
836
             
837
          }
838
      }
839
      catch(Exception e)
840
      {
841
          e.printStackTrace();
842
          logCrud.error("Error creating ObjectList: " + e.getMessage() + " cause: " + e.getCause());
843
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
844
      }
845
      String username = "public";
846
      if(sessionData != null)
847
      {
848
          username = sessionData.getUserName();
849
      }
850
      EventLog.getInstance().log(metacatUrl,
851
              username, null, "read");
852
      logCrud.info("listObjects");
853
      if(totalAfterQuery < count)
854
      {
855
          count = totalAfterQuery;
856
      }
857
      ol.setCount(count);
858
      ol.setStart(start);
859
      ol.setTotal(totalAfterQuery);
860
      return ol;
861
    }
862
    
863
    /**
864
     * Call listObjects with the default values for replicaStatus (true), start (0),
865
     * and count (1000).
866
     * @param token
867
     * @param startTime
868
     * @param endTime
869
     * @param objectFormat
870
     * @return
871
     * @throws NotAuthorized
872
     * @throws InvalidRequest
873
     * @throws NotImplemented
874
     * @throws ServiceFailure
875
     * @throws InvalidToken
876
     */
877
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
878
        ObjectFormat objectFormat)
879
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
880
    {
881
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
882
    }
883

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

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

    
924
            final InputStreamFromOutputStream<String> objectStream = 
925
                new InputStreamFromOutputStream<String>() {
926
                
927
                @Override
928
                public String produce(final OutputStream dataSink) throws Exception {
929

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

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

    
994
        } catch (McdbDocNotFoundException e) {
995
            throw new NotFound("1020", e.getMessage());
996
        } 
997
    }
998

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

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

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

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

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

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

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

    
1378
    /**
1379
     * insert a data doc
1380
     * @param object
1381
     * @param guid
1382
     * @param sessionData
1383
     * @throws ServiceFailure
1384
     * @returns localId of the data object inserted
1385
     */
1386
    private String insertDataObject(InputStream object, Identifier guid, 
1387
            SessionData sessionData) throws ServiceFailure {
1388
        
1389
        String username = "public";
1390
        String[] groups = null;
1391
        if(sessionData != null)
1392
        {
1393
          username = sessionData.getUserName();
1394
          groups = sessionData.getGroupNames();
1395
        }
1396

    
1397
        // generate guid/localId pair for object
1398
        logMetacat.debug("Generating a guid/localId mapping");
1399
        IdentifierManager im = IdentifierManager.getInstance();
1400
        String localId = im.generateLocalId(guid.getValue(), 1);
1401

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

    
1465
    /**
1466
     * write a file to a stream
1467
     * @param dir
1468
     * @param fileName
1469
     * @param data
1470
     * @return
1471
     * @throws ServiceFailure
1472
     */
1473
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1474
        throws ServiceFailure {
1475
        
1476
        File newFile = new File(dir, fileName);
1477
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1478

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

    
1500
        return newFile;
1501
    }
1502

    
1503
    /**
1504
     * insert a systemMetadata doc, return the localId of the sysmeta
1505
     */
1506
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1507
        throws ServiceFailure 
1508
    {
1509
        logMetacat.debug("Starting to insert SystemMetadata...");
1510
    
1511
        // generate guid/localId pair for sysmeta
1512
        Identifier sysMetaGuid = new Identifier();
1513
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1514
        sysmeta.setDateSysMetadataModified(new Date());
1515
        System.out.println("****inserting new system metadata with modified date " + 
1516
                sysmeta.getDateSysMetadataModified());
1517

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

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

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