Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: $'
7
 *     '$Date: 2009-06-13 15:28:13 +0300  $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23
package edu.ucsb.nceas.metacat.dataone;
24

    
25
import java.io.ByteArrayOutputStream;
26
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32
import java.io.PrintWriter;
33
import java.io.StringBufferInputStream;
34
import java.security.MessageDigest;
35
import java.sql.SQLException;
36
import java.util.*;
37
import java.text.DateFormat;
38
import java.text.SimpleDateFormat;
39

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
898
    /**
899
     * describe a document.  
900
     */
901
    public DescribeResponse describe(AuthToken token, Identifier guid)
902
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
903
            NotImplemented, InvalidRequest {
904
        logCrud.info("describe");
905
        
906
        if(token == null)
907
        {
908
            throw new InvalidToken("1370", "Authentication token is null");
909
        }
910
        
911
        if(guid == null || guid.getValue().trim().equals(""))
912
        {
913
            throw new InvalidRequest("1362", "Guid is null.  A valid guid is required.");
914
        }
915
        
916
        SystemMetadata sm = getSystemMetadata(token, guid);
917
        DescribeResponse dr = new DescribeResponse(sm.getObjectFormat(), 
918
                sm.getSize(), sm.getDateSysMetadataModified(), sm.getChecksum());
919
        return dr;
920
    }
921
    
922
    /**
923
     * get a document with a specified guid.
924
     */
925
    public InputStream get(AuthToken token, Identifier guid)
926
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
927
            NotImplemented {
928
        
929
        // Retrieve the session information from the AuthToken
930
        // If the session is expired, then the user is 'public'
931
        if(token == null)
932
        {
933
            token = new AuthToken("Public");
934
        }
935
        final SessionData sessionData = getSessionData(token);
936
        
937
        // Look up the localId for this global identifier
938
        IdentifierManager im = IdentifierManager.getInstance();
939
        try {
940
            final String localId = im.getLocalId(guid.getValue());
941

    
942
            final InputStreamFromOutputStream<String> objectStream = 
943
                new InputStreamFromOutputStream<String>() {
944
                
945
                @Override
946
                public String produce(final OutputStream dataSink) throws Exception {
947

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

    
997
                    return "Completed";
998
                }
999
            };
1000
            String username = "public";
1001
            if(sessionData != null)
1002
            {
1003
                username = sessionData.getUserName();
1004
            }
1005
            
1006
            EventLog.getInstance().log(metacatUrl,
1007
                    username, im.getLocalId(guid.getValue()), "read");
1008
            logCrud.info("get D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
1009
                    ":");
1010
            return objectStream;
1011

    
1012
        } catch (McdbDocNotFoundException e) {
1013
            throw new NotFound("1020", e.getMessage());
1014
        } 
1015
    }
1016

    
1017
    /**
1018
     * get the checksum for a document.  defaults to MD5.
1019
     */
1020
    public Checksum getChecksum(AuthToken token, Identifier guid)
1021
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1022
            InvalidRequest, NotImplemented 
1023
    {
1024
        logCrud.info("getChecksum");
1025
        return getChecksum(token, guid, "MD5");
1026
    }
1027

    
1028
    /**
1029
     * get the checksum for a document with the given algorithm
1030
     */
