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.FileInputStream;
28
import java.io.FileNotFoundException;
29
import java.io.FileOutputStream;
30
import java.io.IOException;
31
import java.io.InputStream;
32
import java.io.OutputStream;
33
import java.io.PrintWriter;
34
import java.io.StringBufferInputStream;
35
import java.security.MessageDigest;
36
import java.sql.SQLException;
37
import java.util.*;
38
import java.text.DateFormat;
39
import java.text.SimpleDateFormat;
40

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

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

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

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

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

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

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

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

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

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

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

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

    
316
        // Check if we are handling metadata or data
317
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
318
        
319
        if (isScienceMetadata) {
320
            // CASE METADATA:
321
            try {
322
                //System.out.println("CrudService: inserting document with guid " + guid.getValue());
323
                this.insertDocument(object, guid, sessionData);
324
                localId = im.getLocalId(guid.getValue());
325
            } catch (IOException e) {
326
                String msg = "Could not create string from XML stream: " +
327
                    " " + e.getMessage();
328
                logMetacat.debug(msg);
329
                throw new ServiceFailure("1190", msg);
330
            } catch(Exception e) {
331
                String msg = "Unexpected error in CrudService.create: " + e.getMessage();
332
                logMetacat.debug(msg);
333
                throw new ServiceFailure("1190", msg);
334
            }
335
            
336

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

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

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

    
900
    /**
901
     * Delete a document. 
902
     */
903
    public Identifier delete(AuthToken token, Identifier guid)
904
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
905
            NotImplemented, InvalidRequest {
906
        logCrud.info("delete");
907
        
908
        if(token == null || token.getToken().equals("publid"))
909
        {
910
            throw new NotAuthorized("1320", "You must be logged in to delete records.");
911
        }
912
        
913
        if(guid == null || guid.getValue().trim().equals(""))
914
        {
915
            throw new InvalidRequest("1322", "No GUID specified in CrudService.delete()");
916
        }
917
        final SessionData sessionData = getSessionData(token);
918
        IdentifierManager manager = IdentifierManager.getInstance();
919
        
920
        String docid;
921
        try
922
        {
923
            docid = manager.getLocalId(guid.getValue());
924
        }
925
        catch(McdbDocNotFoundException mnfe)
926
        {
927
            throw new InvalidRequest("1322", "GUID " + guid + " not found.");
928
        }
929
        
930
        try
931
        {
932
            DocumentImpl.delete(docid, sessionData.getUserName(), sessionData.getGroupNames(), null);
933
        }
934
        catch(Exception e)
935
        {
936
            throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
937
        }
938
        
939
        return guid;
940
    }
941

    
942
    /**
943
     * describe a document.  
944
     */
945
    public DescribeResponse describe(AuthToken token, Identifier guid)
946
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
947
            NotImplemented, InvalidRequest {
948
        logCrud.info("describe");
949
        
950
        if(token == null)
951
        {
952
            throw new InvalidToken("1370", "Authentication token is null");
953
        }
954
        
955
        if(guid == null || guid.getValue().trim().equals(""))
956
        {
957
            throw new InvalidRequest("1362", "Guid is null.  A valid guid is required.");
958
        }
959
        
960
        SystemMetadata sm = getSystemMetadata(token, guid);
961
        DescribeResponse dr = new DescribeResponse(sm.getObjectFormat(), 
962
                sm.getSize(), sm.getDateSysMetadataModified(), sm.getChecksum());
963
        return dr;
964
    }
965
    
966
    /**
967
     * get a document with a specified guid.
968
     */
969
    public InputStream get(AuthToken token, Identifier guid)
970
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
971
            NotImplemented {
972
        
973
        // Retrieve the session information from the AuthToken
974
        // If the session is expired, then the user is 'public'
975
        if(token == null)
976
        {
977
            token = new AuthToken("Public");
978
        }
979
        final SessionData sessionData = getSessionData(token);
980
        
981
        // Look up the localId for this global identifier
982
        IdentifierManager im = IdentifierManager.getInstance();
983
        
984
        try 
985
        {
986
            final String localId = im.getLocalId(guid.getValue());
987
            InputStream objectStream;
988
            try 
989
            {
990
                String username = "public";
991
                String[] groups = new String[0];
992
                if(sessionData != null)
993
                {
994
                    username = sessionData.getUserName();
995
                    groups = sessionData.getGroupNames();
996
                }
997
                
998
                objectStream = readFromMetacat(localId, username, groups);
999
                
1000
            } catch (PropertyNotFoundException e) {
1001
                e.printStackTrace();
1002
                throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
1003
            } catch (ClassNotFoundException e) {
1004
                e.printStackTrace();
1005
                throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
1006
            } catch (IOException e) {
1007
                e.printStackTrace();
1008
                throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
1009
            } catch (SQLException e) {
1010
                e.printStackTrace();
1011
                throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
1012
            } catch (McdbException e) {
1013
                e.printStackTrace();
1014
                throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
1015
            } catch (ParseLSIDException e) {
1016
                e.printStackTrace();
1017
                throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
1018
            } catch (InsufficientKarmaException e) {
1019
                e.printStackTrace();
1020
                throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
1021
            }
1022
        
1023
        
1024
            String username = "public";
1025
            if(sessionData != null)
1026
            {
1027
                username = sessionData.getUserName();
1028
            }
1029
            
1030
            EventLog.getInstance().log(metacatUrl,
1031
                    username, im.getLocalId(guid.getValue()), "read");
1032
            logCrud.info("get D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
1033
                    ":");
1034
            
1035
            return objectStream;
1036
        } 
1037
        catch (McdbDocNotFoundException e) 
1038
        {
1039
            throw new NotFound("1020", e.getMessage());
1040
        } 
1041
    }
1042

    
1043
    /**
1044
     * get the checksum for a document.  defaults to MD5.
1045
     */
1046
    public Checksum getChecksum(AuthToken token, Identifier guid)
1047
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1048
            InvalidRequest, NotImplemented 
1049
    {
1050
        logCrud.info("getChecksum");
1051
        return getChecksum(token, guid, "MD5");
1052
    }
1053

    
1054
    /**
1055
     * get the checksum for a document with the given algorithm
1056
     */
1057
    public Checksum getChecksum(AuthToken token, Identifier guid, 
1058
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
1059
            NotAuthorized, NotFound, InvalidRequest, NotImplemented 
1060
    {
1061
        logCrud.info("getChecksum");
1062
        SystemMetadata sm = getSystemMetadata(token, guid);
1063
        Checksum cs = sm.getChecksum();
1064
        if(cs.getAlgorithm().toString().equals(checksumAlgorithm))
1065
        {
1066
            return cs;
1067
        }
1068
        else
1069
        {
1070
            if(checksumAlgorithm == null)
1071
            {
1072
                checksumAlgorithm = "MD5";
1073
            }
1074
            InputStream docStream = get(token, guid);
1075
            String checksum;
1076
            try
1077
            {
1078
                checksum = checksum(docStream, checksumAlgorithm);
1079
            }
1080
            catch(Exception e)
1081
            {
1082
                throw new ServiceFailure("1410", "Error getting checksum: " + e.getMessage());
1083
            }
1084
            Checksum c = new Checksum();
1085
            c.setAlgorithm(ChecksumAlgorithm.convert(checksumAlgorithm));
1086
            c.setValue(checksum);
1087
            return c;
1088
        }
1089
    }
1090

    
1091
    /**
1092
     * get log records.  
1093
     */
1094
    public Log getLogRecords(AuthToken token, Date fromDate, Date toDate, Event event)
1095
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
1096
            NotImplemented 
1097
    {
1098
        /*System.out.println("=================== Getting log records ===================");
1099
        System.out.println("Current server time is: " + new Date());
1100
        if(fromDate != null)
1101
        {
1102
          System.out.println("query start time is " + fromDate);
1103
        }
1104
        if(toDate != null)
1105
        {
1106
          System.out.println("query end time is " + toDate);
1107
        }*/
1108
        Log log = new Log();
1109
        Vector<LogEntry> logs = new Vector<LogEntry>();
1110
        IdentifierManager im = IdentifierManager.getInstance();
1111
        EventLog el = EventLog.getInstance();
1112
        if(fromDate == null)
1113
        {
1114
            //System.out.println("setting fromdate from null");
1115
            fromDate = new Date(1);
1116
        }
1117
        if(toDate == null)
1118
        {
1119
            //System.out.println("setting todate from null");
1120
            toDate = new Date();
1121
        }
1122
        
1123
        //System.out.println("fromDate: " + fromDate);
1124
        //System.out.println("toDate: " + toDate);
1125
        
1126
        String report = el.getReport(null, null, null, null, 
1127
                new java.sql.Timestamp(fromDate.getTime()), 
1128
                new java.sql.Timestamp(toDate.getTime()));
1129
        
1130
        //System.out.println("report: " + report);
1131
        
1132
        String logEntry = "<logEntry>";
1133
        String endLogEntry = "</logEntry>";
1134
        int startIndex = 0;
1135
        int foundIndex = report.indexOf(logEntry, startIndex);
1136
        while(foundIndex != -1)
1137
        {
1138
            //parse out each entry
1139
            int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
1140
            String entry = report.substring(foundIndex, endEntryIndex);
1141
            //System.out.println("entry: " + entry);
1142
            startIndex = endEntryIndex + endLogEntry.length();
1143
            foundIndex = report.indexOf(logEntry, startIndex);
1144
            
1145
            String entryId = getLogEntryField("entryid", entry);
1146
            String ipAddress = getLogEntryField("ipAddress", entry);
1147
            String principal = getLogEntryField("principal", entry);
1148
            String docid = getLogEntryField("docid", entry);
1149
            String eventS = getLogEntryField("event", entry);
1150
            String dateLogged = getLogEntryField("dateLogged", entry);
1151
            
1152
            LogEntry le = new LogEntry();
1153
            
1154
            Event e = Event.convert(eventS);
1155
            if(e == null)
1156
            { //skip any events that are not Dataone Crud events
1157
                continue;
1158
            }
1159
            le.setEvent(e);
1160
            Identifier entryid = new Identifier();
1161
            entryid.setValue(entryId);
1162
            le.setEntryId(entryid);
1163
            Identifier identifier = new Identifier();
1164
            try
1165
            {
1166
                //System.out.println("converting docid '" + docid + "' to a guid.");
1167
                if(docid == null || docid.trim().equals("") || docid.trim().equals("null"))
1168
                {
1169
                    continue;
1170
                }
1171
                docid = docid.substring(0, docid.lastIndexOf("."));
1172
                identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
1173
            }
1174
            catch(Exception ex)
1175
            { //try to get the guid, if that doesn't work, just use the local id
1176
                //throw new ServiceFailure("1030", "Error getting guid for localId " + 
1177
                //        docid + ": " + ex.getMessage());\
1178
                
1179
                //skip it if the guid can't be found
1180
                continue;
1181
            }
1182
            
1183
            le.setIdentifier(identifier);
1184
            le.setIpAddress(ipAddress);
1185
            Calendar c = Calendar.getInstance();
1186
            String year = dateLogged.substring(0, 4);
1187
            String month = dateLogged.substring(5, 7);
1188
            String date = dateLogged.substring(8, 10);
1189
            //System.out.println("year: " + year + " month: " + month + " day: " + date);
1190
            c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
1191
            Date logDate = c.getTime();
1192
            le.setDateLogged(logDate);
1193
            NodeReference memberNode = new NodeReference();
1194
            memberNode.setValue(ipAddress);
1195
            le.setMemberNode(memberNode);
1196
            Principal princ = new Principal();
1197
            princ.setValue(principal);
1198
            le.setPrincipal(princ);
1199
            le.setUserAgent("metacat/RESTService");
1200
            
1201
            if(event == null)
1202
            {
1203
                logs.add(le);
1204
            }
1205
            
1206
            if(event != null &&
1207
               e.toString().toLowerCase().trim().equals(event.toString().toLowerCase().trim()))
1208
            {
1209
              logs.add(le);
1210
            }
1211
        }
1212
        
1213
        log.setLogEntryList(logs);
1214
        logCrud.info("getLogRecords");
1215
        return log;
1216
    }
1217
    
1218
    /**
1219
     * parse a logEntry and get the relavent field from it
1220
     * @param fieldname
1221
     * @param entry
1222
     * @return
1223
     */
1224
    private String getLogEntryField(String fieldname, String entry)
1225
    {
1226
        String begin = "<" + fieldname + ">";
1227
        String end = "</" + fieldname + ">";
1228
        //System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
1229
        String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
1230
        //System.out.println("entry " + fieldname + " : " + s);
1231
        return s;
1232
    }
1233

    
1234
    /**
1235
     * get the system metadata for a document with a specified guid.
1236
     */
1237
public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
1238
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1239
            InvalidRequest, NotImplemented {
1240
        
1241
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
1242
        
1243
        // Retrieve the session information from the AuthToken
1244
        // If the session is expired, then the user is 'public'
1245
        final SessionData sessionData = getSessionData(token);
1246
                
1247
        try {
1248
            IdentifierManager im = IdentifierManager.getInstance();
1249
            final String localId = im.getSystemMetadataLocalId(guid.getValue());
1250
            InputStream objectStream;
1251
            
1252
            try {
1253
                String username = "public";
1254
                String[] groupnames = null;
1255
                if(sessionData != null)
1256
                {
1257
                    username = sessionData.getUserName();
1258
                    groupnames = sessionData.getGroupNames();
1259
                }
1260
                
1261
                objectStream = readFromMetacat(localId, username, groupnames);
1262
                
1263
            } catch (PropertyNotFoundException e) {
1264
                e.printStackTrace();
1265
                throw new ServiceFailure("1090", "Property not found while reading system metadata from metacat: " + e.getMessage());
1266
            } catch (ClassNotFoundException e) {
1267
                e.printStackTrace();
1268
                throw new ServiceFailure("1090", "Class not found while reading system metadata from metacat: " + e.getMessage());
1269
            } catch (IOException e) {
1270
                e.printStackTrace();
1271
                throw new ServiceFailure("1090", "IOException while reading system metadata from metacat: " + e.getMessage());
1272
            } catch (SQLException e) {
1273
                e.printStackTrace();
1274
                throw new ServiceFailure("1090", "SQLException while reading system metadata from metacat: " + e.getMessage());
1275
            } catch (McdbException e) {
1276
                e.printStackTrace();
1277
                throw new ServiceFailure("1090", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
1278
            } catch (ParseLSIDException e) {
1279
                e.printStackTrace();
1280
                throw new NotFound("1060", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
1281
            } catch (InsufficientKarmaException e) {
1282
                e.printStackTrace();
1283
                throw new NotAuthorized("1040", "User not authorized for get() on system metadata: " + e.getMessage());
1284
            }
1285
                        
1286
            // Deserialize the xml to create a SystemMetadata object
1287
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
1288
            String username = "public";
1289
            if(sessionData != null)
1290
            {
1291
                username = sessionData.getUserName();
1292
            }
1293
            EventLog.getInstance().log(metacatUrl,
1294
                    username, im.getLocalId(guid.getValue()), "read");
1295
            logCrud.info("getsystemmetadata D1GUID:" + guid.getValue()  + 
1296
                    ":D1SYSMETADATA:"+ localId + ":");
1297
            return sysmeta;
1298
            
1299
        } catch (McdbDocNotFoundException e) {
1300
            //e.printStackTrace();
1301
            throw new NotFound("1040", e.getMessage());
1302
        }                
1303
    }
1304
    
1305
    /**
1306
     * parse the date in the systemMetadata
1307
     * @param s
1308
     * @return
1309
     * @throws Exception
1310
     */
1311
    public Date parseDate(String s)
1312
      throws Exception
1313
    {
1314
        /* TODO:
1315
         * This method should be replaced by a DateFormatter
1316
         */
1317
        Date d = null;
1318
        int tIndex = s.indexOf("T");
1319
        int zIndex = s.indexOf("Z");
1320
        if(tIndex != -1 && zIndex != -1)
1321
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
1322
            //System.out.println("original date: " + s);
1323
            
1324
            String date = s.substring(0, tIndex);
1325
            String year = date.substring(0, date.indexOf("-"));
1326
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
1327
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
1328
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
1329
                    " month: " + new Integer(month).intValue() + " day: " + 
1330
                    new Integer(day).intValue());
1331
            */
1332
            String time = s.substring(tIndex + 1, zIndex);
1333
            String hour = time.substring(0, time.indexOf(":"));
1334
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
1335
            String seconds = "00";
1336
            String milliseconds = "00";
1337
            if(time.indexOf(".") != -1)
1338
            {
1339
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
1340
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
1341
            }
1342
            else
1343
            {
1344
                seconds = time.substring(time.lastIndexOf(":") + 1, time.length());
1345
            }
1346
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
1347
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
1348
                    new Integer(seconds).intValue() + " milli: " + 
1349
                    new Integer(milliseconds).intValue());*/
1350
            
1351
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
1352
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0")/*TimeZone.getDefault()*/);
1353
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
1354
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
1355
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
1356
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
1357
            d = new Date(c.getTimeInMillis());
1358
            //System.out.println("d: " + d);
1359
            return d;
1360
        }
1361
        else
1362
        {  //if it's not in the expected format, try the formatter
1363
            return DateFormat.getDateTimeInstance().parse(s);
1364
        }
1365
    }
1366

    
1367
    /*
1368
     * Look up the information on the session using the token provided in
1369
     * the AuthToken.  The Session should have all relevant user information.
1370
     * If the session has expired or is invalid, the 'public' session will
1371
     * be returned, giving the user anonymous access.
1372
     */
1373
    public static SessionData getSessionData(AuthToken token) {
1374
        SessionData sessionData = null;
1375
        String sessionId = "PUBLIC";
1376
        if (token != null) {
1377
            sessionId = token.getToken();
1378
        }
1379
        
1380
        // if the session id is registered in SessionService, get the
1381
        // SessionData for it. Otherwise, use the public session.
1382
        //System.out.println("sessionid: " + sessionId);
1383
        if (sessionId != null &&
1384
            !sessionId.toLowerCase().equals("public") &&
1385
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1386
        {
1387
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1388
        } else {
1389
            sessionData = SessionService.getInstance().getPublicSession();
1390
        }
1391
        
1392
        return sessionData;
1393
    }
1394

    
1395
    /** 
1396
     * Determine if a given object should be treated as an XML science metadata
1397
     * object. 
1398
     * 
1399
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1400
     * 
1401
     * @param sysmeta the SystemMetadata describig the object
1402
     * @return true if the object should be treated as science metadata
1403
     */
1404
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1405
        /*boolean scimeta = false;
1406
        //TODO: this should be read from a .properties file instead of being hard coded
1407
        switch (sysmeta.getObjectFormat()) {
1408
            case EML_2_1_0: scimeta = true; break;
1409
            case EML_2_0_1: scimeta = true; break;
1410
            case EML_2_0_0: scimeta = true; break;
1411
            case FGDC_STD_001_1_1999: scimeta = true; break;
1412
            case FGDC_STD_001_1998: scimeta = true; break;
1413
            case NCML_2_2: scimeta = true; break;
1414
            case DSPACE_METS_SIP_1_0: scimeta = true; break;
1415
        }
1416
        
1417
        return scimeta;*/
1418
        
1419
        return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
1420
    }
1421

    
1422
    /**
1423
     * insert a data doc
1424
     * @param object
1425
     * @param guid
1426
     * @param sessionData
1427
     * @throws ServiceFailure
1428
     * @returns localId of the data object inserted
1429
     */
1430
    private String insertDataObject(InputStream object, Identifier guid, 
1431
            SessionData sessionData) throws ServiceFailure {
1432
        
1433
        String username = "public";
1434
        String[] groups = null;
1435
        if(sessionData != null)
1436
        {
1437
          username = sessionData.getUserName();
1438
          groups = sessionData.getGroupNames();
1439
        }
1440

    
1441
        // generate guid/localId pair for object
1442
        logMetacat.debug("Generating a guid/localId mapping");
1443
        IdentifierManager im = IdentifierManager.getInstance();
1444
        String localId = im.generateLocalId(guid.getValue(), 1);
1445

    
1446
        try {
1447
            logMetacat.debug("Case DATA: starting to write to disk.");
1448
            if (DocumentImpl.getDataFileLockGrant(localId)) {
1449
    
1450
                // Save the data file to disk using "localId" as the name
1451
                try {
1452
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
1453
    
1454
                    File dataDirectory = new File(datafilepath);
1455
                    dataDirectory.mkdirs();
1456
    
1457
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
1458
    
1459
                    // TODO: Check that the file size matches SystemMetadata
1460
                    //                        long size = newFile.length();
1461
                    //                        if (size == 0) {
1462
                    //                            throw new IOException("Uploaded file is 0 bytes!");
1463
                    //                        }
1464
    
1465
                    // Register the file in the database (which generates an exception
1466
                    // if the localId is not acceptable or other untoward things happen
1467
                    try {
1468
                        logMetacat.debug("Registering document...");
1469
                        DocumentImpl.registerDocument(localId, "BIN", localId,
1470
                                username, groups);
1471
                        logMetacat.debug("Registration step completed.");
1472
                    } catch (SQLException e) {
1473
                        //newFile.delete();
1474
                        logMetacat.debug("SQLE: " + e.getMessage());
1475
                        e.printStackTrace(System.out);
1476
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1477
                    } catch (AccessionNumberException e) {
1478
                        //newFile.delete();
1479
                        logMetacat.debug("ANE: " + e.getMessage());
1480
                        e.printStackTrace(System.out);
1481
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1482
                    } catch (Exception e) {
1483
                        //newFile.delete();
1484
                        logMetacat.debug("Exception: " + e.getMessage());
1485
                        e.printStackTrace(System.out);
1486
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1487
                    }
1488
    
1489
                    logMetacat.debug("Logging the creation event.");
1490
                    EventLog.getInstance().log(metacatUrl,
1491
                            username, localId, "create");
1492
    
1493
                    // Schedule replication for this data file
1494
                    logMetacat.debug("Scheduling replication.");
1495
                    ForceReplicationHandler frh = new ForceReplicationHandler(
1496
                            localId, "create", false, null);
1497
    
1498
                } catch (PropertyNotFoundException e) {
1499
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1500
                }
1501
            }
1502
            return localId;
1503
        } catch (Exception e) {
1504
            // Could not get a lock on the document, so we can not update the file now
1505
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1506
        }
1507
    }
1508

    
1509
    /**
1510
     * write a file to a stream
1511
     * @param dir
1512
     * @param fileName
1513
     * @param data
1514
     * @return
1515
     * @throws ServiceFailure
1516
     */
1517
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1518
        throws ServiceFailure {
1519
        
1520
        File newFile = new File(dir, fileName);
1521
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1522

    
1523
        try {
1524
            if (newFile.createNewFile()) {
1525
                // write data stream to desired file
1526
                OutputStream os = new FileOutputStream(newFile);
1527
                long length = IOUtils.copyLarge(data, os);
1528
                os.flush();
1529
                os.close();
1530
            } else {
1531
                logMetacat.debug("File creation failed, or file already exists.");
1532
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1533
            }
1534
        } catch (FileNotFoundException e) {
1535
            logMetacat.debug("FNF: " + e.getMessage());
1536
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1537
                    + e.getMessage());
1538
        } catch (IOException e) {
1539
            logMetacat.debug("IOE: " + e.getMessage());
1540
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1541
                    + " " + e.getMessage());
1542
        }
