Project

General

Profile

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

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

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

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

    
64
import com.gc.iotools.stream.is.InputStreamFromOutputStream;
65

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

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

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

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

    
145
        handler = new MetacatHandler(new Timer());
146

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

    
272
        logMetacat.debug("Starting CrudService.create()...");
273
        
274
        // authenticate & get user info
275
        SessionData sessionData = getSessionData(token);
276
        String username = "public";
277
        String[] groups = null;
278
        if(sessionData != null)
279
        {
280
            username = sessionData.getUserName();
281
            groups = sessionData.getGroupNames();
282
        }
283
        String localId = null;
284

    
285
        if (username == null || username.equals("public"))
286
        {
287
            throw new NotAuthorized("1000", "User " + username + " is not authorized to create content." +
288
                    "  If you are not logged in, please do so and retry the request.");
289
        }
290
        
291
        // verify that guid == SystemMetadata.getIdentifier()
292
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
293
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
294
            throw new InvalidSystemMetadata("1180", 
295
                "GUID in method call does not match GUID in system metadata.");
296
        }
297

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

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

    
326
        } else {
327
            // DEFAULT CASE: DATA (needs to be checked and completed)
328
            insertDataObject(object, guid, sessionData);
329
            
330
        }
331

    
332
        // For Metadata and Data, insert the system metadata into the object store too
333
        String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
334
        //get the document info.  add any access params for the sysmeta too
335
        try
336
        {
337
            Hashtable<String, Object> h = im.getDocumentInfo(sysMetaLocalId);
338
            Vector v = (Vector)h.get("access");
339
            for(int i=0; i<v.size(); i++)
340
            {
341
                Hashtable ah = (Hashtable)v.elementAt(i);
342
                String principal = (String)ah.get("principal_name");
343
                String permission = (String)ah.get("permission");
344
                String permissionType = (String)ah.get("permission_type");
345
                String permissionOrder = (String)ah.get("permission_order");
346
                int perm = new Integer(permission).intValue();
347
                this.setAccess(token, guid, principal, perm, permissionType, permissionOrder, false);
348
            }
349
        }
350
        catch(Exception e)
351
        {
352
            logMetacat.error("Error setting permissions on System Metadata object " + 
353
                    " with id " + sysMetaLocalId + ": " + e.getMessage());
354
        }
355
        
356
        
357
        logMetacat.debug("Returning from CrudService.create()");
358
        EventLog.getInstance().log(metacatUrl,
359
                username, localId, "create");
360
        logCrud.info("create localId:" + localId + " guid:" + guid.getValue());
361
        return guid;
362
    }
363
    
364
    /**
365
     * update an existing object with a new object.  Change the system metadata
366
     * to reflect the changes and update it as well.
367
     */
368
    public Identifier update(AuthToken token, Identifier guid, 
369
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
370
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
371
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
372
            NotImplemented {
373
        try
374
        {
375
            SessionData sessionData = getSessionData(token);
376
            
377
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
378
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
379
            //change sm.old's obsoletedBy field 
380
            List l = sm.getObsoletedByList();
381
            l.add(guid);
382
            sm.setObsoletedByList(l);
383
            //update sm.old
384
            updateSystemMetadata(sm, sessionData);
385
            
386
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
387
            sysmeta.addObsolete(obsoletedGuid);
388
            //insert sm.new
389
            insertSystemMetadata(sysmeta, sessionData);
390
            
391
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
392
            if(isScienceMetadata)
393
            {
394
                //update the doc
395
                updateDocument(object, obsoletedGuid, guid, sessionData);
396
            }
397
            else
398
            {
399
                //update a data file, not xml
400
                insertDataObject(object, guid, sessionData);
401
            }
402
            
403
            IdentifierManager im = IdentifierManager.getInstance();
404
            String username = "public";
405
            if(sessionData != null)
406
            {
407
                username = sessionData.getUserName();
408
            }
409
            EventLog.getInstance().log(metacatUrl,
410
                    username, im.getLocalId(guid.getValue()), "update");
411
            logCrud.info("update localId:" + im.getLocalId(guid.getValue()) + " guid:" + guid.getValue());
412
            return guid;
413
        }
414
        catch(Exception e)
415
        {
416
            throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
417
        }
418
    }
419
    
420
    /**
421
     * set access control on the doc
422
     * @param token
423
     * @param id
424
     * @param principal
425
     * @param permission
426
     */
427
    public void setAccess(AuthToken token, Identifier id, String principal, int permission,
428
      String permissionType, String permissionOrder, boolean setSystemMetadata)
429
      throws ServiceFailure
430
    {
431
        String perm = "";
432
        if(permission == 4)
433
        {
434
            perm = "read";
435
        }
436
        if(permission == 6)
437
        {
438
            perm = "write";
439
        }
440
        setAccess(token, id, principal, perm, permissionType, permissionOrder,
441
                setSystemMetadata);
442
       
443
    }
444
    
445
    /**
446
     * set the permission on the document
447
     * @param token
448
     * @param principal
449
     * @param permission
450
     * @param permissionType
451
     * @param permissionOrder
452
     * @return
453
     */
454
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
455
            String permissionType, String permissionOrder, boolean setSystemMetadata)
456
      throws ServiceFailure
457
    {
458
        try
459
        {
460
            IdentifierManager im = IdentifierManager.getInstance();
461
            String docid = im.getLocalId(id.getValue());
462
            final SessionData sessionData = getSessionData(token);
463
            String permNum = "0";
464
            if(permission.equals("read"))
465
            {
466
                permNum = "4";
467
            }
468
            else if(permission.equals("write"))
469
            {
470
                permNum = "6";
471
            }
472
            System.out.println("user " + sessionData.getUserName() + 
473
                    " is setting access level " + permNum + " for permission " + 
474
                    permissionType + " on doc with localid " + docid);
475
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
476
                    principal, permNum, permissionType, permissionOrder);
477
            if(setSystemMetadata)
478
            {
479
                //set the same perms on the system metadata doc
480
                String smlocalid = im.getSystemMetadataLocalId(id.getValue());
481
                System.out.println("setting access on SM doc with localid " + smlocalid);
482
                //cs.setAccess(token, smid, principal, permission, permissionType, permissionOrder);
483
                handler.setAccess(metacatUrl, sessionData.getUserName(), smlocalid,
484
                        principal, permNum, permissionType, permissionOrder);
485
            }
486
            String username = "public";
487
            if(sessionData != null)
488
            {
489
                username = sessionData.getUserName();
490
            }
491
            EventLog.getInstance().log(metacatUrl,
492
                    username, im.getLocalId(id.getValue()), "setAccess");
493
            logCrud.info("setAccess");
494
        }
