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.ByteArrayInputStream;
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.security.NoSuchAlgorithmException;
34
import java.sql.SQLException;
35
import java.text.DateFormat;
36
import java.util.Calendar;
37
import java.util.Date;
38
import java.util.Enumeration;
39
import java.util.Hashtable;
40
import java.util.List;
41
import java.util.TimeZone;
42
import java.util.Timer;
43
import java.util.TimerTask;
44
import java.util.Vector;
45

    
46
import javax.servlet.http.HttpServletRequest;
47

    
48
import org.apache.commons.io.IOUtils;
49
import org.apache.log4j.Logger;
50
import org.dataone.service.exceptions.IdentifierNotUnique;
51
import org.dataone.service.exceptions.InsufficientResources;
52
import org.dataone.service.exceptions.InvalidRequest;
53
import org.dataone.service.exceptions.InvalidSystemMetadata;
54
import org.dataone.service.exceptions.InvalidToken;
55
import org.dataone.service.exceptions.NotAuthorized;
56
import org.dataone.service.exceptions.NotFound;
57
import org.dataone.service.exceptions.NotImplemented;
58
import org.dataone.service.exceptions.ServiceFailure;
59
import org.dataone.service.exceptions.UnsupportedType;
60
import org.dataone.service.mn.MemberNodeCrud;
61
import org.dataone.service.types.AuthToken;
62
import org.dataone.service.types.Checksum;
63
import org.dataone.service.types.ChecksumAlgorithm;
64
import org.dataone.service.types.DescribeResponse;
65
import org.dataone.service.types.Event;
66
import org.dataone.service.types.Identifier;
67
import org.dataone.service.types.Log;
68
import org.dataone.service.types.LogEntry;
69
import org.dataone.service.types.NodeReference;
70
import org.dataone.service.types.ObjectFormat;
71
import org.dataone.service.types.ObjectList;
72
import org.dataone.service.types.Subject;
73
import org.dataone.service.types.SystemMetadata;
74
import org.dataone.service.types.util.ServiceTypeUtil;
75

    
76
import edu.ucsb.nceas.metacat.AccessionNumberException;
77
import edu.ucsb.nceas.metacat.DocumentImpl;
78
import edu.ucsb.nceas.metacat.EventLog;
79
import edu.ucsb.nceas.metacat.IdentifierManager;
80
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
81
import edu.ucsb.nceas.metacat.McdbException;
82
import edu.ucsb.nceas.metacat.MetacatHandler;
83
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
84
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
85
import edu.ucsb.nceas.metacat.properties.PropertyService;
86
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
87
import edu.ucsb.nceas.metacat.service.SessionService;
88
import edu.ucsb.nceas.metacat.util.DocumentUtil;
89
import edu.ucsb.nceas.metacat.util.SessionData;
90
import edu.ucsb.nceas.utilities.ParseLSIDException;
91
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
92

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

    
103
    private MetacatHandler handler;
104
    private Hashtable<String, String[]> params;
105
    private Logger logMetacat = null;
106
    private Logger logCrud = null;
107
    
108
    private String metacatUrl;
109
    
110
    /**
111
     * singleton accessor
112
     */
113
    public static CrudService getInstance() 
114
    {
115
      if(crudService == null)
116
      {
117
        crudService = new CrudService();
118
      }
119
      
120
      return crudService;
121
    }
122
    
123
    /**
124
     * Constructor, private for singleton access
125
     */
126
    private CrudService() {
127
        logMetacat = Logger.getLogger(CrudService.class);
128
        logCrud = Logger.getLogger("DataOneLogger");
129
        try
130
        {
131
            String server = PropertyService.getProperty("server.name");
132
            String port = PropertyService.getProperty("server.httpPort");
133
            String context = PropertyService.getProperty("application.context");
134
            metacatUrl = "http://" + server + ":" + port + "/" + context + "/d1";
135
            logMetacat.debug("Initializing CrudService with url " + metacatUrl);
136
        }
137
        catch(Exception e)
138
        {
139
            logMetacat.error("Could not find servlet url in CrudService: " + e.getMessage());
140
            e.printStackTrace();
141
            throw new RuntimeException("Error getting servlet url in CrudService: " + e.getMessage());
142
        }
143
        
144
        params = new Hashtable<String, String[]>();
145
        handler = new MetacatHandler(new Timer());
146
    }
147
    
148
    /**
149
     * return the context url CrudService is using.
150
     */
151
    public String getContextUrl()
152
    {
153
        return metacatUrl;
154
    }
155
    
156
    /**
157
     * Set the context url that this service uses.  It is normally not necessary
158
     * to call this method unless you are trying to connect to a server other
159
     * than the one in which this service is installed.  Otherwise, this value is
160
     * taken from the metacat.properties file (server.name, server.port, application.context).
161
     */
162
    public void setContextUrl(String url)
163
    {
164
        metacatUrl = url;
165
    }
166
    
167
    /**
168
     * set the params for this service from an HttpServletRequest param list
169
     */
170
    public void setParamsFromRequest(HttpServletRequest request)
171
    {
172
        @SuppressWarnings("unchecked")
173
        Enumeration<String> paramlist = request.getParameterNames();
174
        while (paramlist.hasMoreElements()) {
175
            String name = (String) paramlist.nextElement();
176
            String[] value = (String[])request.getParameterValues(name);
177
            params.put(name, value);
178
        }
179
    }
180
    
181
    /**
182
     * Authenticate against metacat and get a token.
183
     * @param username
184
     * @param password
185
     * @return
186
     * @throws ServiceFailure
187
     */
188
    public AuthToken authenticate(String username, String password)
189
      throws ServiceFailure
190
    {
191
        /* TODO:
192
         * This method is not in the original D1 crud spec.  It is highly
193
         * metacat centric.  Higher level decisions need to be made on authentication
194
         * interfaces for D1 nodes.
195
         */
196
        try
197
        {
198
            MetacatRestClient restClient = new MetacatRestClient(getContextUrl());   
199
            String response = restClient.login(username, password);
200
            String sessionid = restClient.getSessionId();
201
            SessionService sessionService = SessionService.getInstance();
202
            sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
203
            AuthToken token = new AuthToken(sessionid);
204
            EventLog.getInstance().log(metacatUrl,
205
                    username, null, "authenticate");
206
            logCrud.info("authenticate");
207
            return token;
208
        }
209
        catch(Exception e)
210
        {
211
            throw new ServiceFailure("1620", "Error authenticating with metacat: " + e.getMessage());
212
        }
213
    }
214
    
215
    /**
216
     * set the parameter values needed for this request
217
     */
218
    public void setParameter(String name, String[] value)
219
    {
220
        params.put(name, value);
221
    }
222
    
223

    
224
    
225
    
226
    
227
    /**
228
     * create an object via the crud interface
229
     */