1031
    public Checksum getChecksum(AuthToken token, Identifier guid, 
1032
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
1033
            NotAuthorized, NotFound, InvalidRequest, NotImplemented 
1034
    {
1035
        logCrud.info("getChecksum");
1036
        if(checksumAlgorithm == null)
1037
        {
1038
            checksumAlgorithm = "MD5";
1039
        }
1040
        InputStream docStream = get(token, guid);
1041
        String checksum;
1042
        try
1043
        {
1044
            checksum = checksum(docStream, checksumAlgorithm);
1045
        }
1046
        catch(Exception e)
1047
        {
1048
            throw new ServiceFailure("1410", "Error getting checksum: " + e.getMessage());
1049
        }
1050
        Checksum c = new Checksum();
1051
        c.setAlgorithm(ChecksumAlgorithm.convert(checksumAlgorithm));
1052
        c.setValue(checksum);
1053
        return c;
1054
    }
1055

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

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

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

    
1345
    /*
1346
     * Look up the information on the session using the token provided in
1347
     * the AuthToken.  The Session should have all relevant user information.
1348
     * If the session has expired or is invalid, the 'public' session will
1349
     * be returned, giving the user anonymous access.
1350
     */
1351
    public static SessionData getSessionData(AuthToken token) {
1352
        SessionData sessionData = null;
1353
        String sessionId = "PUBLIC";
1354
        if (token != null) {
1355
            sessionId = token.getToken();
1356
        }
1357
        
1358
        // if the session id is registered in SessionService, get the
1359
        // SessionData for it. Otherwise, use the public session.
1360
        //System.out.println("sessionid: " + sessionId);
1361
        if (sessionId != null &&
1362
            !sessionId.toLowerCase().equals("public") &&
1363
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1364
        {
1365
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1366
        } else {
1367
            sessionData = SessionService.getInstance().getPublicSession();
1368
        }
1369
        
1370
        return sessionData;
1371
    }
1372

    
1373
    /** 
1374
     * Determine if a given object should be treated as an XML science metadata
1375
     * object. 
1376
     * 
1377
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1378
     * 
1379
     * @param sysmeta the SystemMetadata describig the object
1380
     * @return true if the object should be treated as science metadata
1381
     */
1382
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1383
        /*boolean scimeta = false;
1384
        //TODO: this should be read from a .properties file instead of being hard coded
1385
        switch (sysmeta.getObjectFormat()) {
1386
            case EML_2_1_0: scimeta = true; break;
1387
            case EML_2_0_1: scimeta = true; break;
1388
            case EML_2_0_0: scimeta = true; break;
1389
            case FGDC_STD_001_1_1999: scimeta = true; break;
1390
            case FGDC_STD_001_1998: scimeta = true; break;
1391
            case NCML_2_2: scimeta = true; break;
1392
            case DSPACE_METS_SIP_1_0: scimeta = true; break;
1393
        }
1394
        
1395
        return scimeta;*/
1396
        
1397
        return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
1398
    }
1399

    
1400
    /**
1401
     * insert a data doc
1402
     * @param object
1403
     * @param guid
1404
     * @param sessionData
1405
     * @throws ServiceFailure
1406
     * @returns localId of the data object inserted
1407
     */
1408
    private String insertDataObject(InputStream object, Identifier guid, 
1409
            SessionData sessionData) throws ServiceFailure {
1410
        
1411
        String username = "public";
1412
        String[] groups = null;
1413
        if(sessionData != null)
1414
        {
1415
          username = sessionData.getUserName();
1416
          groups = sessionData.getGroupNames();
1417
        }
1418

    
1419
        // generate guid/localId pair for object
1420
        logMetacat.debug("Generating a guid/localId mapping");
1421
        IdentifierManager im = IdentifierManager.getInstance();
1422
        String localId = im.generateLocalId(guid.getValue(), 1);
1423

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

    
1487
    /**
1488
     * write a file to a stream
1489
     * @param dir
1490
     * @param fileName
1491
     * @param data
1492
     * @return
1493
     * @throws ServiceFailure
1494
     */
1495
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1496
        throws ServiceFailure {
1497
        
1498
        File newFile = new File(dir, fileName);
1499
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1500

    
1501
        try {
1502
            if (newFile.createNewFile()) {
1503
                // write data stream to desired file
1504
                OutputStream os = new FileOutputStream(newFile);
1505
                long length = IOUtils.copyLarge(data, os);
1506
                os.flush();
1507
                os.close();
1508
            } else {
1509
                logMetacat.debug("File creation failed, or file already exists.");
1510
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1511
            }
1512
        } catch (FileNotFoundException e) {
1513
            logMetacat.debug("FNF: " + e.getMessage());
1514
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1515
                    + e.getMessage());
1516
        } catch (IOException e) {
1517
            logMetacat.debug("IOE: " + e.getMessage());
1518
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1519
                    + " " + e.getMessage());
1520
        }
1521

    
1522
        return newFile;
1523
    }
1524

    
1525
    /**
1526
     * insert a systemMetadata doc, return the localId of the sysmeta
1527
     */
1528
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1529
        throws ServiceFailure 
1530
    {
1531
        logMetacat.debug("Starting to insert SystemMetadata...");
1532
    
1533
        // generate guid/localId pair for sysmeta
1534
        Identifier sysMetaGuid = new Identifier();
1535
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1536
        sysmeta.setDateSysMetadataModified(new Date());
1537
        System.out.println("****inserting new system metadata with modified date " + 
1538
                sysmeta.getDateSysMetadataModified());
1539

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

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

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