1543

    
1544
        return newFile;
1545
    }
1546

    
1547
    /**
1548
     * insert a systemMetadata doc, return the localId of the sysmeta
1549
     */
1550
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1551
        throws ServiceFailure 
1552
    {
1553
        logMetacat.debug("Starting to insert SystemMetadata...");
1554
    
1555
        // generate guid/localId pair for sysmeta
1556
        Identifier sysMetaGuid = new Identifier();
1557
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1558
        sysmeta.setDateSysMetadataModified(new Date());
1559
        System.out.println("****inserting new system metadata with modified date " + 
1560
                sysmeta.getDateSysMetadataModified());
1561

    
1562
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
1563
        System.out.println("sysmeta: " + xml);
1564
        String localId = insertDocument(xml, sysMetaGuid, sessionData, true);
1565
        System.out.println("sysmeta inserted with localId " + localId);
1566
        //insert the system metadata doc id into the systemmetadata table to 
1567
        //link it to the data or metadata document
1568
        IdentifierManager.getInstance().createSystemMetadataMapping(
1569
                sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
1570
        return localId;
1571
    }
1572
    
1573
    /**
1574
     * update a systemMetadata doc
1575
     */
1576
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1577
      throws ServiceFailure
1578
    {
1579
        try
1580
        {
1581
            String smId = IdentifierManager.getInstance().getSystemMetadataLocalId(sm.getIdentifier().getValue());
1582
            System.out.println("setting date modified to " + new Date());
1583
            sm.setDateSysMetadataModified(new Date());
1584
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
1585
            String localId = updateDocument(xml, sm.getIdentifier(), null, sessionData, true);
1586
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
1587
        }
1588
        catch(Exception e)
1589
        {
1590
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
1591
        }
1592
    }
1593
    
1594
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1595
        throws ServiceFailure
1596
    {
1597
        return insertDocument(xml, guid, sessionData, false);
1598
    }
1599
    
1600
    /**
1601
     * insert a document
1602
     * NOTE: this method shouldn't be used from the update or create() methods.  
1603
     * we shouldn't be putting the science metadata or data objects into memory.
1604
     */
1605
    private String insertDocument(String xml, Identifier guid, SessionData sessionData,
1606
            boolean isSystemMetadata)
1607
        throws ServiceFailure
1608
    {
1609
        return insertOrUpdateDocument(xml, guid, sessionData, "insert", isSystemMetadata);
1610
    }
1611
    
1612
    /**
1613
     * insert a document from a stream
1614
     */
1615
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1616
      throws IOException, ServiceFailure
1617
    {
1618
        //HACK: change this eventually.  we should not be converting the stream to a string
1619
        String xml = IOUtils.toString(is);
1620
        return insertDocument(xml, guid, sessionData);
1621
    }
1622
    
1623
    /**
1624
     * update a document
1625
     * NOTE: this method shouldn't be used from the update or create() methods.  
1626
     * we shouldn't be putting the science metadata or data objects into memory.
1627
     */
1628
    private String updateDocument(String xml, Identifier obsoleteGuid, 
1629
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1630
        throws ServiceFailure
1631
    {
1632
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update", isSystemMetadata);
1633
    }
1634
    
1635
    /**
1636
     * update a document from a stream
1637
     */
1638
    private String updateDocument(InputStream is, Identifier obsoleteGuid, 
1639
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1640
      throws IOException, ServiceFailure
1641
    {
1642
        //HACK: change this eventually.  we should not be converting the stream to a string
1643
        String xml = IOUtils.toString(is);
1644
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData, isSystemMetadata);
1645
        IdentifierManager im = IdentifierManager.getInstance();
1646
        if(guid != null)
1647
        {
1648
          im.createMapping(guid.getValue(), localId);
1649
        }
1650
        return localId;
1651
    }
1652
    
1653
    /**
1654
     * insert a document, return the id of the document that was inserted
1655
     */
1656
    protected String insertOrUpdateDocument(String xml, Identifier guid, 
1657
            SessionData sessionData, String insertOrUpdate, boolean isSystemMetadata) 
1658
        throws ServiceFailure {
1659
        logMetacat.debug("Starting to insert xml document...");
1660
        IdentifierManager im = IdentifierManager.getInstance();
1661

    
1662
        // generate guid/localId pair for sysmeta
1663
        String localId = null;
1664
        if(insertOrUpdate.equals("insert"))
1665
        {
1666
            localId = im.generateLocalId(guid.getValue(), 1, isSystemMetadata);
1667
        }
1668
        else
1669
        {
1670
            //localid should already exist in the identifier table, so just find it
1671
            try
1672
            {
1673
                System.out.println("updating guid " + guid.getValue());
1674
                if(!isSystemMetadata)
1675
                {
1676
                    System.out.println("looking in identifier table for guid " + guid.getValue());
1677
                    localId = im.getLocalId(guid.getValue());
1678
                }
1679
                else
1680
                {
1681
                    System.out.println("looking in systemmetadata table for guid " + guid.getValue());
1682
                    localId = im.getSystemMetadataLocalId(guid.getValue());
1683
                }
1684
                System.out.println("localId: " + localId);
1685
                //increment the revision
1686
                String docid = localId.substring(0, localId.lastIndexOf("."));
1687
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1688
                int rev = new Integer(revS).intValue();
1689
                rev++;
1690
                docid = docid + "." + rev;
1691
                localId = docid;
1692
                System.out.println("incremented localId: " + localId);
1693
            }
1694
            catch(McdbDocNotFoundException e)
1695
            {
1696
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1697
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1698
            }
1699
        }
1700
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1701
                localId);
1702

    
1703
        String[] action = new String[1];
1704
        action[0] = insertOrUpdate;
1705
        params.put("action", action);
1706
        String[] docid = new String[1];
1707
        docid[0] = localId;
1708
        params.put("docid", docid);
1709
        String[] doctext = new String[1];
1710
        doctext[0] = xml;
1711
        logMetacat.debug(doctext[0]);
1712
        params.put("doctext", doctext);
1713
        
1714
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1715
        // onto output stream, or alternatively, capture that and parse it to 
1716
        // generate the right exceptions
1717
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1718
        //PrintWriter pw = new PrintWriter(output);
1719
        String username = "public";
1720
        String[] groupnames = null;
1721
        if(sessionData != null)
1722
        {
1723
            username = sessionData.getUserName();
1724
            groupnames = sessionData.getGroupNames();
1725
        }
1726
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1727
                            null, params, username, groupnames);
1728
        if(result.indexOf("<error>") != -1)
1729
        {
1730
            throw new ServiceFailure("1000", "Error inserting or updating document: " + result);
1731
        }
1732
        //String outputS = new String(output.toByteArray());
1733
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1734
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1735
        return localId;
1736
    }