230
    public Identifier create(AuthToken token, Identifier guid, 
231
            InputStream object, SystemMetadata sysmeta) throws InvalidToken, 
232
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
233
            InsufficientResources, InvalidSystemMetadata, NotImplemented {
234
        logMetacat.debug("Starting CrudService.create()...");
235
        
236
        // authenticate & get user info
237
        SessionData sessionData = getSessionData(token);
238
        String username = "public";
239
        String[] groups = null;
240
        if(sessionData != null)
241
        {
242
            username = sessionData.getUserName();
243
            groups = sessionData.getGroupNames();
244
        }
245
        String localId = null;
246

    
247
        if (username == null || username.equals("public"))
248
        {
249
            //TODO: many of the thrown exceptions do not use the correct error codes
250
            //check these against the docs and correct them
251
            throw new NotAuthorized("1100", "User " + username + " is not authorized to create content." +
252
                    "  If you are not logged in, please do so and retry the request.");
253
        }
254
        
255
        // verify that guid == SystemMetadata.getIdentifier()
256
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
257
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
258
            throw new InvalidSystemMetadata("1180", 
259
                "GUID in method call (" + guid.getValue() + ") does not match GUID in system metadata (" +
260
                sysmeta.getIdentifier().getValue() + ").");
261
        }
262

    
263
        logMetacat.debug("Checking if identifier exists...");
264
        // Check that the identifier does not already exist
265
        IdentifierManager im = IdentifierManager.getInstance();
266
        if (im.identifierExists(guid.getValue())) {
267
            throw new IdentifierNotUnique("1120", 
268
                "GUID is already in use by an existing object.");
269
        }
270

    
271
        // Check if we are handling metadata or data
272
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
273
        
274
        if (isScienceMetadata) {
275
            // CASE METADATA:
276
            try {
277
                //logCrud.debug("CrudService: inserting document with guid " + guid.getValue());
278
                this.insertDocument(object, guid, sessionData);
279
                localId = im.getLocalId(guid.getValue());
280
            } catch (IOException e) {
281
                String msg = "Could not create string from XML stream: " +
282
                    " " + e.getMessage();
283
                logMetacat.debug(msg);
284
                throw new ServiceFailure("1190", msg);
285
            } catch(Exception e) {
286
                String msg = "Unexpected error in CrudService.create: " + e.getMessage();
287
                logMetacat.debug(msg);
288
                throw new ServiceFailure("1190", msg);
289
            }
290
            
291

    
292
        } else {
293
            // DEFAULT CASE: DATA (needs to be checked and completed)
294
            localId = insertDataObject(object, guid, sessionData);
295
            
296
        }
297

    
298
        // For Metadata and Data, insert the system metadata into the object store too
299
        insertSystemMetadata(sysmeta, sessionData);
300
        //get the document info.  add any access params for the sysmeta too
301
        //logCrud.debug("looking for access records to add for system " +
302
        //    "metadata who's parent doc's  local id is " + localId);
303
        try
304
        {
305
            Hashtable<String, Object> h = im.getDocumentInfo(localId.substring(0, localId.lastIndexOf(".")));
306
            Vector v = (Vector)h.get("access");
307
            for(int i=0; i<v.size(); i++)
308
            {
309
                @SuppressWarnings("unchecked")
310
                Hashtable<String, String> ah = (Hashtable<String, String>)v.elementAt(i);
311
                String principal = (String)ah.get("principal_name");
312
                String permission = (String)ah.get("permission");
313
                String permissionType = (String)ah.get("permission_type");
314
                String permissionOrder = (String)ah.get("permission_order");
315
                int perm = new Integer(permission).intValue();
316
                //logCrud.debug("found access record for principal " + principal);
317
                //logCrud.debug("permission: " + perm + " perm_type: " + permissionType + 
318
                //    " perm_order: " + permissionOrder);
319
                this.setAccess(token, guid, principal, perm, permissionType, permissionOrder, true);
320
            }
321
        }
322
        catch(Exception e)
323
        {
324
            logMetacat.error("Error setting permissions on System Metadata object: " +
325
            		e.getMessage());
326
            //TODO: decide if this error should cancel the entire create or
327
            //if it should continue with just a logged error.
328
        }
329
        
330
        
331
        logMetacat.debug("Returning from CrudService.create()");
332
        EventLog.getInstance().log(metacatUrl,
333
                username, localId, "create");
334
        logCrud.info("create D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId);
335
        return guid;
336
    }
337
    
338
    /**
339
     * update an existing object with a new object.  Change the system metadata
340
     * to reflect the changes and update it as well.
341
     */
342
    public Identifier update(AuthToken token, Identifier guid, 
343
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
344
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
345
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
346
            NotImplemented {
347
    	try
348
    	{
349
    		SessionData sessionData = getSessionData(token);
350
            
351
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
352
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
353
            //change sm.old's obsoletedBy field 
354
            List<Identifier> l = sm.getObsoletedByList();
355
            l.add(guid);
356
            sm.setObsoletedByList(l);
357
            //update sm.old
358
            updateSystemMetadata(sm, sessionData);
359
            
360
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
361
            sysmeta.addObsolete(obsoletedGuid);
362
            //insert sm.new
363
            insertSystemMetadata(sysmeta, sessionData);
364
            String localId;
365
            
366
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
367
            if(isScienceMetadata)
368
            {
369
                //update the doc
370
                localId = updateDocument(object, obsoletedGuid, guid, sessionData, false);
371
            }
372
            else
373
            {
374
                //update a data file, not xml
375
                localId = insertDataObject(object, guid, sessionData);
376
            }
377
            
378
            IdentifierManager im = IdentifierManager.getInstance();
379
            String username = "public";
380
            if(sessionData != null)
381
            {
382
                username = sessionData.getUserName();
383
            }
384
            EventLog.getInstance().log(metacatUrl,
385
                    username, im.getLocalId(guid.getValue()), "update");
386
            logCrud.info("update D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId);
387
            return guid;
388
        }
389

    
390
    	catch(IOException e) {
391
            throw new ServiceFailure("1310", "Error updating document in CrudService: " + e.getMessage());
392
        }
393
    	catch( McdbDocNotFoundException e) {
394
    		throw new ServiceFailure("1310", "Error updating document in CrudService: " + e.getMessage());
395
    	}
396
    	catch( InvalidRequest e) {
397
    		throw new ServiceFailure("1310", "Error updating document in CrudService: " + e.getMessage());
398
    	}
399
    }
400
    
401
    /**
402
     * set access permissions on both the science metadata and system metadata
403
     */
404
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
405
            String permissionType, String permissionOrder)
406
      throws ServiceFailure
407
    {
408
        setAccess(token, id, principal, permission, permissionType, permissionOrder, true);
409
    }
410
    
411
    /**
412
     * set access control on the doc
413
     * @param token
414
     * @param id
415
     * @param principal
416
     * @param permission
417
     */
418
    public void setAccess(AuthToken token, Identifier id, String principal, int permission,
419
      String permissionType, String permissionOrder, boolean setSystemMetadata)
420
      throws ServiceFailure
421
    {
422
        String perm = "";
423
        if(permission >= 4)
424
        {
425
            perm = "read";
426
        }
427
        if(permission >= 6)
428
        {
429
            perm = "write";
430
        }
431
        //logCrud.debug("perm in setAccess: " + perm);
432
        //logCrud.debug("permission in setAccess: " + permission);
433
        setAccess(token, id, principal, perm, permissionType, permissionOrder,
434
                setSystemMetadata);
435
       
436
    }
437
    
438
    /**
439
     * set the permission on the document
440
     * @param token
441
     * @param principal
442
     * @param permission
443
     * @param permissionType
444
     * @param permissionOrder
445
     * @return
446
     */
447
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
448
            String permissionType, String permissionOrder, boolean setSystemMetadata)