495
        catch(Exception e)
496
        {
497
            e.printStackTrace();
498
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
499
        }
500
    }
501
    
502
    /**
503
     *  Retrieve the list of objects present on the MN that match the calling 
504
     *  parameters. This method is required to support the process of Member 
505
     *  Node synchronization. At a minimum, this method should be able to 
506
     *  return a list of objects that match:
507
     *  startTime <= SystemMetadata.dateSysMetadataModified
508
     *  but is expected to also support date range (by also specifying endTime), 
509
     *  and should also support slicing of the matching set of records by 
510
     *  indicating the starting index of the response (where 0 is the index 
511
     *  of the first item) and the count of elements to be returned.
512
     *  
513
     *  If startTime or endTime is null, the query is not restricted by that parameter.
514
     *  
515
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
516
     * @param token
517
     * @param startTime
518
     * @param endTime
519
     * @param objectFormat
520
     * @param replicaStatus
521
     * @param start
522
     * @param count
523
     * @return ObjectList
524
     * @throws NotAuthorized
525
     * @throws InvalidRequest
526
     * @throws NotImplemented
527
     * @throws ServiceFailure
528
     * @throws InvalidToken
529
     */
530
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
531
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
532
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
533
    {
534
      ObjectList ol = new ObjectList();
535
      final SessionData sessionData = getSessionData(token);
536
      int totalAfterQuery = 0;
537
      try
538
      {
539
          System.out.println("=========== Listing Objects =============");
540
          System.out.println("Current server time is: " + new Date());
541
          if(startTime != null)
542
          {
543
              System.out.println("query start time is " + startTime);
544
          }
545
          if(endTime != null)
546
          {
547
              System.out.println("query end time is " + endTime);
548
          }
549
          params.clear();
550
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
551
          params.put("qformat", new String[] {"xml"});
552
          params.put("returnfield", new String[] {"size", "originMemberNode", 
553
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "checksum/@algorithm"});
554
          params.put("anyfield", new String[] {"%"});
555
          
556
          //System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
557
          //    " sessionid: " + sessionData.getId() + " params: " + params.toString());
558
          String username = "public";
559
          String[] groups = null;
560
          String sessionid = "";
561
          if(sessionData != null)
562
          {
563
              username = sessionData.getUserName();
564
              groups = sessionData.getGroupNames();
565
              sessionid = sessionData.getId();
566
          }
567
          
568
          MetacatResultSet rs = handler.query(metacatUrl, params, username, 
569
                  groups, sessionid);
570
          List docs = rs.getDocuments();
571
          if(count == 1000)
572
          {
573
              count = docs.size();
574
          }
575
          
576
          //System.out.println("query returned " + docs.size() + " documents.");
577
          Vector<Document> docCopy = new Vector<Document>();
578
          
579
          //preparse the list to remove any that don't match the query params
580
          for(int i=0; i<docs.size(); i++)
581
          {
582
              Document d = (Document)docs.get(i);
583
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
584
              
585
              if(returnedObjectFormat != null && 
586
                 objectFormat != null && 
587
                 !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
588
              { //make sure the objectFormat is the one specified
589
                  continue;
590
              }
591
              
592
              String dateSMM = d.getField("dateSysMetadataModified");
593
              if((startTime != null || endTime != null) && dateSMM == null)
594
              {  //if startTime or endTime are not null, we need a date to compare to
595
                  continue;
596
              }
597
              
598
              //date parse
599
              Date dateSysMetadataModified = null;
600
              if(dateSMM != null)
601
              {
602
                  //dateSysMetadataModified = parseDate(dateSMM);
603
                  if(dateSMM.indexOf(".") != -1)
604
                  {  //strip the milliseconds
605
                      dateSMM = dateSMM.substring(0, dateSMM.indexOf(".")) + 'Z';
606
                  }
607
                  //System.out.println("dateSMM: " + dateSMM);
608
                  //dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-0"));
609
                  try
610
                  {   //the format we want
611
                      dateSysMetadataModified = dateFormat.parse(dateSMM);
612
                  }
613
                  catch(java.text.ParseException pe)
614
                  {   //try another legacy format
615
                      DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
616
                      dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
617
                      dateSysMetadataModified = dateFormat2.parse(dateSMM);
618
                  }                  
619
              }
620
              
621
              /*System.out.println("docid: " + d.docid);
622
              System.out.println("dateSysMetadataModified: " + dateSysMetadataModified);
623
              System.out.println("startTime: " + startTime);
624
              System.out.println("endtime: " + endTime);*/
625
              
626
              int startDateComparison = 0;
627
              int endDateComparison = 0;
628
              if(startTime != null)
629
              {
630
                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
631
                  zTime.setTime(startTime);
632
                  startTime = zTime.getTime();
633
                  
634
                  if(dateSysMetadataModified == null)
635
                  {
636
                      startDateComparison = -1;
637
                  }
638
                  else
639
                  {
640
                      startDateComparison = dateSysMetadataModified.compareTo(startTime);
641
                  }
642
                  //System.out.println("startDateCom: " + startDateComparison);
643
              }
644
              else
645
              {
646
                  startDateComparison = 1;
647
              }
648
              
649
              if(endTime != null)
650
              {
651
                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
652
                  zTime.setTime(endTime);
653
                  endTime = zTime.getTime();
654
                  
655
                  if(dateSysMetadataModified == null)
656
                  {
657
                      endDateComparison = 1;
658
                  }
659
                  else
660
                  {
661
                      endDateComparison = dateSysMetadataModified.compareTo(endTime);
662
                  }
663
                  //System.out.println("endDateCom: " + endDateComparison);
664
              }
665
              else
666
              {
667
                  endDateComparison = -1;
668
              }
669
              
670
              
671
              if(startDateComparison < 0 || endDateComparison > 0)
672
              { 
673
                  continue;                  
674
              }
675
              
676
              docCopy.add((Document)docs.get(i));
677
          } //end pre-parse
678
          
679
          docs = docCopy;
680
          totalAfterQuery = docs.size();
681
          //System.out.println("total after subquery: " + totalAfterQuery);
682
          
683
          //make sure we don't run over the end
684
          int end = start + count;
685
          if(end > docs.size())
686
          {
687
              end = docs.size();
688
          }
689
          
690
          for(int i=start; i<end; i++)
691
          {
692
              //get the document from the result
693
              Document d = (Document)docs.get(i);
694
              //System.out.println("processing doc " + d.docid);
695
              
696
              String dateSMM = d.getField("dateSysMetadataModified");
697
              Date dateSysMetadataModified = null;
698
              if(dateSMM != null)
699
              {
700
                  try
701
                  {
702
                      dateSysMetadataModified = parseDate(dateSMM);
703
                  }
704
                  catch(Exception e)
705
                  { //if we fail to parse the date, just ignore the value
706
                      dateSysMetadataModified = null;
707
                  }
708
              }
709
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
710
                
711
              
712
              ObjectInfo info = new ObjectInfo();
713
              //add the fields to the info object
714
              Checksum cs = new Checksum();
715
              cs.setValue(d.getField("checksum"));
716
              String csalg = d.getField("algorithm");
717
              if(csalg == null)
718
              {
719
                  csalg = "MD5";
720
              }
721
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
722
              cs.setAlgorithm(ca);
723
              info.setChecksum(cs);
724
              info.setDateSysMetadataModified(dateSysMetadataModified);
725
              Identifier id = new Identifier();
726
              id.setValue(d.getField("identifier"));
727
              info.setIdentifier(id);
728
              info.setObjectFormat(returnedObjectFormat);
729
              String size = d.getField("size");
730
              if(size != null)
731
              {
732
                  info.setSize(new Long(size.trim()).longValue());
733
              }
734
              //add the ObjectInfo to the ObjectList
735
              if(info.getIdentifier().getValue() != null)
736
              { //id can be null from tests.  should not happen in production.
737
                  ol.addObjectInfo(info);
738
              }
739
             
740
          }
741
      }
742
      catch(Exception e)
743
      {
744
          e.printStackTrace();
745
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
746
      }
747
      String username = "public";
748
      if(sessionData != null)
749
      {
750
          username = sessionData.getUserName();
751
      }
752
      EventLog.getInstance().log(metacatUrl,
753
              username, null, "read");
754
      logCrud.info("listObjects");
755
      ol.setCount(count);
756
      ol.setStart(start);
757
      ol.setTotal(totalAfterQuery);
758
      return ol;
759
    }
760
    
761
    /**
762
     * Call listObjects with the default values for replicaStatus (true), start (0),
763
     * and count (1000).
764
     * @param token
765
     * @param startTime
766
     * @param endTime
767
     * @param objectFormat
768
     * @return
769
     * @throws NotAuthorized
770
     * @throws InvalidRequest
771
     * @throws NotImplemented
772
     * @throws ServiceFailure
773
     * @throws InvalidToken
774
     */
775
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
776
        ObjectFormat objectFormat)