1737
    
1738
    /**
1739
     * serialize a dataone type
1740
     */
1741
    private void serializeServiceType(Class type, Object object, OutputStream out)
1742
        throws JiBXException
1743
    {
1744
        IBindingFactory bfact = BindingDirectory.getFactory(type);
1745
        IMarshallingContext mctx = bfact.createMarshallingContext();
1746
        mctx.marshalDocument(object, "UTF-8", null, out);
1747
    }
1748
    
1749
    /**
1750
     * serialize a system metadata doc
1751
     * @param sysmeta
1752
     * @return
1753
     * @throws ServiceFailure
1754
     */
1755
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1756
        throws ServiceFailure {
1757
        IBindingFactory bfact;
1758
        ByteArrayOutputStream sysmetaOut = null;
1759
        try {
1760
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1761
            IMarshallingContext mctx = bfact.createMarshallingContext();
1762
            sysmetaOut = new ByteArrayOutputStream();
1763
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1764
        } catch (JiBXException e) {
1765
            e.printStackTrace();
1766
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1767
        }
1768
        
1769
        return sysmetaOut;
1770
    }
1771
    
1772
    /**
1773
     * deserialize a system metadata doc
1774
     * @param xml
1775
     * @return
1776
     * @throws ServiceFailure
1777
     */