449
      throws ServiceFailure
450
    {
451
        /* TODO:
452
         * This is also not part of the D1 Crud spec.  This method is needed for
453
         * systems such as metacat where access to objects is controlled by
454
         * and ACL.  Higher level decisions need to be made about how this
455
         * should work within D1.
456
         */
457
        try
458
        {
459
            final SessionData sessionData = getSessionData(token);
460
            if(sessionData == null)
461
            {
462
                throw new ServiceFailure("1000", "User must be logged in to set access.");
463
            }
464
            IdentifierManager im = IdentifierManager.getInstance();
465
            String docid = im.getLocalId(id.getValue());
466
        
467
            String permNum = "0";
468
            if(permission.equals("read"))
469
            {
470
                permNum = "4";
471
            }
472
            else if(permission.equals("write"))
473
            {
474
                permNum = "6";
475
            }
476
            logCrud.debug("user " + sessionData.getUserName() + 
477
                    " is setting access level " + permNum + " for permission " + 
478
                    permissionType + " on doc with localid " + docid);
479
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
480
                    principal, permNum, permissionType, permissionOrder);
481
            if(setSystemMetadata)
482
            {
483
                //set the same perms on the system metadata doc
484
                String smlocalid = im.getSystemMetadataLocalId(id.getValue());
485
                logCrud.debug("setting access on SM doc with localid " + smlocalid);
486
                //cs.setAccess(token, smid, principal, permission, permissionType, permissionOrder);
487
                handler.setAccess(metacatUrl, sessionData.getUserName(), smlocalid,
488
                        principal, permNum, permissionType, permissionOrder);
489
            }
490
            String username = "public";
491
            if(sessionData != null)
492
            {
493
                username = sessionData.getUserName();
494
            }
495
            EventLog.getInstance().log(metacatUrl,
496
                    username, im.getLocalId(id.getValue()), "setAccess");
497
            logCrud.info("setAccess");
498
        }
499
        catch(Exception e)
500
        {
501
            e.printStackTrace();
502
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
503
        }
504
    }
505
    
506
    /**
507
     *  Retrieve the list of objects present on the MN that match the calling 
508
     *  parameters. This method is required to support the process of Member 
509
     *  Node synchronization. At a minimum, this method should be able to 
510
     *  return a list of objects that match:
511
     *  startTime <= SystemMetadata.dateSysMetadataModified
512
     *  but is expected to also support date range (by also specifying endTime), 
513
     *  and should also support slicing of the matching set of records by 
514
     *  indicating the starting index of the response (where 0 is the index 
515
     *  of the first item) and the count of elements to be returned.
516
     *  
517
     *  If startTime or endTime is null, the query is not restricted by that parameter.
518
     *  
519
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
520
     * @param token
521
     * @param startTime
522
     * @param endTime
523
     * @param objectFormat
524
     * @param replicaStatus
525
     * @param start
526
     * @param count
527
     * @return ObjectList
528
     * @throws NotAuthorized
529
     * @throws InvalidRequest
530
     * @throws NotImplemented
531
     * @throws ServiceFailure
532
     * @throws InvalidToken
533
     */