777
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
778
    {
779
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
780
    }
781

    
782
    /**
783
     * Delete a document.  NOT IMPLEMENTED
784
     */
785
    public Identifier delete(AuthToken token, Identifier guid)
786
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
787
            NotImplemented {
788
        logCrud.info("delete");
789
        throw new NotImplemented("1000", "This method not yet implemented.");
790
    }
791

    
792
    /**
793
     * describe a document.  NOT IMPLEMENTED
794
     */
795
    public DescribeResponse describe(AuthToken token, Identifier guid)
796
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
797
            NotImplemented {
798
        logCrud.info("describe");
799
        throw new NotImplemented("1000", "This method not yet implemented.");
800
    }
801
    
802
    /**
803
     * get a document with a specified guid.
804
     */
805
    public InputStream get(AuthToken token, Identifier guid)
806
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
807
            NotImplemented {
808
        
809
        // Retrieve the session information from the AuthToken
810
        // If the session is expired, then the user is 'public'
811
        if(token == null)
812
        {
813
            token = new AuthToken("Public");
814
        }
815
        final SessionData sessionData = getSessionData(token);
816
        
817
        // Look up the localId for this global identifier
818
        IdentifierManager im = IdentifierManager.getInstance();
819
        try {
820
            final String localId = im.getLocalId(guid.getValue());
821

    
822
            final InputStreamFromOutputStream<String> objectStream = 
823
                new InputStreamFromOutputStream<String>() {
824
                
825
                @Override
826
                public String produce(final OutputStream dataSink) throws Exception {
827

    
828
                    try {
829
                        String username = "public";
830
                        String[] groups = new String[0];
831
                        if(sessionData != null)
832
                        {
833
                            username = sessionData.getUserName();
834
                            groups = sessionData.getGroupNames();
835
                        }
836
                        /*System.out.println("metacatUrl: " + metacatUrl + 
837
                            " dataSink: " + dataSink + " localId: " + localId + 
838
                            " username: " + username + " params: " + params.toString());
839
                        */    
840
                        handler.readFromMetacat(metacatUrl, null, 
841
                                dataSink, localId, "xml",
842
                                username, 
843
                                groups, true, params);
844
                    } catch (PropertyNotFoundException e) {
845
                        e.printStackTrace();
846
                        throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
847
                    } catch (ClassNotFoundException e) {
848
                        e.printStackTrace();
849
                        throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
850
                    } catch (IOException e) {
851
                        e.printStackTrace();
852
                        throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
853
                    } catch (SQLException e) {
854
                        e.printStackTrace();
855
                        throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
856
                    } catch (McdbException e) {
857
                        e.printStackTrace();
858
                        throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
859
                    } catch (ParseLSIDException e) {
860
                        e.printStackTrace();
861
                        throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
862
                    } catch (InsufficientKarmaException e) {
863
                        e.printStackTrace();
864
                        throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
865
                    }
866

    
867
                    return "Completed";
868
                }
869
            };
870
            String username = "public";
871
            if(sessionData != null)
872
            {
873
                username = sessionData.getUserName();
874
            }
875
            
876
            EventLog.getInstance().log(metacatUrl,
877
                    username, im.getLocalId(guid.getValue()), "read");
878
            logCrud.info("get localId:" + localId + " guid:" + guid.getValue());
879
            return objectStream;
880

    
881
        } catch (McdbDocNotFoundException e) {
882
            throw new NotFound("1020", e.getMessage());
883
        }
884
    }