1778
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1779
        throws ServiceFailure {
1780
        try {
1781
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1782
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1783
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1784
            return sysmeta;
1785
        } catch (JiBXException e) {
1786
            e.printStackTrace();
1787
            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1788
        }    
1789
    }
1790
    
1791
    /**
1792
     * read a document from metacat and return the InputStream
1793
     * 
1794
     * @param localId
1795
     * @param username
1796
     * @param groups
1797
     * @return
1798
     * @throws InsufficientKarmaException
1799
     * @throws ParseLSIDException
1800
     * @throws PropertyNotFoundException
1801
     * @throws McdbException
1802
     * @throws SQLException
1803
     * @throws ClassNotFoundException
1804
     * @throws IOException
1805
     */
1806
    private InputStream readFromMetacat(String localId, String username, String[] groups)
1807
        throws InsufficientKarmaException, ParseLSIDException,
1808
        PropertyNotFoundException, McdbException, SQLException, 
1809
        ClassNotFoundException, IOException
1810
    {
1811
        File tmpDir;
1812
        try
1813
        {
1814
            tmpDir = new File(PropertyService.getProperty("application.tempDir"));
1815
        }
1816
        catch(PropertyNotFoundException pnfe)
1817
        {
1818
            logMetacat.error("ResourceHandler.writeMMPPartstoFiles: " +
1819
                    "application.tmpDir not found.  Using /tmp instead.");
1820
            tmpDir = new File("/tmp");
1821
        }
1822
        Date d = new Date();
1823
        final File outputFile = new File(tmpDir, "metacat.output." + d.getTime());
1824
        FileOutputStream dataSink = new FileOutputStream(outputFile);
1825
        
1826
        handler.readFromMetacat(metacatUrl, null, 
1827
                dataSink, localId, "xml",
1828
                username, 
1829
                groups, true, params);
1830
        
1831
        //set a timer to clean up the temp files
1832
        Timer t = new Timer();
1833
        TimerTask tt = new TimerTask() {
1834
            @Override
1835
            public void run()
1836
            {
1837
                outputFile.delete();
1838
            }
1839
        };
1840
        t.schedule(tt, 20000); //schedule after 20 secs
1841
        
1842
        InputStream objectStream = new FileInputStream(outputFile);
1843
        return objectStream;
1844
    }