534
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
535
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
536
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
537
    {
538
      //ObjectList ol = new ObjectList();
539
      //final SessionData sessionData = getSessionData(token);
540
      //int totalAfterQuery = 0;
541
      
542
      
543
      return IdentifierManager.getInstance().querySystemMetadata(startTime, endTime,
544
              objectFormat, replicaStatus, start, count);
545
      
546
      
547
      /////////////////////////////////////////////////////////////////////////
548
      ///////////////// OLD CODE //////////////////////////////////////////////
549
      /////////////////////////////////////////////////////////////////////////
550
      
551
//      try
552
//      {
553
//          if (PropertyService.getProperty("database.queryCacheOn").equals("true"))
554
//          {
555
//              //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
556
//              DBQuery.clearQueryResultCache();
557
//          }
558
//      }
559
//      catch (PropertyNotFoundException e1)
560
//      {
561
//          //just don't do anything
562
//      }
563
//      
564
//      try
565
//      {
566
//          //TODO: Milliseconds need to be added to the dateFormat
567
//          System.out.println("=========== Listing Objects =============");
568
//          System.out.println("Current server time is: " + new Date());
569
//          if(startTime != null)
570
//          {
571
//              System.out.println("query start time is " + startTime);
572
//          }
573
//          if(endTime != null)
574
//          {
575
//              System.out.println("query end time is " + endTime);
576
//          }
577
//          params.clear();
578
//          params.put("qformat", new String[] {PropertyService.getProperty("crudService.listObjects.QFormat")});
579
//          params.put("action", new String[] {"squery"});
580
//          params.put("query", new String[] {createListObjectsPathQueryDocument()});
581
//          
582
//          /*System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
583
//                  " sessionid: " + sessionData.getId() + " params: ");
584
//          String url = metacatUrl + "/metacat?action=query&sessionid=" + sessionData.getId();
585
//          Enumeration keys = params.keys();
586
//          while(keys.hasMoreElements())
587
//          {
588
//              String key = (String)keys.nextElement();
589
//              String[] parr = params.get(key);
590
//              for(int i=0; i<parr.length; i++)
591
//              {
592
//                  System.out.println("param " + key + ": " + parr[i]);
593
//                  url += "&" + key + "=" + parr[i] ;
594
//              }
595
//          }
596
//          System.out.println("query url: " + url);
597
//          */
598
//          String username = "public";
599
//          String[] groups = null;
600
//          String sessionid = "";
601
//          if(sessionData != null)
602
//          {
603
//              username = sessionData.getUserName();
604
//              groups = sessionData.getGroupNames();
605
//              sessionid = sessionData.getId();
606
//          }
607
//          
608
//          MetacatResultSet rs = handler.query(metacatUrl, params, username, 
609
//                  groups, sessionid);
610
//          List docs = rs.getDocuments();
611
//          
612
//          System.out.println("query returned " + docs.size() + " documents.");
613
//          Vector<Document> docCopy = new Vector<Document>();
614
//          
615
//          //preparse the list to remove any that don't match the query params
616
//          /* TODO: this type of query/subquery processing is probably not scalable
617
//           * to larger object stores.  This code should be revisited.  The metacat
618
//           * query handler should probably be altered to handle the type of query 
619
//           * done here.
620
//           */ 
621
//          for(int i=0; i<docs.size(); i++)
622
//          {
623
//              Document d = (Document)docs.get(i);
624
//              
625
//              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
626
//              
627
//              if(returnedObjectFormat != null && 
628
//                 objectFormat != null && 
629
//                 !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
630
//              { //make sure the objectFormat is the one specified
631
//                  continue;
632
//              }
633
//              
634
//              String dateSMM = d.getField("dateSysMetadataModified");
635
//              if((startTime != null || endTime != null) && dateSMM == null)
636
//              {  //if startTime or endTime are not null, we need a date to compare to
637
//                  continue;
638
//              }
639
//              
640
//              //date parse
641
//              Date dateSysMetadataModified = null;
642
//              if(dateSMM != null)
643
//              {
644
//
645
//                  /*                  
646
//                  if(dateSMM.indexOf(".") != -1)
647
//                  {  //strip the milliseconds
648
//                      //TODO: don't do this. we need milliseconds now.
649
//                      //TODO: explore ISO 8601 to figure out milliseconds
650
//                      dateSMM = dateSMM.substring(0, dateSMM.indexOf(".")) + 'Z';
651
//                  }
652
//                  */
653
//                  //System.out.println("dateSMM: " + dateSMM);
654
//                  //dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-0"));
655
//                  try
656
//                  {   //the format we want
657
//                      dateSysMetadataModified = dateFormat.parse(dateSMM);
658
//                  }
659
//                  catch(java.text.ParseException pe)
660
//                  {   //try another legacy format
661
//                      try
662
//                      {
663
//                          DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S'Z'");
664
//                          dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
665
//                          dateSysMetadataModified = dateFormat2.parse(dateSMM);
666
//                      }
667
//                      catch(java.text.ParseException pe2)
668
//                      {
669
//                          //try another legacy format
670
//                          DateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
671
//                          dateFormat3.setTimeZone(TimeZone.getTimeZone("GMT-0"));
672
//                          dateSysMetadataModified = dateFormat3.parse(dateSMM);
673
//                      }
674
//                      
675
//                  }                  
676
//              }
677
//              
678
//              /*System.out.println("====================================");
679
//              System.out.println("doc number " + i);
680
//              System.out.println("docid: " + d.docid);
681
//              System.out.println("guid: " + d.getField("identifier").trim());
682
//              System.out.println("dateSMM: " + dateSMM);
683
//              System.out.println("dateSysMetadataModified: " + dateSysMetadataModified);
684
//              System.out.println("startTime: " + startTime);
685
//              System.out.println("endtime: " + endTime);*/
686
//              
687
//              int startDateComparison = 0;
688
//              int endDateComparison = 0;
689
//              if(startTime != null)
690
//              {
691
//                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
692
//                  zTime.setTime(startTime);
693
//                  startTime = zTime.getTime();
694
//                  
695
//                  if(dateSysMetadataModified == null)
696
//                  {
697
//                      startDateComparison = -1;
698
//                  }
699
//                  else
700
//                  {
701
//                      startDateComparison = dateSysMetadataModified.compareTo(startTime);
702
//                  }
703
//                  //System.out.println("startDateCom: " + startDateComparison);
704
//              }
705
//              else
706
//              {
707
//                  startDateComparison = 1;
708
//              }
709
//              
710
//              if(endTime != null)
711
//              {
712
//                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
713
//                  zTime.setTime(endTime);
714
//                  endTime = zTime.getTime();
715
//                  
716
//                  if(dateSysMetadataModified == null)
717
//                  {
718
//                      endDateComparison = 1;
719
//                  }
720
//                  else
721
//                  {
722
//                      endDateComparison = dateSysMetadataModified.compareTo(endTime);
723
//                  }
724
//                  //System.out.println("endDateCom: " + endDateComparison);
725
//              }
726
//              else
727
//              {
728
//                  endDateComparison = -1;
729
//              }
730
//              
731
//              
732
//              if(startDateComparison < 0 || endDateComparison > 0)
733
//              { 
734
//                  continue;                  
735
//              }
736
//              
737
//              docCopy.add((Document)docs.get(i));
738
//          } //end pre-parse
739
//          
740
//          docs = docCopy;
741
//          totalAfterQuery = docs.size();
742
//          //System.out.println("total after subquery: " + totalAfterQuery);
743
//          
744
//          //make sure we don't run over the end
745
//          int end = start + count;
746
//          if(end > docs.size())
747
//          {
748
//              end = docs.size();
749
//          }
750
//          
751
//          for(int i=start; i<end; i++)
752
//          {
753
//              //get the document from the result
754
//              Document d = (Document)docs.get(i);
755
//              //System.out.println("processing doc " + d.docid);
756
//              
757
//              String dateSMM = d.getField("dateSysMetadataModified");
758
//              //System.out.println("dateSMM: " + dateSMM);
759
//              //System.out.println("parsed date: " + parseDate(dateSMM));
760
//              Date dateSysMetadataModified = null;
761
//              if(dateSMM != null)
762
//              {
763
//                  try
764
//                  {
765
//                      dateSysMetadataModified = parseDate(dateSMM);
766
//                  }
767
//                  catch(Exception e)
768
//                  { //if we fail to parse the date, just ignore the value
769
//                      dateSysMetadataModified = null;
770
//                  }
771
//              }
772
//              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
773
//                
774
//              
775
//              ObjectInfo info = new ObjectInfo();
776
//              //add the fields to the info object
777
//              Checksum cs = new Checksum();
778
//              cs.setValue(d.getField("checksum"));
779
//              String csalg = d.getField("algorithm");
780
//              if(csalg == null)
781
//              {
782
//                  csalg = "MD5";
783
//              }
784
//              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
785
//              cs.setAlgorithm(ca);
786
//              info.setChecksum(cs);
787
//              info.setDateSysMetadataModified(dateSysMetadataModified);
788
//              Identifier id = new Identifier();
789
//              id.setValue(d.getField("identifier").trim());
790
//              info.setIdentifier(id);
791
//              info.setObjectFormat(returnedObjectFormat);
792
//              String size = d.getField("size");
793
//              if(size != null)
794
//              {
795
//                  info.setSize(new Long(size.trim()).longValue());
796
//              }
797
//              //add the ObjectInfo to the ObjectList
798
//              //logCrud.info("objectFormat: " + info.getObjectFormat().toString());
799
//              //logCrud.info("id: " + info.getIdentifier().getValue());
800
//              
801
//              if(info.getIdentifier().getValue() != null)
802
//              { //id can be null from tests.  should not happen in production.
803
//                  if((info.getObjectFormat() != null && !info.getObjectFormat().toString().trim().equals("")))
804
//                  { //objectFormat needs to not be null and not be an empty string
805
//                    ol.addObjectInfo(info);
806
//                  }
807
//                  else
808
//                  {
809
//                      logCrud.info("Not adding object with null objectFormat" + info.getIdentifier().getValue().toString());
810
//                  }
811
//              }
812
//             
813
//          }
814
//      }
815
//      catch(Exception e)
816
//      {
817
//          e.printStackTrace();
818
//          logCrud.error("Error creating ObjectList: " + e.getMessage() + " cause: " + e.getCause());
819
//          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
820
//      }
821
//      String username = "public";
822
//      if(sessionData != null)
823
//      {
824
//          username = sessionData.getUserName();
825
//      }
826
//      EventLog.getInstance().log(metacatUrl,
827
//              username, null, "read");
828
//      logCrud.info("listObjects");
829
//      if(totalAfterQuery < count)
830
//      {
831
//          count = totalAfterQuery;
832
//      }
833
//      ol.setCount(count);
834
//      ol.setStart(start);
835
//      ol.setTotal(totalAfterQuery);
836
//      return ol;
837
    }
