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
        System.out.println("#####################Create!");
272

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

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

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

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

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

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

    
791
    /**
792
     * Delete a document.  NOT IMPLEMENTED
793
     */
794
    public Identifier delete(AuthToken token, Identifier guid)
795
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
796
            NotImplemented {
797
        logCrud.info("delete");
798
        throw new NotImplemented("1000", "This method not yet implemented.");
799
    }
800

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

    
831
            final InputStreamFromOutputStream<String> objectStream = 
832
                new InputStreamFromOutputStream<String>() {
833
                
834
                @Override
835
                public String produce(final OutputStream dataSink) throws Exception {
836

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

    
876
                    return "Completed";
877
                }
878
            };
879
            String username = "public";
880
            if(sessionData != null)
881
            {
882
                username = sessionData.getUserName();
883
            }
884
            
885
            EventLog.getInstance().log(metacatUrl,
886
                    username, im.getLocalId(guid.getValue()), "read");
887
            logCrud.info("get localId:" + localId + " guid:" + guid.getValue());
888
            return objectStream;
889

    
890
        } catch (McdbDocNotFoundException e) {
891
            throw new NotFound("1020", e.getMessage());
892
        }
893
    }
894

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

    
905
    /**
906
     * get the checksum for a document.  NOT IMPLEMENTED
907
     */
908
    public Checksum getChecksum(AuthToken token, Identifier guid, 
909
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
910
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
911
        logCrud.info("getChecksum");
912
        throw new NotImplemented("1000", "This method not yet implemented.");
913
    }
914

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

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

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

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

    
1218
    /** 
1219
     * Determine if a given object should be treated as an XML science metadata
1220
     * object. 
1221
     * 
1222
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1223
     * 
1224
     * @param sysmeta the SystemMetadata describig the object
1225
     * @return true if the object should be treated as science metadata
1226
     */
1227
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1228
        boolean scimeta = false;
1229
        switch (sysmeta.getObjectFormat()) {
1230
            case EML_2_1_0: scimeta = true; break;
1231
            case EML_2_0_1: scimeta = true; break;
1232
            case EML_2_0_0: scimeta = true; break;
1233
            case FGDC_STD_001_1_1999: scimeta = true; break;
1234
            case FGDC_STD_001_1998: scimeta = true; break;
1235
            case NCML_2_2: scimeta = true; break;
1236
        }
1237
        
1238
        return scimeta;
1239
    }
1240

    
1241
    /**
1242
     * insert a data doc
1243
     * @param object
1244
     * @param guid
1245
     * @param sessionData
1246
     * @throws ServiceFailure
1247
     */
1248
    private void insertDataObject(InputStream object, Identifier guid, 
1249
            SessionData sessionData) throws ServiceFailure {
1250
        
1251
        String username = "public";
1252
        String[] groups = null;
1253
        if(sessionData != null)
1254
        {
1255
          username = sessionData.getUserName();
1256
          groups = sessionData.getGroupNames();
1257
        }
1258

    
1259
        // generate guid/localId pair for object
1260
        logMetacat.debug("Generating a guid/localId mapping");
1261
        IdentifierManager im = IdentifierManager.getInstance();
1262
        String localId = im.generateLocalId(guid.getValue(), 1);
1263

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

    
1327
    /**
1328
     * write a file to a stream
1329
     * @param dir
1330
     * @param fileName
1331
     * @param data
1332
     * @return
1333
     * @throws ServiceFailure
1334
     */
1335
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1336
        throws ServiceFailure {
1337
        
1338
        File newFile = new File(dir, fileName);
1339
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1340

    
1341
        try {
1342
            if (newFile.createNewFile()) {
1343
                // write data stream to desired file
1344
                OutputStream os = new FileOutputStream(newFile);
1345
                long length = IOUtils.copyLarge(data, os);
1346
                os.flush();
1347
                os.close();
1348
            } else {
1349
                logMetacat.debug("File creation failed, or file already exists.");
1350
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1351
            }
1352
        } catch (FileNotFoundException e) {
1353
            logMetacat.debug("FNF: " + e.getMessage());
1354
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1355
                    + e.getMessage());
1356
        } catch (IOException e) {
1357
            logMetacat.debug("IOE: " + e.getMessage());
1358
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1359
                    + " " + e.getMessage());
1360
        }
1361

    
1362
        return newFile;
1363
    }
1364
    
1365
    private static Date getDateInTimeZone(Date currentDate, String timeZoneId)
1366
    {
1367
        TimeZone tz = TimeZone.getTimeZone(timeZoneId);
1368
        Calendar mbCal = new GregorianCalendar(TimeZone.getTimeZone(timeZoneId));
1369
        mbCal.setTimeInMillis(currentDate.getTime());
1370

    
1371
        Calendar cal = Calendar.getInstance();
1372
        cal.set(Calendar.YEAR, mbCal.get(Calendar.YEAR));
1373
        cal.set(Calendar.MONTH, mbCal.get(Calendar.MONTH));
1374
        cal.set(Calendar.DAY_OF_MONTH, mbCal.get(Calendar.DAY_OF_MONTH));
1375
        cal.set(Calendar.HOUR_OF_DAY, mbCal.get(Calendar.HOUR_OF_DAY));
1376
        cal.set(Calendar.MINUTE, mbCal.get(Calendar.MINUTE));
1377
        cal.set(Calendar.SECOND, mbCal.get(Calendar.SECOND));
1378
        cal.set(Calendar.MILLISECOND, mbCal.get(Calendar.MILLISECOND));
1379

    
1380
        return cal.getTime();
1381
    }
1382

    
1383
    /**
1384
     * insert a systemMetadata doc, return the localId of the sysmeta
1385
     */
1386
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1387
        throws ServiceFailure 
1388
    {
1389
        logMetacat.debug("Starting to insert SystemMetadata...");
1390
    
1391
        // generate guid/localId pair for sysmeta
1392
        Identifier sysMetaGuid = new Identifier();
1393
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1394
        sysmeta.setDateSysMetadataModified(new Date());
1395
        System.out.println("****inserting new system metadata with modified date " + sysmeta.getDateSysMetadataModified());
1396

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

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

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