1845
    
1846
    /**
1847
     * return an MD5 checksum for the stream
1848
     * @param is
1849
     * @return
1850
     */
1851
    private String checksum(InputStream is)
1852
        throws Exception
1853
    {
1854
        return checksum(is, "MD5");
1855
    }
1856
    
1857
    /**
1858
     * produce a checksum for item using the given algorithm
1859
     */
1860
    private String checksum(InputStream is, String algorithm)
1861
      throws Exception
1862
    {        
1863
        byte[] buffer = new byte[1024];
1864
        MessageDigest complete = MessageDigest.getInstance(algorithm);
1865
        int numRead;
1866
        
1867
        do 
1868
        {
1869
          numRead = is.read(buffer);
1870
          if (numRead > 0) 
1871
          {
1872
            complete.update(buffer, 0, numRead);
1873
          }
1874
        } while (numRead != -1);
1875
        
1876
        
1877
        return getHex(complete.digest());
1878
    }
1879
    
1880
    /**
1881
     * convert a byte array to a hex string
1882
     */
1883
    private static String getHex( byte [] raw ) 
1884
    {
1885
        final String HEXES = "0123456789ABCDEF";
1886
        if ( raw == null ) {
1887
          return null;
1888
        }
1889
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
1890
        for ( final byte b : raw ) {
1891
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
1892
             .append(HEXES.charAt((b & 0x0F)));
1893
        }
1894
        return hex.toString();
1895
    }