838
    
839
    /**
840
     * Call listObjects with the default values for replicaStatus (true), start (0),
841
     * and count (1000).
842
     * @param token
843
     * @param startTime
844
     * @param endTime
845
     * @param objectFormat
846
     * @return
847
     * @throws NotAuthorized
848
     * @throws InvalidRequest
849
     * @throws NotImplemented
850
     * @throws ServiceFailure
851
     * @throws InvalidToken
852
     */
853
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
854
        ObjectFormat objectFormat)
855
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
856
    {
857
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
858
    }
859

    
860
    /**
861
     * Delete a document. 
862
     */
863
    public Identifier delete(AuthToken token, Identifier guid)
864
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
865
            NotImplemented, InvalidRequest {
866
        logCrud.info("delete");
867
        
868
        if(token == null || token.getToken().equals("publid"))
869
        {
870
            throw new NotAuthorized("1320", "You must be logged in to delete records.");
871
        }
872
        
873
        if(guid == null || guid.getValue().trim().equals(""))
874
        {
875
            throw new InvalidRequest("1322", "No GUID specified in CrudService.delete()");
876
        }
877
        final SessionData sessionData = getSessionData(token);
878
        IdentifierManager manager = IdentifierManager.getInstance();
879
        
880
        String docid;
881
        try
882
        {
883
            docid = manager.getLocalId(guid.getValue());
884
        }
885
        catch(McdbDocNotFoundException mnfe)
886
        {
887
            throw new InvalidRequest("1322", "GUID " + guid + " not found.");
888
        }
889
        
890
        try
891
        {
892
            DocumentImpl.delete(docid, sessionData.getUserName(), sessionData.getGroupNames(), null);
893
        }
894
        catch(SQLException e)
895
        {
896
            throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
897
        }
898
        catch(McdbDocNotFoundException e)
899
        {
900
          throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
901
        }
902
        catch(InsufficientKarmaException e)
903
        {
904
          throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
905
        }
906
        catch(Exception e)
907
        {
908
          throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
909
        }
910
        return guid;
911
    }
912

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

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

    
1025
    /**
1026
     * get the checksum for a document with the given algorithm
1027
     */
1028
    public Checksum getChecksum(AuthToken token, Identifier guid, 
1029
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
1030
            NotAuthorized, NotFound, InvalidRequest, NotImplemented 
1031
    {
1032
        logCrud.info("getChecksum");
1033
        SystemMetadata sm = getSystemMetadata(token, guid);
1034
        Checksum cs = sm.getChecksum();
1035
        if(cs.getAlgorithm().toString().equals(checksumAlgorithm))
1036
        {
1037
            return cs;
1038
        }
1039
        else
1040
        {
1041
            if(checksumAlgorithm == null)
1042
            {
1043
                checksumAlgorithm = "MD5";
1044
            }
1045
            
1046
            String checksum;
1047
            try
1048
            {
1049
            	//InputStream docStream = get(token, guid);
1050
                String localId = IdentifierManager.getInstance().getLocalId(guid.getValue());
1051
                DocumentImpl doc = new DocumentImpl(localId);
1052
                InputStream docStream = new ByteArrayInputStream(doc.getBytes());
1053
                
1054
                checksum = checksum(docStream, checksumAlgorithm);
1055
            }
1056
            catch(Exception e)
1057
            {
1058
                throw new ServiceFailure("1410", "Error getting checksum: " + e.getMessage());
1059
            }
1060
            Checksum c = new Checksum();
1061
            c.setAlgorithm(ChecksumAlgorithm.convert(checksumAlgorithm));
1062
            c.setValue(checksum);
1063
            return c;
1064
        }
1065
    }
1066

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

    
1210
    /**
1211
     * get the system metadata for a document with a specified guid.
1212
     */
1213
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
1214
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1215
            InvalidRequest, NotImplemented {
1216
        
1217
    	logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
1218
        
1219
        IdentifierManager im = IdentifierManager.getInstance();
1220
        String localId = null;
1221
        SystemMetadata sysmeta = null;
1222
		try {
1223
			localId = im.getSystemMetadataLocalId(guid.getValue());
1224
	        // look up the SysMeta
1225
	        sysmeta = im.getSystemMetadata(localId);
1226
		} catch (McdbDocNotFoundException e) {
1227
			e.printStackTrace();
1228
			throw new NotFound(null, "Could not locate SystemMetadata for localId: " + localId);
1229
		}        
1230

    
1231
		logCrud.info("getsystemmetadata D1GUID:" + guid.getValue()  + ":D1SYSMETADATA:"+ localId + ":");
1232
        
1233
        return sysmeta;
1234
                   
1235
    }
1236
    
1237
    /**
1238
     * parse the date in the systemMetadata
1239
     * @param s
1240
     * @return
1241
     * @throws Exception
1242
     */
1243
    public Date parseDate(String s)
1244
      throws Exception
1245
    {
1246
        /* TODO:
1247
         * This method should be replaced by a DateFormatter
1248
         */
1249
        Date d = null;
1250
        int tIndex = s.indexOf("T");
1251
        int zIndex = s.indexOf("Z");
1252
        if(tIndex != -1 && zIndex != -1)
1253
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
1254
            //System.out.println("original date: " + s);
1255
            
1256
            String date = s.substring(0, tIndex);
1257
            String year = date.substring(0, date.indexOf("-"));
1258
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
1259
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
1260
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
1261
                    " month: " + new Integer(month).intValue() + " day: " + 
1262
                    new Integer(day).intValue());
1263
            */
1264
            String time = s.substring(tIndex + 1, zIndex);
1265
            String hour = time.substring(0, time.indexOf(":"));
1266
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
1267
            String seconds = "00";
1268
            String milliseconds = "00";
1269
            if(time.indexOf(".") != -1)
1270
            {
1271
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
1272
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
1273
            }
1274
            else
1275
            {
1276
                seconds = time.substring(time.lastIndexOf(":") + 1, time.length());
1277
            }
1278
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
1279
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
1280
                    new Integer(seconds).intValue() + " milli: " + 
1281
                    new Integer(milliseconds).intValue());*/
