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

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

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

    
1006
    /**
1007
     * get the checksum for a document.  defaults to MD5.
1008
     */
1009
    public Checksum getChecksum(AuthToken token, Identifier guid)
1010
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1011
            InvalidRequest, NotImplemented 
1012
    {
1013
        logCrud.info("getChecksum");
1014
        return getChecksum(token, guid, "MD5");
1015
    }
1016

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

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

    
1202
    /**
1203
     * get the system metadata for a document with a specified guid.
1204
     */
1205
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
1206
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1207
            InvalidRequest, NotImplemented {
1208
        
1209
    	logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
1210
        
1211
        SystemMetadata sysmeta = null;
1212
		try {
1213
	        // look up the SysMeta
1214
	        sysmeta = IdentifierManager.getInstance().getSystemMetadata(guid.getValue());
1215
		} catch (McdbDocNotFoundException e) {
1216
			e.printStackTrace();
1217
			throw new NotFound(null, "Could not locate SystemMetadata for: " + guid.getValue());
1218
		}        
1219

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

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

    
1316
    /** 
1317
     * Determine if a given object should be treated as an XML science metadata
1318
     * object. 
1319
     * 
1320
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1321
     * 
1322
     * @param sysmeta the SystemMetadata describig the object
1323
     * @return true if the object should be treated as science metadata
1324
     */
1325
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1326
        /*boolean scimeta = false;
1327
        //TODO: this should be read from a .properties file instead of being hard coded
1328
        switch (sysmeta.getObjectFormat()) {
1329
            case EML_2_1_0: scimeta = true; break;
1330
            case EML_2_0_1: scimeta = true; break;
1331
            case EML_2_0_0: scimeta = true; break;
1332
            case FGDC_STD_001_1_1999: scimeta = true; break;
1333
            case FGDC_STD_001_1998: scimeta = true; break;
1334
            case NCML_2_2: scimeta = true; break;
1335
            case DSPACE_METS_SIP_1_0: scimeta = true; break;
1336
        }
1337
        
1338
        return scimeta;*/
1339
        
1340
        return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
1341
    }
1342

    
1343
    /**
1344
     * insert a data doc
1345
     * @param object
1346
     * @param guid
1347
     * @param sessionData
1348
     * @throws ServiceFailure
1349
     * @returns localId of the data object inserted
1350
     */
1351
    private String insertDataObject(InputStream object, Identifier guid, 
1352
            SessionData sessionData) throws ServiceFailure {
1353
        
1354
        String username = "public";
1355
        String[] groups = null;
1356
        if(sessionData != null)
1357
        {
1358
          username = sessionData.getUserName();
1359
          groups = sessionData.getGroupNames();
1360
        }
1361

    
1362
        // generate guid/localId pair for object
1363
        logMetacat.debug("Generating a guid/localId mapping");
1364
        IdentifierManager im = IdentifierManager.getInstance();
1365
        String localId = im.generateLocalId(guid.getValue(), 1);
1366

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

    
1430
    /**
1431
     * write a file to a stream
1432
     * @param dir
1433
     * @param fileName
1434
     * @param data
1435
     * @return
1436
     * @throws ServiceFailure
1437
     */
1438
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1439
        throws ServiceFailure {
1440
        
1441
        File newFile = new File(dir, fileName);
1442
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1443

    
1444
        try {
1445
            if (newFile.createNewFile()) {
1446
                // write data stream to desired file
1447
                OutputStream os = new FileOutputStream(newFile);
1448
                long length = IOUtils.copyLarge(data, os);
1449
                os.flush();
1450
                os.close();
1451
            } else {
1452
                logMetacat.debug("File creation failed, or file already exists.");
1453
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1454
            }
1455
        } catch (FileNotFoundException e) {
1456
            logMetacat.debug("FNF: " + e.getMessage());
1457
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1458
                    + e.getMessage());
1459
        } catch (IOException e) {
1460
            logMetacat.debug("IOE: " + e.getMessage());
1461
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1462
                    + " " + e.getMessage());
1463
        }
1464

    
1465
        return newFile;
1466
    }
1467

    
1468
    /**
1469
     * insert a systemMetadata doc, return the localId of the sysmeta
1470
     */
1471
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1472
        throws ServiceFailure 
1473
    {
1474
        logMetacat.debug("Starting to insert SystemMetadata...");
1475
        sysmeta.setDateSysMetadataModified(new Date());
1476
        logCrud.debug("****inserting new system metadata with modified date " + 
1477
                sysmeta.getDateSysMetadataModified());
1478

    
1479
        //insert the system metadata
1480
        IdentifierManager.getInstance().createSystemMetadata(sysmeta);
1481
        IdentifierManager.getInstance().updateSystemMetadata(sysmeta);
1482
        
1483
    }