1896
    
1897
    /**
1898
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
1899
     * a proper date object
1900
     * @param date
1901
     * @return
1902
     */
1903
    private Date parseMetacatDate(String date)
1904
    {
1905
        String year = date.substring(0, 4);
1906
        String month = date.substring(5, 7);
1907
        String day = date.substring(8, 10);
1908
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
1909
        c.set(new Integer(year).intValue(), 
1910
              new Integer(month).intValue(), 
1911
              new Integer(day).intValue());
1912
        System.out.println("time in parseMetacatDate: " + c.getTime());
1913
        return c.getTime();
1914
    }
1915
    
1916
    /**
1917
     * find the size (in bytes) of a stream
1918
     * @param is
1919
     * @return
1920
     * @throws IOException
1921
     */
1922
    private long sizeOfStream(InputStream is)
1923
        throws IOException
1924
    {
1925
        long size = 0;
1926
        byte[] b = new byte[1024];
1927
        int numread = is.read(b, 0, 1024);
1928
        while(numread != -1)
1929
        {
1930
            size += numread;
1931
            numread = is.read(b, 0, 1024);
1932
        }
1933
        return size;
1934
    }
1935
    
1936
    /**
1937
     * create system metadata with a specified id, doc and format
1938
     */
1939
    private SystemMetadata createSystemMetadata(String localId, AuthToken token)