1282
            
1283
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
1284
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0")/*TimeZone.getDefault()*/);
1285
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
1286
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
1287
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
1288
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
1289
            d = new Date(c.getTimeInMillis());
1290
            //System.out.println("d: " + d);
1291
            return d;
1292
        }
1293
        else
1294
        {  //if it's not in the expected format, try the formatter
1295
            return DateFormat.getDateTimeInstance().parse(s);
1296
        }
1297
    }
1298

    
1299
    /*
1300
     * Look up the information on the session using the token provided in
1301
     * the AuthToken.  The Session should have all relevant user information.
1302
     * If the session has expired or is invalid, the 'public' session will
1303
     * be returned, giving the user anonymous access.
1304
     */
1305
    public static SessionData getSessionData(AuthToken token) {
1306
        SessionData sessionData = null;
1307
        String sessionId = "PUBLIC";
1308
        if (token != null) {
1309
            sessionId = token.getToken();
1310
        }
1311
        
1312
        // if the session id is registered in SessionService, get the
1313
        // SessionData for it. Otherwise, use the public session.
1314
        //System.out.println("sessionid: " + sessionId);
1315
        if (sessionId != null &&
1316
            !sessionId.toLowerCase().equals("public") &&
1317
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1318
        {
1319
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1320
        } else {
1321
            sessionData = SessionService.getInstance().getPublicSession();
1322
        }
1323
        
1324
        return sessionData;
1325
    }
1326

    
1327
    /** 
1328
     * Determine if a given object should be treated as an XML science metadata
1329
     * object. 
1330
     * 
1331
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1332
     * 
1333
     * @param sysmeta the SystemMetadata describig the object
1334
     * @return true if the object should be treated as science metadata
1335
     */
1336
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1337
        /*boolean scimeta = false;
1338
        //TODO: this should be read from a .properties file instead of being hard coded
1339
        switch (sysmeta.getObjectFormat()) {
1340
            case EML_2_1_0: scimeta = true; break;
1341
            case EML_2_0_1: scimeta = true; break;
1342
            case EML_2_0_0: scimeta = true; break;
1343
            case FGDC_STD_001_1_1999: scimeta = true; break;
1344
            case FGDC_STD_001_1998: scimeta = true; break;
1345
            case NCML_2_2: scimeta = true; break;
1346
            case DSPACE_METS_SIP_1_0: scimeta = true; break;
1347
        }
1348
        
1349
        return scimeta;*/
1350
        
1351
        return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
1352
    }
1353

    
1354
    /**
1355
     * insert a data doc
1356
     * @param object
1357
     * @param guid
1358
     * @param sessionData
1359
     * @throws ServiceFailure
1360
     * @returns localId of the data object inserted
1361
     */
1362
    private String insertDataObject(InputStream object, Identifier guid, 
1363
            SessionData sessionData) throws ServiceFailure {
1364
        
1365
        String username = "public";
1366
        String[] groups = null;
1367
        if(sessionData != null)
1368
        {
1369
          username = sessionData.getUserName();
1370
          groups = sessionData.getGroupNames();
1371
        }
1372

    
1373
        // generate guid/localId pair for object
1374
        logMetacat.debug("Generating a guid/localId mapping");
1375
        IdentifierManager im = IdentifierManager.getInstance();
1376
        String localId = im.generateLocalId(guid.getValue(), 1);
1377

    
1378
        try {
1379
            logMetacat.debug("Case DATA: starting to write to disk.");
1380
            if (DocumentImpl.getDataFileLockGrant(localId)) {
1381
    
1382
                // Save the data file to disk using "localId" as the name
1383
                try {
1384
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
1385
    
1386
                    File dataDirectory = new File(datafilepath);
1387
                    dataDirectory.mkdirs();
1388
    
1389
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
1390
    
1391
                    // TODO: Check that the file size matches SystemMetadata
1392
                    //                        long size = newFile.length();
1393
                    //                        if (size == 0) {
1394
                    //                            throw new IOException("Uploaded file is 0 bytes!");
1395
                    //                        }
1396
    
1397
                    // Register the file in the database (which generates an exception
1398
                    // if the localId is not acceptable or other untoward things happen
1399
                    try {
1400
                        logMetacat.debug("Registering document...");
1401
                        DocumentImpl.registerDocument(localId, "BIN", localId,
1402
                                username, groups);
1403
                        logMetacat.debug("Registration step completed.");
1404
                    } catch (SQLException e) {
1405
                        //newFile.delete();
1406
                        logMetacat.debug("SQLE: " + e.getMessage());
1407
                        e.printStackTrace(System.out);
1408
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1409
                    } catch (AccessionNumberException e) {
1410
                        //newFile.delete();
1411
                        logMetacat.debug("ANE: " + e.getMessage());
1412
                        e.printStackTrace(System.out);
1413
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1414
                    } catch (Exception e) {
1415
                        //newFile.delete();
1416
                        logMetacat.debug("Exception: " + e.getMessage());
1417
                        e.printStackTrace(System.out);
1418
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1419
                    }
1420
    
1421
                    logMetacat.debug("Logging the creation event.");
1422
                    EventLog.getInstance().log(metacatUrl,
1423
                            username, localId, "create");
1424
    
1425
                    // Schedule replication for this data file
1426
                    logMetacat.debug("Scheduling replication.");
1427
                    ForceReplicationHandler frh = new ForceReplicationHandler(
1428
                            localId, "create", false, null);
1429
    
1430
                } catch (PropertyNotFoundException e) {
1431
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1432
                }
1433
            }
1434
            return localId;
1435
        } catch (Exception e) {
1436
            // Could not get a lock on the document, so we can not update the file now
1437
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1438
        }
1439
    }
1440

    
1441
    /**
1442
     * write a file to a stream
1443
     * @param dir
1444
     * @param fileName
1445
     * @param data
1446
     * @return
1447
     * @throws ServiceFailure
1448
     */
