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

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

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

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

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

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

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

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

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

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

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

    
1369
        // generate guid/localId pair for object
1370
        logMetacat.debug("Generating a guid/localId mapping");
1371
        IdentifierManager im = IdentifierManager.getInstance();
1372
        String localId = im.generateLocalId(guid.getValue(), 1);
1373

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

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

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

    
1472
        return newFile;
1473
    }
1474

    
1475
    /**
1476
     * insert a systemMetadata doc, return the localId of the sysmeta
1477
     */
1478
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1479
        throws ServiceFailure 
1480
    {
1481
        logMetacat.debug("Starting to insert SystemMetadata...");
1482
        sysmeta.setDateSysMetadataModified(new Date());
1483
        logCrud.debug("****inserting new system metadata with modified date " + 
1484
                sysmeta.getDateSysMetadataModified());
1485

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

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

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

    
(2-2/8)