885

    
886
    /**
887
     * get the checksum for a document.  NOT IMPLEMENTED
888
     */
889
    public Checksum getChecksum(AuthToken token, Identifier guid)
890
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
891
            InvalidRequest, NotImplemented {
892
        logCrud.info("getChecksum");
893
        throw new NotImplemented("1000", "This method not yet implemented.");
894
    }
895

    
896
    /**
897
     * get the checksum for a document.  NOT IMPLEMENTED
898
     */
899
    public Checksum getChecksum(AuthToken token, Identifier guid, 
900
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
901
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
902
        logCrud.info("getChecksum");
903
        throw new NotImplemented("1000", "This method not yet implemented.");
904
    }
905

    
906
    /**
907
     * get log records.  
908
     */
909
    public Log getLogRecords(AuthToken token, Date fromDate, Date toDate, Event event)
910
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
911
            NotImplemented 
912
    {
913
        System.out.println("=================== Getting log records ===================");
914
        System.out.println("Current server time is: " + new Date());
915
        if(fromDate != null)
916
        {
917
          System.out.println("query start time is " + fromDate);
918
        }
919
        if(toDate != null)
920
        {
921
          System.out.println("query end time is " + toDate);
922
        }
923
        Log log = new Log();
924
        Vector<LogEntry> logs = new Vector<LogEntry>();
925
        IdentifierManager im = IdentifierManager.getInstance();
926
        EventLog el = EventLog.getInstance();
927
        if(fromDate == null)
928
        {
929
            System.out.println("setting fromdate from null");
930
            fromDate = new Date(1);
931
        }
932
        if(toDate == null)
933
        {
934
            System.out.println("setting todate from null");
935
            toDate = new Date();
936
        }
937
        
938
        System.out.println("fromDate: " + fromDate);
939
        System.out.println("toDate: " + toDate);
940
        
941
        String report = el.getReport(null, null, null, null, 
942
                new java.sql.Timestamp(fromDate.getTime()), 
943
                new java.sql.Timestamp(toDate.getTime()));
944
        
945
        //System.out.println("report: " + report);
946
        
947
        String logEntry = "<logEntry>";
948
        String endLogEntry = "</logEntry>";
949
        int startIndex = 0;
950
        int foundIndex = report.indexOf(logEntry, startIndex);
951
        while(foundIndex != -1)
952
        {
953
            //parse out each entry
954
            int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
955
            String entry = report.substring(foundIndex, endEntryIndex);
956
            //System.out.println("entry: " + entry);
957
            startIndex = endEntryIndex + endLogEntry.length();
958
            foundIndex = report.indexOf(logEntry, startIndex);
959
            
960
            String entryId = getLogEntryField("entryid", entry);
961
            String ipAddress = getLogEntryField("ipAddress", entry);
962
            String principal = getLogEntryField("principal", entry);
963
            String docid = getLogEntryField("docid", entry);
964
            String eventS = getLogEntryField("event", entry);
965
            String dateLogged = getLogEntryField("dateLogged", entry);
966
            
967
            LogEntry le = new LogEntry();
968
            
969
            Event e = Event.convert(eventS);
970
            if(e == null)
971
            { //skip any events that are not Dataone Crud events
972
                continue;
973
            }
974
            le.setEvent(e);
975
            Identifier entryid = new Identifier();
976
            entryid.setValue(entryId);
977
            le.setEntryId(entryid);
978
            Identifier identifier = new Identifier();
979
            try
980
            {
981
                //System.out.println("converting docid '" + docid + "' to a guid.");
982
                if(docid == null || docid.trim().equals("") || docid.trim().equals("null"))
983
                {
984
                    continue;
985
                }
986
                docid = docid.substring(0, docid.lastIndexOf("."));
987
                identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
988
            }
989
            catch(Exception ex)
990
            { //try to get the guid, if that doesn't work, just use the local id
991
                //throw new ServiceFailure("1030", "Error getting guid for localId " + 
992
                //        docid + ": " + ex.getMessage());\
993
                
994
                //skip it if the guid can't be found
995
                continue;
996
            }
997
            
998
            le.setIdentifier(identifier);
999
            le.setIpAddress(ipAddress);
1000
            Calendar c = Calendar.getInstance();
1001
            String year = dateLogged.substring(0, 4);
1002
            String month = dateLogged.substring(5, 7);
1003
            String date = dateLogged.substring(8, 10);
1004
            //System.out.println("year: " + year + " month: " + month + " day: " + date);
1005
            c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
1006
            Date logDate = c.getTime();
1007
            le.setDateLogged(logDate);
1008
            NodeReference memberNode = new NodeReference();
1009
            memberNode.setValue(ipAddress);
1010
            le.setMemberNode(memberNode);
1011
            Principal princ = new Principal();
1012
            princ.setValue(principal);
1013
            le.setPrincipal(princ);
1014
            le.setUserAgent("metacat/RESTService");
1015
            
1016
            if(event == null)
1017
            {
1018
                logs.add(le);
1019
            }
1020
            
1021
            if(event != null &&
1022
               e.toString().toLowerCase().trim().equals(event.toString().toLowerCase().trim()))
1023
            {
1024
              logs.add(le);
1025
            }
1026
        }
1027
        
1028
        log.setLogEntryList(logs);
1029
        logCrud.info("getLogRecords");
1030
        return log;
1031
    }