1940
      throws Exception
1941
    {
1942
        IdentifierManager im = IdentifierManager.getInstance();
1943
        Hashtable<String, Object> docInfo = im.getDocumentInfo(localId);
1944
        
1945
        //get the document text
1946
        int rev = im.getLatestRevForLocalId(localId);
1947
        Identifier identifier = new Identifier();
1948
        identifier.setValue(im.getGUID(localId, rev));
1949
        InputStream is = this.get(token, identifier);
1950
        
1951
        SystemMetadata sm = new SystemMetadata();
1952
        //set the id
1953
        sm.setIdentifier(identifier);
1954
        
1955
        //set the object format
1956
        String doctype = (String)docInfo.get("doctype");
1957
        ObjectFormat format = ObjectFormat.convert((String)docInfo.get("doctype"));
1958
        if(format == null)
1959
        {
1960
            if(doctype.trim().equals("BIN"))
1961
            {
1962
                format = ObjectFormat.OCTET_STREAM;
1963
            }
1964
            else
1965
            {
1966
                format = ObjectFormat.convert("text/plain");
1967
            }
1968
        }
1969
        sm.setObjectFormat(format);
1970
        
1971
        //create the checksum
1972
        String checksumS = checksum(is);
1973
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
1974
        Checksum checksum = new Checksum();
1975
        checksum.setValue(checksumS);
1976
        checksum.setAlgorithm(ca);
1977
        sm.setChecksum(checksum);
1978
        
1979
        //set the size
1980
        is = this.get(token, identifier);
1981
        sm.setSize(sizeOfStream(is));
1982
        
1983
        //submitter
1984
        Principal p = new Principal();
1985
        p.setValue((String)docInfo.get("user_owner"));
1986
        sm.setSubmitter(p);
1987
        sm.setRightsHolder(p);
1988
        try
1989
        {
1990
            Date dateCreated = parseMetacatDate((String)docInfo.get("date_created"));
1991
            sm.setDateUploaded(dateCreated);
1992
            Date dateUpdated = parseMetacatDate((String)docInfo.get("date_updated"));
1993
            sm.setDateSysMetadataModified(dateUpdated);
1994
        }
1995
        catch(Exception e)
1996
        {
1997
            System.out.println("POSSIBLE ERROR: couldn't parse a date: " + e.getMessage());
1998
            Date dateCreated = new Date();
1999
            sm.setDateUploaded(dateCreated);
2000
            Date dateUpdated = new Date();
2001
            sm.setDateSysMetadataModified(dateUpdated);
2002
        }
2003
        NodeReference nr = new NodeReference();
2004
        //TODO: this should be set to be something more meaningful once the registry is up
2005
        nr.setValue("metacat");
2006
        sm.setOriginMemberNode(nr);
2007
        sm.setAuthoritativeMemberNode(nr);
2008
        return sm;
2009
    }
2010
}
(1-1/3)