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

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

    
302
        logMetacat.debug("Checking if identifier exists...");
303
        // Check that the identifier does not already exist
304
        IdentifierManager im = IdentifierManager.getInstance();
305
        if (im.identifierExists(guid.getValue())) {
306
            throw new IdentifierNotUnique("1120", 
307
                "GUID is already in use by an existing object.");
308
        }
309

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

    
331
        } else {
332
            // DEFAULT CASE: DATA (needs to be checked and completed)
333
            localId = insertDataObject(object, guid, sessionData);
334
            
335
        }
336

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

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

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

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

    
1037
    /**
1038
     * get the checksum for a document.  defaults to MD5.
1039
     */
1040
    public Checksum getChecksum(AuthToken token, Identifier guid)
1041
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1042
            InvalidRequest, NotImplemented 
1043
    {
1044
        logCrud.info("getChecksum");
1045
        return getChecksum(token, guid, "MD5");
1046
    }
1047

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

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

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

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

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

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

    
1435
        // generate guid/localId pair for object
1436
        logMetacat.debug("Generating a guid/localId mapping");
1437
        IdentifierManager im = IdentifierManager.getInstance();
1438
        String localId = im.generateLocalId(guid.getValue(), 1);
1439

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

    
1503
    /**
1504
     * write a file to a stream
1505
     * @param dir
1506
     * @param fileName
1507
     * @param data
1508
     * @return
1509
     * @throws ServiceFailure
1510
     */
1511
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1512
        throws ServiceFailure {
1513
        
1514
        File newFile = new File(dir, fileName);
1515
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1516

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

    
1538
        return newFile;
1539
    }
1540

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

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

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

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