1032
    
1033
    /**
1034
     * parse a logEntry and get the relavent field from it
1035
     * @param fieldname
1036
     * @param entry
1037
     * @return
1038
     */
1039
    private String getLogEntryField(String fieldname, String entry)
1040
    {
1041
        String begin = "<" + fieldname + ">";
1042
        String end = "</" + fieldname + ">";
1043
        //System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
1044
        String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
1045
        //System.out.println("entry " + fieldname + " : " + s);
1046
        return s;
1047
    }
1048

    
1049
    /**
1050
     * get the system metadata for a document with a specified guid.
1051
     */
1052
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
1053
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1054
            InvalidRequest, NotImplemented {
1055
        
1056
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
1057
        
1058
        // Retrieve the session information from the AuthToken
1059
        // If the session is expired, then the user is 'public'
1060
        final SessionData sessionData = getSessionData(token);
1061
                
1062
        try {
1063
            IdentifierManager im = IdentifierManager.getInstance();
1064
            final String localId = im.getSystemMetadataLocalId(guid.getValue());
1065
            
1066
            // Read system metadata from metacat's db
1067
            final InputStreamFromOutputStream<String> objectStream = 
1068
                new InputStreamFromOutputStream<String>() {
1069
                
1070
                @Override
1071
                public String produce(final OutputStream dataSink) throws Exception {
1072
                    try {
1073
                        handler.readFromMetacat(metacatUrl, null, 
1074
                                dataSink, localId, "xml",
1075
                                sessionData.getUserName(), 
1076
                                sessionData.getGroupNames(), true, params);
1077
                    } catch (PropertyNotFoundException e) {
1078
                        e.printStackTrace();
1079
                        throw new ServiceFailure("1030", "Property not found while reading system metadata from metacat: " + e.getMessage());
1080
                    } catch (ClassNotFoundException e) {
1081
                        e.printStackTrace();
1082
                        throw new ServiceFailure("1030", "Class not found while reading system metadata from metacat: " + e.getMessage());
1083
                    } catch (IOException e) {
1084
                        e.printStackTrace();
1085
                        throw new ServiceFailure("1030", "IOException while reading system metadata from metacat: " + e.getMessage());
1086
                    } catch (SQLException e) {
1087
                        e.printStackTrace();
1088
                        throw new ServiceFailure("1030", "SQLException while reading system metadata from metacat: " + e.getMessage());
1089
                    } catch (McdbException e) {
1090
                        e.printStackTrace();
1091
                        throw new ServiceFailure("1030", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
1092
                    } catch (ParseLSIDException e) {
1093
                        e.printStackTrace();
1094
                        throw new NotFound("1020", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
1095
                    } catch (InsufficientKarmaException e) {
1096
                        e.printStackTrace();
1097
                        throw new NotAuthorized("1000", "User not authorized for get() on system metadata: " + e.getMessage());
1098
                    }
1099

    
1100
                    return "Completed";
1101
                }
1102
            };
1103
            
1104
            // Deserialize the xml to create a SystemMetadata object
1105
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
1106
            String username = "public";
1107
            if(sessionData != null)
1108
            {
1109
                username = sessionData.getUserName();
1110
            }
1111
            EventLog.getInstance().log(metacatUrl,
1112
                    username, im.getLocalId(guid.getValue()), "read");
1113
            logCrud.info("getSystemMetadata localId: " + localId + " guid:" + guid.getValue());
1114
            return sysmeta;
1115
            
1116
        } catch (McdbDocNotFoundException e) {
1117
            //e.printStackTrace();
1118
            throw new NotFound("1000", e.getMessage());
1119
        }                
1120
    }
1121
    
1122
    /**
1123
     * parse the date in the systemMetadata
1124
     * @param s
1125
     * @return
1126
     * @throws Exception
1127
     */
1128
    public Date parseDate(String s)
1129
      throws Exception
1130
    {
1131
        Date d = null;
1132
        int tIndex = s.indexOf("T");
1133
        int zIndex = s.indexOf("Z");
1134
        if(tIndex != -1 && zIndex != -1)
1135
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
1136
            //System.out.println("original date: " + s);
1137
            
1138
            String date = s.substring(0, tIndex);
1139
            String year = date.substring(0, date.indexOf("-"));
1140
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
1141
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
1142
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
1143
                    " month: " + new Integer(month).intValue() + " day: " + 
1144
                    new Integer(day).intValue());
1145
            */
1146
            String time = s.substring(tIndex + 1, zIndex);
1147
            String hour = time.substring(0, time.indexOf(":"));
1148
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
1149
            String seconds = "00";
1150
            String milliseconds = "00";
1151
            if(time.indexOf(".") != -1)
1152
            {
1153
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
1154
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
1155
            }
1156
            else
1157
            {
1158
                seconds = time.substring(time.lastIndexOf(":") + 1, time.length());
1159
            }
1160
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
1161
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
1162
                    new Integer(seconds).intValue() + " milli: " + 
1163
                    new Integer(milliseconds).intValue());*/
1164
            
1165
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
1166
            Calendar c = Calendar.getInstance(/*TimeZone.getTimeZone("GMT-0")*/TimeZone.getDefault());
1167
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
1168
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
1169
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
1170
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
1171
            d = new Date(c.getTimeInMillis());
1172
            //System.out.println("d: " + d);
1173
            return d;
1174
        }
1175
        else
1176
        {  //if it's not in the expected format, try the formatter
1177
            return DateFormat.getDateTimeInstance().parse(s);
1178
        }
1179
    }
1180

    
1181
    /*
1182
     * Look up the information on the session using the token provided in
1183
     * the AuthToken.  The Session should have all relevant user information.
1184
     * If the session has expired or is invalid, the 'public' session will
1185
     * be returned, giving the user anonymous access.
1186
     */