1449
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1450
        throws ServiceFailure {
1451
        
1452
        File newFile = new File(dir, fileName);
1453
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1454

    
1455
        try {
1456
            if (newFile.createNewFile()) {
1457
                // write data stream to desired file
1458
                OutputStream os = new FileOutputStream(newFile);
1459
                long length = IOUtils.copyLarge(data, os);
1460
                os.flush();
1461
                os.close();
1462
            } else {
1463
                logMetacat.debug("File creation failed, or file already exists.");
1464
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1465
            }
1466
        } catch (FileNotFoundException e) {
1467
            logMetacat.debug("FNF: " + e.getMessage());
1468
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1469
                    + e.getMessage());
1470
        } catch (IOException e) {
1471
            logMetacat.debug("IOE: " + e.getMessage());
1472
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1473
                    + " " + e.getMessage());
1474
        }
1475

    
1476
        return newFile;
1477
    }
1478

    
1479
    /**
1480
     * insert a systemMetadata doc, return the localId of the sysmeta
1481
     */
1482
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1483
        throws ServiceFailure 
1484
    {
1485
        logMetacat.debug("Starting to insert SystemMetadata...");
1486
    
1487
        // generate guid/localId pair for sysmeta
1488
        Identifier sysMetaGuid = new Identifier();
1489
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1490
        sysmeta.setDateSysMetadataModified(new Date());
1491
        logCrud.debug("****inserting new system metadata with modified date " + 
1492
                sysmeta.getDateSysMetadataModified());
1493

    
1494
        //insert the system metadata doc id into the systemmetadata table to 
1495
        //link it to the data or metadata document
1496
        IdentifierManager.getInstance().createSystemMetadataMapping(
1497
                sysmeta, sysMetaGuid.getValue());
1498
        
1499
        IdentifierManager.getInstance().insertAdditionalSystemMetadataFields(sysmeta);
1500
        
1501
    }
1502
    
1503
    /**
1504
     * update a systemMetadata doc
1505
     */
1506
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1507
      throws ServiceFailure
1508
    {
1509
        
1510
        logCrud.debug("CrudService.updateSystemMetadata() called.");
1511
        try
1512
        {
1513
            logCrud.debug("Setting date modified to " + new Date());
1514
            sm.setDateSysMetadataModified(new Date());
1515

    
1516
            IdentifierManager.getInstance().insertAdditionalSystemMetadataFields(sm);
1517
                        
1518
        }
1519
        catch(Exception e)
1520
        {
1521
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getClass() + ": " + e.getMessage());
1522
        }
1523
    }
1524
    
1525
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1526
        throws ServiceFailure
1527
    {
1528
        return insertDocument(xml, guid, sessionData, false);
1529
    }
1530
    
1531
    /**
1532
     * insert a document
1533
     * NOTE: this method shouldn't be used from the update or create() methods.  
1534
     * we shouldn't be putting the science metadata or data objects into memory.
1535
     */
1536
    private String insertDocument(String xml, Identifier guid, SessionData sessionData,
1537
            boolean isSystemMetadata)
1538
        throws ServiceFailure
1539
    {
1540
        return insertOrUpdateDocument(xml, guid, sessionData, "insert", isSystemMetadata);
1541
    }
1542
    
1543
    /**
1544
     * insert a document from a stream
1545
     */
1546
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1547
      throws IOException, ServiceFailure
1548
    {
1549
        //HACK: change this eventually.  we should not be converting the stream to a string
1550
        String xml = IOUtils.toString(is);
1551
        return insertDocument(xml, guid, sessionData);
1552
    }
1553
    
1554
    /**
1555
     * update a document
1556
     * NOTE: this method shouldn't be used from the update or create() methods.  
1557
     * we shouldn't be putting the science metadata or data objects into memory.
1558
     */
1559
    private String updateDocument(String xml, Identifier obsoleteGuid, 
1560
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1561
        throws ServiceFailure
1562
    {
1563
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update", isSystemMetadata);
1564
    }
1565
    
1566
    /**
1567
     * update a document from a stream
1568
     */
1569
    private String updateDocument(InputStream is, Identifier obsoleteGuid, 
1570
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1571
      throws IOException, ServiceFailure
1572
    {
1573
        //HACK: change this eventually.  we should not be converting the stream to a string
1574
        String xml = IOUtils.toString(is);
1575
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData, isSystemMetadata);
1576
        IdentifierManager im = IdentifierManager.getInstance();
1577
        if(guid != null)
1578
        {
1579
          im.createMapping(guid.getValue(), localId);
1580
        }
1581
        return localId;
1582
    }
1583
    
1584
    /**
1585
     * insert a document, return the id of the document that was inserted
1586
     */
1587
    protected String insertOrUpdateDocument(String xml, Identifier guid, 
1588
            SessionData sessionData, String insertOrUpdate, boolean isSystemMetadata) 
1589
        throws ServiceFailure {
1590
        logMetacat.debug("Starting to insert xml document...");
1591
        IdentifierManager im = IdentifierManager.getInstance();
1592

    
1593
        // generate guid/localId pair for sysmeta
1594
        String localId = null;
1595
        if(insertOrUpdate.equals("insert"))
1596
        {
1597
            localId = im.generateLocalId(guid.getValue(), 1, isSystemMetadata);
1598
        }
1599
        else
1600
        {
1601
            //localid should already exist in the identifier table, so just find it
1602
            try
1603
            {
1604
                logCrud.debug("updating guid " + guid.getValue());
1605
                if(!isSystemMetadata)
1606
                {
1607
                    logCrud.debug("looking in identifier table for guid " + guid.getValue());
1608
                    localId = im.getLocalId(guid.getValue());
1609
                }
1610
                else
1611
                {
1612
                    logCrud.debug("looking in systemmetadata table for guid " + guid.getValue());
1613
                    localId = im.getSystemMetadataLocalId(guid.getValue());
1614
                }
1615
                logCrud.debug("localId: " + localId);
1616
                //increment the revision
1617
                String docid = localId.substring(0, localId.lastIndexOf("."));
1618
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1619
                int rev = new Integer(revS).intValue();
1620
                rev++;
1621
                docid = docid + "." + rev;
1622
                localId = docid;
1623
                logCrud.debug("incremented localId: " + localId);
1624
            }
1625
            catch(McdbDocNotFoundException e)
1626
            {
1627
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1628
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1629
            }
1630
        }
1631
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1632
                localId);
1633

    
1634
        String[] action = new String[1];
1635
        action[0] = insertOrUpdate;
1636
        params.put("action", action);
1637
        String[] docid = new String[1];
1638
        docid[0] = localId;
1639
        params.put("docid", docid);
1640
        String[] doctext = new String[1];
1641
        doctext[0] = xml;
1642
        logMetacat.debug(doctext[0]);
1643
        params.put("doctext", doctext);
1644
        
1645
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1646
        // onto output stream, or alternatively, capture that and parse it to 
1647
        // generate the right exceptions
1648
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1649
        //PrintWriter pw = new PrintWriter(output);
1650
        String username = "public";
1651
        String[] groupnames = null;
1652
        if(sessionData != null)
1653
        {
1654
            username = sessionData.getUserName();
1655
            groupnames = sessionData.getGroupNames();
1656
        }
1657
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1658
                            null, params, username, groupnames);