1484
    
1485
    /**
1486
     * update a systemMetadata doc
1487
     */
1488
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1489
      throws ServiceFailure
1490
    {
1491
        
1492
        logCrud.debug("CrudService.updateSystemMetadata() called.");
1493
        try
1494
        {
1495
            logCrud.debug("Setting date modified to " + new Date());
1496
            sm.setDateSysMetadataModified(new Date());
1497
            IdentifierManager.getInstance().updateSystemMetadata(sm);
1498
        }
1499
        catch(Exception e)
1500
        {
1501
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getClass() + ": " + e.getMessage());
1502
        }
1503
    }
1504
    
1505
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1506
        throws ServiceFailure
1507
    {
1508
        return insertDocument(xml, guid, sessionData, false);
1509
    }
1510
    
1511
    /**
1512
     * insert a document
1513
     * NOTE: this method shouldn't be used from the update or create() methods.  
1514
     * we shouldn't be putting the science metadata or data objects into memory.
1515
     */
1516
    private String insertDocument(String xml, Identifier guid, SessionData sessionData,
1517
            boolean isSystemMetadata)
1518
        throws ServiceFailure
1519
    {
1520
        return insertOrUpdateDocument(xml, guid, sessionData, "insert", isSystemMetadata);
1521
    }
1522
    
1523
    /**
1524
     * insert a document from a stream
1525
     */
1526
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1527
      throws IOException, ServiceFailure
1528
    {
1529
        //HACK: change this eventually.  we should not be converting the stream to a string
1530
        String xml = IOUtils.toString(is);
1531
        return insertDocument(xml, guid, sessionData);
1532
    }
1533
    
1534
    /**
1535
     * update a document
1536
     * NOTE: this method shouldn't be used from the update or create() methods.  
1537
     * we shouldn't be putting the science metadata or data objects into memory.
1538
     */
1539
    private String updateDocument(String xml, Identifier obsoleteGuid, 
1540
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1541
        throws ServiceFailure
1542
    {
1543
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update", isSystemMetadata);
1544
    }
1545
    
1546
    /**
1547
     * update a document from a stream
1548
     */
1549
    private String updateDocument(InputStream is, Identifier obsoleteGuid, 
1550
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1551
      throws IOException, ServiceFailure
1552
    {
1553
        //HACK: change this eventually.  we should not be converting the stream to a string
1554
        String xml = IOUtils.toString(is);
1555
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData, isSystemMetadata);
1556
        IdentifierManager im = IdentifierManager.getInstance();
1557
        if(guid != null)
1558
        {
1559
          im.createMapping(guid.getValue(), localId);
1560
        }
1561
        return localId;
1562
    }
1563
    
1564
    /**
1565
     * insert a document, return the id of the document that was inserted
1566
     */
1567
    protected String insertOrUpdateDocument(String xml, Identifier guid, 
1568
            SessionData sessionData, String insertOrUpdate, boolean isSystemMetadata) 
1569
        throws ServiceFailure {
1570
        logMetacat.debug("Starting to insert xml document...");
1571
        IdentifierManager im = IdentifierManager.getInstance();
1572

    
1573
        // generate guid/localId pair for sysmeta
1574
        String localId = null;
1575
        if(insertOrUpdate.equals("insert"))
1576
        {
1577
            localId = im.generateLocalId(guid.getValue(), 1, isSystemMetadata);
1578
        }
1579
        else
1580
        {
1581
            //localid should already exist in the identifier table, so just find it
1582
            try
1583
            {
1584
                logCrud.debug("updating guid " + guid.getValue());
1585
                logCrud.debug("looking in identifier table for guid " + guid.getValue());
1586
                
1587
                localId = im.getLocalId(guid.getValue());
1588
                
1589
                logCrud.debug("localId: " + localId);
1590
                //increment the revision
1591
                String docid = localId.substring(0, localId.lastIndexOf("."));
1592
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1593
                int rev = new Integer(revS).intValue();
1594
                rev++;
1595
                docid = docid + "." + rev;
1596
                localId = docid;
1597
                logCrud.debug("incremented localId: " + localId);
1598
            }
1599
            catch(McdbDocNotFoundException e)
1600
            {
1601
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1602
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1603
            }
1604
        }
1605
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1606
                localId);
1607

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

    
(1-1/4)