1187
    public static SessionData getSessionData(AuthToken token) {
1188
        SessionData sessionData = null;
1189
        String sessionId = "PUBLIC";
1190
        if (token != null) {
1191
            sessionId = token.getToken();
1192
        }
1193
        
1194
        // if the session id is registered in SessionService, get the
1195
        // SessionData for it. Otherwise, use the public session.
1196
        //System.out.println("sessionid: " + sessionId);
1197
        if (sessionId != null &&
1198
            !sessionId.toLowerCase().equals("public") &&
1199
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1200
        {
1201
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1202
        } else {
1203
            sessionData = SessionService.getInstance().getPublicSession();
1204
        }
1205
        
1206
        return sessionData;
1207
    }
1208

    
1209
    /** 
1210
     * Determine if a given object should be treated as an XML science metadata
1211
     * object. 
1212
     * 
1213
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1214
     * 
1215
     * @param sysmeta the SystemMetadata describig the object
1216
     * @return true if the object should be treated as science metadata
1217
     */
1218
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1219
        boolean scimeta = false;
1220
        switch (sysmeta.getObjectFormat()) {
1221
            case EML_2_1_0: scimeta = true; break;
1222
            case EML_2_0_1: scimeta = true; break;
1223
            case EML_2_0_0: scimeta = true; break;
1224
            case FGDC_STD_001_1_1999: scimeta = true; break;
1225
            case FGDC_STD_001_1998: scimeta = true; break;
1226
            case NCML_2_2: scimeta = true; break;
1227
        }
1228
        
1229
        return scimeta;
1230
    }
1231

    
1232
    /**
1233
     * insert a data doc
1234
     * @param object
1235
     * @param guid
1236
     * @param sessionData
1237
     * @throws ServiceFailure
1238
     */
1239
    private void insertDataObject(InputStream object, Identifier guid, 
1240
            SessionData sessionData) throws ServiceFailure {
1241
        
1242
        String username = "public";
1243
        String[] groups = null;
1244
        if(sessionData != null)
1245
        {
1246
          username = sessionData.getUserName();
1247
          groups = sessionData.getGroupNames();
1248
        }
1249

    
1250
        // generate guid/localId pair for object
1251
        logMetacat.debug("Generating a guid/localId mapping");
1252
        IdentifierManager im = IdentifierManager.getInstance();
1253
        String localId = im.generateLocalId(guid.getValue(), 1);
1254

    
1255
        try {
1256
            logMetacat.debug("Case DATA: starting to write to disk.");
1257
            if (DocumentImpl.getDataFileLockGrant(localId)) {
1258
    
1259
                // Save the data file to disk using "localId" as the name
1260
                try {
1261
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
1262
    
1263
                    File dataDirectory = new File(datafilepath);
1264
                    dataDirectory.mkdirs();
1265
    
1266
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
1267
    
1268
                    // TODO: Check that the file size matches SystemMetadata
1269
                    //                        long size = newFile.length();
1270
                    //                        if (size == 0) {
1271
                    //                            throw new IOException("Uploaded file is 0 bytes!");
1272
                    //                        }
1273
    
1274
                    // Register the file in the database (which generates an exception
1275
                    // if the localId is not acceptable or other untoward things happen
1276
                    try {
1277
                        logMetacat.debug("Registering document...");
1278
                        DocumentImpl.registerDocument(localId, "BIN", localId,
1279
                                username, groups);
1280
                        logMetacat.debug("Registration step completed.");
1281
                    } catch (SQLException e) {
1282
                        //newFile.delete();
1283
                        logMetacat.debug("SQLE: " + e.getMessage());
1284
                        e.printStackTrace(System.out);
1285
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1286
                    } catch (AccessionNumberException e) {
1287
                        //newFile.delete();
1288
                        logMetacat.debug("ANE: " + e.getMessage());
1289
                        e.printStackTrace(System.out);
1290
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1291
                    } catch (Exception e) {
1292
                        //newFile.delete();
1293
                        logMetacat.debug("Exception: " + e.getMessage());
1294
                        e.printStackTrace(System.out);
1295
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1296
                    }
1297
    
1298
                    logMetacat.debug("Logging the creation event.");
1299
                    EventLog.getInstance().log(metacatUrl,
1300
                            username, localId, "create");
1301
    
1302
                    // Schedule replication for this data file
1303
                    logMetacat.debug("Scheduling replication.");
1304
                    ForceReplicationHandler frh = new ForceReplicationHandler(
1305
                            localId, "create", false, null);
1306
    
1307
                } catch (PropertyNotFoundException e) {
1308
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1309
                }
1310
    
1311
            }
1312
        } catch (Exception e) {
1313
            // Could not get a lock on the document, so we can not update the file now
1314
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1315
        }
1316
    }
1317

    
1318
    /**
1319
     * write a file to a stream
1320
     * @param dir
1321
     * @param fileName
1322
     * @param data
1323
     * @return
1324
     * @throws ServiceFailure
1325
     */
1326
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1327
        throws ServiceFailure {
1328
        
1329
        File newFile = new File(dir, fileName);
1330
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1331

    
1332
        try {
1333
            if (newFile.createNewFile()) {
1334
                // write data stream to desired file
1335
                OutputStream os = new FileOutputStream(newFile);
1336
                long length = IOUtils.copyLarge(data, os);
1337
                os.flush();
1338
                os.close();
1339
            } else {
1340
                logMetacat.debug("File creation failed, or file already exists.");
1341
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1342
            }
1343
        } catch (FileNotFoundException e) {
1344
            logMetacat.debug("FNF: " + e.getMessage());
1345
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1346
                    + e.getMessage());
1347
        } catch (IOException e) {
1348
            logMetacat.debug("IOE: " + e.getMessage());
1349
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1350
                    + " " + e.getMessage());
1351
        }
1352

    
1353
        return newFile;
1354
    }
1355
    
1356
    private static Date getDateInTimeZone(Date currentDate, String timeZoneId)