1659
        if(result.indexOf("<error>") != -1)
1660
        {
1661
            throw new ServiceFailure("1000", "Error inserting or updating document: " + result);
1662
        }
1663
        //String outputS = new String(output.toByteArray());
1664
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1665
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1666
        return localId;
1667
    }
1668
    
1669
    /**
1670
     * serialize a dataone type
1671
     */
1672
//    private void serializeServiceType(Class type, Object object, OutputStream out)
1673
//        throws JiBXException
1674
//    {
1675
//        IBindingFactory bfact = BindingDirectory.getFactory(type);
1676
//        IMarshallingContext mctx = bfact.createMarshallingContext();
1677
//        mctx.marshalDocument(object, "UTF-8", null, out);
1678
//    }
1679
    
1680
    /**
1681
     * serialize a system metadata doc
1682
     * @param sysmeta
1683
     * @return
1684
     * @throws ServiceFailure
1685
     */
1686
//    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1687
//        throws ServiceFailure {
1688
//        IBindingFactory bfact;
1689
//        ByteArrayOutputStream sysmetaOut = null;
1690
//        try {
1691
//            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1692
//            IMarshallingContext mctx = bfact.createMarshallingContext();
1693
//            sysmetaOut = new ByteArrayOutputStream();
1694
//            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1695
//        } catch (JiBXException e) {
1696
//            e.printStackTrace();
1697
//            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1698
//        }
1699
//        
1700
//        return sysmetaOut;
1701
//    }
1702
//    
1703
    /**
1704
     * deserialize a system metadata doc
1705
     * @param xml
1706
     * @return
1707
     * @throws ServiceFailure
1708
     */
1709
//    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1710
//        throws ServiceFailure {
1711
//        try {
1712
//            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1713
//            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1714
//            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1715
//            return sysmeta;
1716
//        } catch (JiBXException e) {
1717
//            e.printStackTrace();
1718
//            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1719
//        }    
1720
//    }
1721
    
1722
    /**
1723
     * read a document from metacat and return the InputStream
1724
     * 
1725
     * @param localId
1726
     * @param username
1727
     * @param groups
1728
     * @return
1729
     * @throws InsufficientKarmaException
1730
     * @throws ParseLSIDException
1731
     * @throws PropertyNotFoundException
1732
     * @throws McdbException
1733
     * @throws SQLException
1734
     * @throws ClassNotFoundException
1735
     * @throws IOException
1736
     */
1737
    private InputStream readFromMetacat(String localId, String username, String[] groups)
1738
        throws InsufficientKarmaException, ParseLSIDException,
1739
        PropertyNotFoundException, McdbException, SQLException, 
1740
        ClassNotFoundException, IOException
1741
    {
1742
        File tmpDir;
1743
        try
1744
        {
1745
            tmpDir = new File(PropertyService.getProperty("application.tempDir"));
1746
        }
1747
        catch(PropertyNotFoundException pnfe)
1748
        {
1749
            logMetacat.error("ResourceHandler.writeMMPPartstoFiles: " +
1750
                    "application.tmpDir not found.  Using /tmp instead.");
1751
            tmpDir = new File("/tmp");
1752
        }
1753
        Date d = new Date();
1754
        final File outputFile = new File(tmpDir, "metacat.output." + d.getTime());
1755
        FileOutputStream dataSink = new FileOutputStream(outputFile);
1756
        
1757
        handler.readFromMetacat(metacatUrl, null, 
1758
                dataSink, localId, "xml",
1759
                username, 
1760
                groups, true, params);
1761
        
1762
        //set a timer to clean up the temp files
1763
        Timer t = new Timer();
1764
        TimerTask tt = new TimerTask() {
1765
            @Override
1766
            public void run()
1767
            {
1768
                outputFile.delete();
1769
            }
1770
        };
1771
        t.schedule(tt, 20000); //schedule after 20 secs
1772
        
1773
        InputStream objectStream = new FileInputStream(outputFile);
1774
        return objectStream;
1775
    }
1776
    
1777
    /**
1778
     * return an MD5 checksum for the stream
1779
     * @param is
1780
     * @return
1781
     * @throws IOException 
1782
     * @throws NoSuchAlgorithmException 
1783
     */
1784
    public static String checksum(InputStream is) throws NoSuchAlgorithmException, IOException
1785
    {
1786
        return checksum(is, "MD5");
1787
    }
1788
    
1789
    /**
1790
     * produce a checksum for item using the given algorithm
1791
     * @throws IOException 
1792
     * @throws NoSuchAlgorithmException 
1793
     */
1794
    public static String checksum(InputStream is, String algorithm) throws NoSuchAlgorithmException, IOException
1795
    {        
1796
        return ServiceTypeUtil.checksum(is, ChecksumAlgorithm.convert(algorithm)).getValue();
1797
    }
1798
    
1799
    
1800
    
1801
    /**
1802
     * find the size (in bytes) of a stream
1803
     * @param is
1804
     * @return
1805
     * @throws IOException
1806
     */
1807
    private long sizeOfStream(InputStream is)
1808
        throws IOException
1809
    {
1810
        long size = 0;
1811
        byte[] b = new byte[1024];
1812
        int numread = is.read(b, 0, 1024);
1813
        while(numread != -1)
1814
        {
1815
            size += numread;
1816
            numread = is.read(b, 0, 1024);
1817
        }
1818
        return size;
1819
    }
1820
    
1821
    
1822
    
1823
    /**
1824
     * create the listObjects pathQuery document
1825
     */
1826
//    private String createListObjectsPathQueryDocument()
1827
//        throws PropertyNotFoundException
1828
//    {
1829
//        String s = "<pathquery>";
1830
//        s += "<returndoctype>" + PropertyService.getProperty("crudService.listObjects.ReturnDoctype") + "</returndoctype>";
1831
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.1") + "</returnfield>";
1832
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.2") + "</returnfield>";
1833
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.3") + "</returnfield>";
1834
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.4") + "</returnfield>";
1835
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.5") + "</returnfield>";
1836
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.6") + "</returnfield>";
1837
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.7") + "</returnfield>";
1838
//        s += "<querygroup operator=\"UNION\"><queryterm casesensitive=\"false\" searchmode=\"contains\">";
1839
//        s += "<value>%</value>"; 
1840
//        s += "<pathexpr>" + PropertyService.getProperty("crudService.listObjects.ReturnField.3") + "</pathexpr>";
1841
//        s += "</queryterm></querygroup></pathquery>";
1842
//  
1843
//        return s;
1844
//    }
1845
}
1846

    
(1-1/4)