1357
    {
1358
        TimeZone tz = TimeZone.getTimeZone(timeZoneId);
1359
        Calendar mbCal = new GregorianCalendar(TimeZone.getTimeZone(timeZoneId));
1360
        mbCal.setTimeInMillis(currentDate.getTime());
1361

    
1362
        Calendar cal = Calendar.getInstance();
1363
        cal.set(Calendar.YEAR, mbCal.get(Calendar.YEAR));
1364
        cal.set(Calendar.MONTH, mbCal.get(Calendar.MONTH));
1365
        cal.set(Calendar.DAY_OF_MONTH, mbCal.get(Calendar.DAY_OF_MONTH));
1366
        cal.set(Calendar.HOUR_OF_DAY, mbCal.get(Calendar.HOUR_OF_DAY));
1367
        cal.set(Calendar.MINUTE, mbCal.get(Calendar.MINUTE));
1368
        cal.set(Calendar.SECOND, mbCal.get(Calendar.SECOND));
1369
        cal.set(Calendar.MILLISECOND, mbCal.get(Calendar.MILLISECOND));
1370

    
1371
        return cal.getTime();
1372
    }
1373

    
1374
    /**
1375
     * insert a systemMetadata doc, return the localId of the sysmeta
1376
     */
1377
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1378
        throws ServiceFailure 
1379
    {
1380
        logMetacat.debug("Starting to insert SystemMetadata...");
1381
    
1382
        // generate guid/localId pair for sysmeta
1383
        Identifier sysMetaGuid = new Identifier();
1384
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1385
        sysmeta.setDateSysMetadataModified(new Date());
1386
        System.out.println("****inserting new system metadata with modified date " + sysmeta.getDateSysMetadataModified());
1387

    
1388
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
1389
        //System.out.println("sysmeta: " + xml);
1390
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
1391
        System.out.println("sysmeta inserted with localId " + localId);
1392
        //insert the system metadata doc id into the identifiers table to 
1393
        //link it to the data or metadata document
1394
        IdentifierManager.getInstance().createSystemMetadataMapping(
1395
                sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
1396
        return localId;
1397
    }
1398
    
1399
    /**
1400
     * update a systemMetadata doc
1401
     */
1402
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1403
      throws ServiceFailure
1404
    {
1405
        try
1406
        {
1407
            String smId = IdentifierManager.getInstance().getSystemMetadataLocalId(sm.getIdentifier().getValue());
1408
            sm.setDateSysMetadataModified(new Date());
1409
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
1410
            Identifier id = new Identifier();
1411
            id.setValue(smId);
1412
            String localId = updateDocument(xml, id, null, sessionData);
1413
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
1414
        }
1415
        catch(Exception e)
1416
        {
1417
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
1418
        }
1419
    }
1420
    
1421
    /**
1422
     * insert a document
1423
     * NOTE: this method shouldn't be used from the update or create() methods.  
1424
     * we shouldn't be putting the science metadata or data objects into memory.
1425
     */
1426
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1427
        throws ServiceFailure
1428
    {
1429
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
1430
    }
1431
    
1432
    /**
1433
     * insert a document from a stream
1434
     */
1435
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1436
      throws IOException, ServiceFailure
1437
    {
1438
        //HACK: change this eventually.  we should not be converting the stream to a string
1439
        String xml = IOUtils.toString(is);
1440
        return insertDocument(xml, guid, sessionData);
1441
    }
1442
    
1443
    /**
1444
     * update a document
1445
     * NOTE: this method shouldn't be used from the update or create() methods.  
1446
     * we shouldn't be putting the science metadata or data objects into memory.
1447
     */
1448
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1449
        throws ServiceFailure
1450
    {
1451
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
1452
    }
1453
    
1454
    /**
1455
     * update a document from a stream
1456
     */
1457
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1458
      throws IOException, ServiceFailure
1459
    {
1460
        //HACK: change this eventually.  we should not be converting the stream to a string
1461
        String xml = IOUtils.toString(is);
1462
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
1463
        IdentifierManager im = IdentifierManager.getInstance();
1464
        if(guid != null)
1465
        {
1466
          im.createMapping(guid.getValue(), localId);
1467
        }
1468
        return localId;
1469
    }
1470
    
1471
    /**
1472
     * insert a document, return the id of the document that was inserted
1473
     */
1474
    protected String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
1475
        throws ServiceFailure {
1476
        logMetacat.debug("Starting to insert xml document...");
1477
        IdentifierManager im = IdentifierManager.getInstance();
1478

    
1479
        // generate guid/localId pair for sysmeta
1480
        String localId = null;
1481
        if(insertOrUpdate.equals("insert"))
1482
        {
1483
            localId = im.generateLocalId(guid.getValue(), 1);
1484
        }
1485
        else
1486
        {
1487
            //localid should already exist in the identifier table, so just find it
1488
            try
1489
            {
1490
                localId = im.getLocalId(guid.getValue());
1491
                //increment the revision
1492
                String docid = localId.substring(0, localId.lastIndexOf("."));
1493
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1494
                int rev = new Integer(revS).intValue();
1495
                rev++;
1496
                docid = docid + "." + rev;
1497
                localId = docid;
1498
            }
1499
            catch(McdbDocNotFoundException e)
1500
            {
1501
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1502
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1503
            }
1504
        }
1505
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1506
                localId);
1507

    
1508
        String[] action = new String[1];
1509
        action[0] = insertOrUpdate;
1510
        params.put("action", action);
1511
        String[] docid = new String[1];
1512
        docid[0] = localId;
1513
        params.put("docid", docid);
1514
        String[] doctext = new String[1];
1515
        doctext[0] = xml;
1516
        logMetacat.debug(doctext[0]);
1517
        params.put("doctext", doctext);
1518
        
1519
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1520
        // onto output stream, or alternatively, capture that and parse it to 
1521
        // generate the right exceptions
1522
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1523
        //PrintWriter pw = new PrintWriter(output);
1524
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1525
                            null, params, sessionData.getUserName(), sessionData.getGroupNames());
1526
        //String outputS = new String(output.toByteArray());
1527
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1528
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1529
        return localId;
1530
    }
1531
    
1532
    /**
1533
     * serialize a system metadata doc
1534
     * @param sysmeta
1535
     * @return
1536
     * @throws ServiceFailure
1537
     */
1538
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1539
        throws ServiceFailure {
1540
        IBindingFactory bfact;
1541
        ByteArrayOutputStream sysmetaOut = null;
1542
        try {
1543
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1544
            IMarshallingContext mctx = bfact.createMarshallingContext();
1545
            sysmetaOut = new ByteArrayOutputStream();
1546
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1547
        } catch (JiBXException e) {
1548
            e.printStackTrace();
1549
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1550
        }
1551
        
1552
        return sysmetaOut;
1553
    }
1554
    
1555
    /**
1556
     * deserialize a system metadata doc
1557
     * @param xml
1558
     * @return
1559
     * @throws ServiceFailure
1560
     */
1561
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1562
        throws ServiceFailure {
1563
        try {
1564
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1565
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1566
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1567
            return sysmeta;
1568
        } catch (JiBXException e) {
1569
            e.printStackTrace();
1570
            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1571
        }    
1572
    }
1573
    
1574
    /**
1575
     * produce an md5 checksum for item
1576
     */
1577
    private String checksum(InputStream is)
1578
      throws Exception
1579
    {        
1580
        byte[] buffer = new byte[1024];
1581
        MessageDigest complete = MessageDigest.getInstance("MD5");
1582
        int numRead;
1583
        
1584
        do 
1585
        {
1586
          numRead = is.read(buffer);
1587
          if (numRead > 0) 
1588
          {
1589
            complete.update(buffer, 0, numRead);
1590
          }
1591
        } while (numRead != -1);
1592
        
1593
        
1594
        return getHex(complete.digest());
1595
    }
1596
    
1597
    /**
1598
     * convert a byte array to a hex string
1599
     */
1600
    private static String getHex( byte [] raw ) 
1601
    {
1602
        final String HEXES = "0123456789ABCDEF";
1603
        if ( raw == null ) {
1604
          return null;
1605
        }
1606
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
1607
        for ( final byte b : raw ) {
1608
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
1609
             .append(HEXES.charAt((b & 0x0F)));
1610
        }
1611
        return hex.toString();
1612
    }
1613
    
1614
    /**
1615
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
1616
     * a proper date object
1617
     * @param date
1618
     * @return
1619
     */
1620
    private Date parseMetacatDate(String date)
1621
    {
1622
        String year = date.substring(0, 4);
1623
        String month = date.substring(5, 7);
1624
        String day = date.substring(8, 10);
1625
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
1626
        c.set(new Integer(year).intValue(), 
1627
              new Integer(month).intValue(), 
1628
              new Integer(day).intValue());
1629
        System.out.println("time in parseMetacatDate: " + c.getTime());
1630
        return c.getTime();
1631
    }
1632
    
1633
    /**
1634
     * find the size (in bytes) of a stream
1635
     * @param is
1636
     * @return
1637
     * @throws IOException
1638
     */
1639
    private long sizeOfStream(InputStream is)
1640
        throws IOException
1641
    {
1642
        long size = 0;
1643
        byte[] b = new byte[1024];
1644
        int numread = is.read(b, 0, 1024);
1645
        while(numread != -1)
1646
        {
1647
            size += numread;
1648
            numread = is.read(b, 0, 1024);
1649
        }
1650
        return size;
1651
    }
1652
    
1653
    /**
1654
     * create system metadata with a specified id, doc and format
1655
     */
1656
    private SystemMetadata createSystemMetadata(String localId, AuthToken token)
1657
      throws Exception
1658
    {
1659
        IdentifierManager im = IdentifierManager.getInstance();
1660
        Hashtable<String, Object> docInfo = im.getDocumentInfo(localId);
1661
        
1662
        //get the document text
1663
        int rev = im.getLatestRevForLocalId(localId);
1664
        Identifier identifier = new Identifier();
1665
        identifier.setValue(im.getGUID(localId, rev));
1666
        InputStream is = this.get(token, identifier);
1667
        
1668
        SystemMetadata sm = new SystemMetadata();
1669
        //set the id
1670
        sm.setIdentifier(identifier);
1671
        
1672
        //set the object format
1673
        String doctype = (String)docInfo.get("doctype");
1674
        ObjectFormat format = ObjectFormat.convert((String)docInfo.get("doctype"));
1675
        if(format == null)
1676
        {
1677
            if(doctype.trim().equals("BIN"))
1678
            {
1679
                format = ObjectFormat.APPLICATIONOCTETSTREAM;
1680
            }
1681
            else
1682
            {
1683
                format = ObjectFormat.convert("text/plain");
1684
            }
1685
        }
1686
        sm.setObjectFormat(format);
1687
        
1688
        //create the checksum
1689
        String checksumS = checksum(is);
1690
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
1691
        Checksum checksum = new Checksum();
1692
        checksum.setValue(checksumS);
1693
        checksum.setAlgorithm(ca);
1694
        sm.setChecksum(checksum);
1695
        
1696
        //set the size
1697
        is = this.get(token, identifier);
1698
        sm.setSize(sizeOfStream(is));
1699
        
1700
        //submitter
1701
        Principal p = new Principal();
1702
        p.setValue((String)docInfo.get("user_owner"));
1703
        sm.setSubmitter(p);
1704
        sm.setRightsHolder(p);
1705
        try
1706
        {
1707
            Date dateCreated = parseMetacatDate((String)docInfo.get("date_created"));
1708
            sm.setDateUploaded(dateCreated);
1709
            Date dateUpdated = parseMetacatDate((String)docInfo.get("date_updated"));
1710
            sm.setDateSysMetadataModified(dateUpdated);
1711
        }
1712
        catch(Exception e)
1713
        {
1714
            System.out.println("POSSIBLE ERROR: couldn't parse a date: " + e.getMessage());
1715
            Date dateCreated = new Date();
1716
            sm.setDateUploaded(dateCreated);
1717
            Date dateUpdated = new Date();
1718
            sm.setDateSysMetadataModified(dateUpdated);
1719
        }
1720
        NodeReference nr = new NodeReference();
1721
        nr.setValue("metacat");
1722
        sm.setOriginMemberNode(nr);
1723
        sm.setAuthoritativeMemberNode(nr);
1724
        return sm;
1725
    }
1726
}
(1-1/2)