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

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

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

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

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

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

    
94
    private MetacatHandler handler;
95
    private Hashtable<String, String[]> params;
96
    private Logger logMetacat = null;
97
    private Logger logCrud = null;
98
    
99
    private String metacatUrl;
100

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

    
142
        handler = new MetacatHandler(new Timer());
143

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

    
266
        logMetacat.debug("Starting CrudService.create()...");
267
        
268
        // authenticate & get user info
269
        SessionData sessionData = getSessionData(token);
270
        String username = sessionData.getUserName();
271
        String[] groups = sessionData.getGroupNames();
272
        String localId = null;
273

    
274
        if (username == null || username.equals("public"))
275
        {
276
            throw new NotAuthorized("1000", "User " + username + " is not authorized to create content." +
277
                    "  If you are not logged in, please do so and retry the request.");
278
        }
279
        
280
        // verify that guid == SystemMetadata.getIdentifier()
281
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
282
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
283
            throw new InvalidSystemMetadata("1180", 
284
                "GUID in method call does not match GUID in system metadata.");
285
        }
286

    
287
        logMetacat.debug("Checking if identifier exists...");
288
        // Check that the identifier does not already exist
289
        IdentifierManager im = IdentifierManager.getInstance();
290
        if (im.identifierExists(guid.getValue())) {
291
            throw new IdentifierNotUnique("1120", 
292
                "GUID is already in use by an existing object.");
293
        }
294

    
295
        // Check if we are handling metadata or data
296
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
297
        
298
        if (isScienceMetadata) {
299
            // CASE METADATA:
300
            try {
301
                this.insertDocument(object, guid, sessionData);
302
                localId = im.getLocalId(guid.getValue());
303
            } catch (IOException e) {
304
                String msg = "Could not create string from XML stream: " +
305
                    " " + e.getMessage();
306
                logMetacat.debug(msg);
307
                throw new ServiceFailure("1190", msg);
308
            } catch(Exception e) {
309
                String msg = "Unexpected error in CrudService.create: " + e.getMessage();
310
                logMetacat.debug(msg);
311
                throw new ServiceFailure("1190", msg);
312
            }
313
            
314

    
315
        } else {
316
            // DEFAULT CASE: DATA (needs to be checked and completed)
317
            insertDataObject(object, guid, sessionData);
318
            
319
        }
320

    
321
        // For Metadata and Data, insert the system metadata into the object store too
322
        insertSystemMetadata(sysmeta, sessionData);
323
        logMetacat.debug("Returning from CrudService.create()");
324
        EventLog.getInstance().log(metacatUrl,
325
                username, localId, "create");
326
        logCrud.info("create localId:" + localId + " guid:" + guid.getValue());
327
        return guid;
328
    }
329
    
330
    /**
331
     * update an existing object with a new object.  Change the system metadata
332
     * to reflect the changes and update it as well.
333
     */
334
    public Identifier update(AuthToken token, Identifier guid, 
335
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
336
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
337
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
338
            NotImplemented {
339
        try
340
        {
341
            SessionData sessionData = getSessionData(token);
342
            
343
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
344
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
345
            //change sm.old's obsoletedBy field 
346
            List l = sm.getObsoletedByList();
347
            l.add(guid);
348
            sm.setObsoletedByList(l);
349
            //update sm.old
350
            updateSystemMetadata(sm, sessionData);
351
            
352
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
353
            sysmeta.addObsolete(obsoletedGuid);
354
            //insert sm.new
355
            insertSystemMetadata(sysmeta, sessionData);
356
            
357
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
358
            if(isScienceMetadata)
359
            {
360
                //update the doc
361
                updateDocument(object, obsoletedGuid, guid, sessionData);
362
            }
363
            else
364
            {
365
                //update a data file, not xml
366
                insertDataObject(object, guid, sessionData);
367
            }
368
            
369
            IdentifierManager im = IdentifierManager.getInstance();
370
            String username = sessionData.getUserName();
371
            EventLog.getInstance().log(metacatUrl,
372
                    username, im.getLocalId(guid.getValue()), "update");
373
            logCrud.info("update localId:" + im.getLocalId(guid.getValue()) + " guid:" + guid.getValue());
374
            return guid;
375
        }
376
        catch(Exception e)
377
        {
378
            throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
379
        }
380
    }
381
    
382
    /**
383
     * set the permission on the document
384
     * @param token
385
     * @param principal
386
     * @param permission
387
     * @param permissionType
388
     * @param permissionOrder
389
     * @return
390
     */
391
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
392
            String permissionType, String permissionOrder)
393
      throws ServiceFailure
394
    {
395
        try
396
        {
397
            IdentifierManager im = IdentifierManager.getInstance();
398
            String docid = im.getLocalId(id.getValue());
399
            final SessionData sessionData = getSessionData(token);
400
            String permNum = "0";
401
            if(permission.equals("read"))
402
            {
403
                permNum = "4";
404
            }
405
            else if(permission.equals("write"))
406
            {
407
                permNum = "6";
408
            }
409
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
410
                    principal, permNum, permissionType, permissionOrder);
411
            
412
            String username = sessionData.getUserName();
413
            EventLog.getInstance().log(metacatUrl,
414
                    username, im.getLocalId(id.getValue()), "setAccess");
415
            logCrud.info("setAccess");
416
        }
417
        catch(Exception e)
418
        {
419
            e.printStackTrace();
420
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
421
        }
422
    }
423
    
424
    /**
425
     *  Retrieve the list of objects present on the MN that match the calling 
426
     *  parameters. This method is required to support the process of Member 
427
     *  Node synchronization. At a minimum, this method should be able to 
428
     *  return a list of objects that match:
429
     *  startTime <= SystemMetadata.dateSysMetadataModified
430
     *  but is expected to also support date range (by also specifying endTime), 
431
     *  and should also support slicing of the matching set of records by 
432
     *  indicating the starting index of the response (where 0 is the index 
433
     *  of the first item) and the count of elements to be returned.
434
     *  
435
     *  If startTime or endTime is null, the query is not restricted by that parameter.
436
     *  
437
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
438
     * @param token
439
     * @param startTime
440
     * @param endTime
441
     * @param objectFormat
442
     * @param replicaStatus
443
     * @param start
444
     * @param count
445
     * @return ObjectList
446
     * @throws NotAuthorized
447
     * @throws InvalidRequest
448
     * @throws NotImplemented
449
     * @throws ServiceFailure
450
     * @throws InvalidToken
451
     */
452
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
453
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
454
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
455
    {
456
      ObjectList ol = new ObjectList();
457
      final SessionData sessionData = getSessionData(token);
458
      try
459
      {
460
          params.clear();
461
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
462
          params.put("qformat", new String[] {"xml"});
463
          params.put("returnfield", new String[] {"size", "originMemberNode", 
464
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "checksum/@algorithm"});
465
          params.put("anyfield", new String[] {"%"});
466
          
467
          //System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
468
          //    " sessionid: " + sessionData.getId() + " params: " + params.toString());
469
          
470
          MetacatResultSet rs = handler.query(metacatUrl, params, sessionData.getUserName(), 
471
                  sessionData.getGroupNames(), sessionData.getId());
472
          List docs = rs.getDocuments();
473
          if(count == 1000)
474
          {
475
              count = docs.size();
476
          }
477
          
478
          //System.out.println("query returned " + count + " documents.");
479
          
480
          for(int i=start; i<count; i++)
481
          {
482
              //get the document from the result
483
              Document d = (Document)docs.get(i);
484
              //System.out.println("processing doc " + d.docid);
485
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
486
              if(returnedObjectFormat == null)
487
              {
488
                  continue;
489
              }
490
              if(objectFormat != null && !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
491
              { //make sure the objectFormat is the one specified
492
                  continue;
493
              }
494
              
495
              String dateSMM = d.getField("dateSysMetadataModified");
496
              if(dateSMM == null)
497
              {
498
                  continue;
499
              }
500
              Date dateSysMetadataModified = parseDate(dateSMM);
501
              int startDateComparison = 0;
502
              int endDateComparison = 0;
503
              if(startTime != null)
504
              {
505
                  startDateComparison = dateSysMetadataModified.compareTo(startTime);
506
              }
507
              
508
              if(endTime != null)
509
              {
510
                  endDateComparison = dateSysMetadataModified.compareTo(endTime);
511
              }
512
              
513
              if(startDateComparison < 0 || endDateComparison > 0)
514
              { //this date falls outside of the startTime and endTime params, so
515
                //skip it
516
                  continue;                  
517
              }
518
              
519
              ObjectInfo info = new ObjectInfo();
520
              //add the fields to the info object
521
              Checksum cs = new Checksum();
522
              cs.setValue(d.getField("checksum"));
523
              String csalg = d.getField("algorithm");
524
              if(csalg == null)
525
              {
526
                  csalg = "MD5";
527
              }
528
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
529
              cs.setAlgorithm(ca);
530
              info.setChecksum(cs);
531
              info.setDateSysMetadataModified(dateSysMetadataModified);
532
              Identifier id = new Identifier();
533
              id.setValue(d.getField("identifier"));
534
              info.setIdentifier(id);
535
              info.setObjectFormat(returnedObjectFormat);
536
              info.setSize(new Long(d.getField("size").trim()).longValue());
537
              //add the ObjectInfo to the ObjectList
538
              ol.addObjectInfo(info);
539
          }
540
      }
541
      catch(Exception e)
542
      {
543
          e.printStackTrace();
544
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
545
      }
546
      String username = sessionData.getUserName();
547
      EventLog.getInstance().log(metacatUrl,
548
              username, null, "read");
549
      logCrud.info("listObjects");
550
      //System.out.println("ol.size: " + ol.sizeObjectInfoList());
551
      ol.setCount(ol.sizeObjectInfoList());
552
      ol.setStart(0);
553
      ol.setTotal(ol.sizeObjectInfoList());
554
      return ol;
555
    }
556
    
557
    /**
558
     * Call listObjects with the default values for replicaStatus (true), start (0),
559
     * and count (1000).
560
     * @param token
561
     * @param startTime
562
     * @param endTime
563
     * @param objectFormat
564
     * @return
565
     * @throws NotAuthorized
566
     * @throws InvalidRequest
567
     * @throws NotImplemented
568
     * @throws ServiceFailure
569
     * @throws InvalidToken
570
     */
571
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
572
        ObjectFormat objectFormat)
573
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
574
    {
575
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
576
    }
577

    
578
    /**
579
     * Delete a document.  NOT IMPLEMENTED
580
     */
581
    public Identifier delete(AuthToken token, Identifier guid)
582
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
583
            NotImplemented {
584
        logCrud.info("delete");
585
        throw new NotImplemented("1000", "This method not yet implemented.");
586
    }
587

    
588
    /**
589
     * describe a document.  NOT IMPLEMENTED
590
     */
591
    public DescribeResponse describe(AuthToken token, Identifier guid)
592
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
593
            NotImplemented {
594
        logCrud.info("describe");
595
        throw new NotImplemented("1000", "This method not yet implemented.");
596
    }
597
    
598
    /**
599
     * get a document with a specified guid.
600
     */
601
    public InputStream get(AuthToken token, Identifier guid)
602
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
603
            NotImplemented {
604
        
605
        // Retrieve the session information from the AuthToken
606
        // If the session is expired, then the user is 'public'
607
        final SessionData sessionData = getSessionData(token);
608
        
609
        // Look up the localId for this global identifier
610
        IdentifierManager im = IdentifierManager.getInstance();
611
        try {
612
            final String localId = im.getLocalId(guid.getValue());
613

    
614
            final InputStreamFromOutputStream<String> objectStream = 
615
                new InputStreamFromOutputStream<String>() {
616
                
617
                @Override
618
                public String produce(final OutputStream dataSink) throws Exception {
619

    
620
                    try {
621
                        handler.readFromMetacat(metacatUrl, null, 
622
                                dataSink, localId, "xml",
623
                                sessionData.getUserName(), 
624
                                sessionData.getGroupNames(), true, params);
625
                    } catch (PropertyNotFoundException e) {
626
                        e.printStackTrace();
627
                        throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
628
                    } catch (ClassNotFoundException e) {
629
                        e.printStackTrace();
630
                        throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
631
                    } catch (IOException e) {
632
                        e.printStackTrace();
633
                        throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
634
                    } catch (SQLException e) {
635
                        e.printStackTrace();
636
                        throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
637
                    } catch (McdbException e) {
638
                        e.printStackTrace();
639
                        throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
640
                    } catch (ParseLSIDException e) {
641
                        e.printStackTrace();
642
                        throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
643
                    } catch (InsufficientKarmaException e) {
644
                        e.printStackTrace();
645
                        throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
646
                    }
647

    
648
                    return "Completed";
649
                }
650
            };
651
            
652
            String username = sessionData.getUserName();
653
            EventLog.getInstance().log(metacatUrl,
654
                    username, im.getLocalId(guid.getValue()), "read");
655
            logCrud.info("get localId:" + localId + " guid:" + guid.getValue());
656
            return objectStream;
657

    
658
        } catch (McdbDocNotFoundException e) {
659
            throw new NotFound("1020", e.getMessage());
660
        }
661
    }
662

    
663
    /**
664
     * get the checksum for a document.  NOT IMPLEMENTED
665
     */
666
    public Checksum getChecksum(AuthToken token, Identifier guid)
667
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
668
            InvalidRequest, NotImplemented {
669
        logCrud.info("getChecksum");
670
        throw new NotImplemented("1000", "This method not yet implemented.");
671
    }
672

    
673
    /**
674
     * get the checksum for a document.  NOT IMPLEMENTED
675
     */
676
    public Checksum getChecksum(AuthToken token, Identifier guid, 
677
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
678
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
679
        logCrud.info("getChecksum");
680
        throw new NotImplemented("1000", "This method not yet implemented.");
681
    }
682

    
683
    /**
684
     * get log records.  
685
     */
686
    public Log getLogRecords(AuthToken token, Date fromDate, Date toDate, Event event)
687
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
688
            NotImplemented 
689
    {
690
        Log log = new Log();
691
        Vector<LogEntry> logs = new Vector<LogEntry>();
692
        IdentifierManager im = IdentifierManager.getInstance();
693
        EventLog el = EventLog.getInstance();
694
        if(fromDate == null)
695
        {
696
            fromDate = new Date(1);
697
        }
698
        if(toDate == null)
699
        {
700
            toDate = new Date();
701
        }
702
        String report = el.getReport(null, null, null, null, 
703
                new java.sql.Timestamp(fromDate.getTime()), 
704
                new java.sql.Timestamp(toDate.getTime()));
705
        
706
        String logEntry = "<logEntry>";
707
        String endLogEntry = "</logEntry>";
708
        int startIndex = 0;
709
        int foundIndex = report.indexOf(logEntry, startIndex);
710
        while(foundIndex != -1)
711
        {
712
            //parse out each entry
713
            int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
714
            String entry = report.substring(foundIndex, endEntryIndex);
715
            //System.out.println("entry: " + entry);
716
            startIndex = endEntryIndex + endLogEntry.length();
717
            foundIndex = report.indexOf(logEntry, startIndex);
718
            
719
            String entryId = getLogEntryField("entryid", entry);
720
            String ipAddress = getLogEntryField("ipAddress", entry);
721
            String principal = getLogEntryField("principal", entry);
722
            String docid = getLogEntryField("docid", entry);
723
            String eventS = getLogEntryField("event", entry);
724
            String dateLogged = getLogEntryField("dateLogged", entry);
725
            
726
            LogEntry le = new LogEntry();
727
            
728
            Event e = Event.convert(eventS);
729
            if(e == null)
730
            { //skip any events that are not Dataone Crud events
731
                continue;
732
            }
733
            le.setEvent(e);
734
            Identifier entryid = new Identifier();
735
            entryid.setValue(entryId);
736
            le.setEntryId(entryid);
737
            Identifier identifier = new Identifier();
738
            try
739
            {
740
                identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
741
            }
742
            catch(Exception ex)
743
            { //try to get the guid, if that doesn't work, just use the local id
744
                identifier.setValue(docid);
745
            }
746
            
747
            le.setIdentifier(identifier);
748
            le.setIpAddress(ipAddress);
749
            Calendar c = Calendar.getInstance();
750
            String year = dateLogged.substring(0, 4);
751
            String month = dateLogged.substring(5, 7);
752
            String date = dateLogged.substring(8, 10);
753
            //System.out.println("year: " + year + " month: " + month + " day: " + date);
754
            c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
755
            Date logDate = c.getTime();
756
            le.setDateLogged(logDate);
757
            NodeReference memberNode = new NodeReference();
758
            memberNode.setValue(ipAddress);
759
            le.setMemberNode(memberNode);
760
            Principal princ = new Principal();
761
            princ.setValue(principal);
762
            le.setPrincipal(princ);
763
            le.setUserAgent("metacat/RESTService");
764
            
765
            if(event == null)
766
            {
767
                logs.add(le);
768
            }
769
            
770
            if(event != null &&
771
               e.toString().toLowerCase().trim().equals(event.toString().toLowerCase().trim()))
772
            {
773
              logs.add(le);
774
            }
775
        }
776
        
777
        log.setLogEntryList(logs);
778
        logCrud.info("getLogRecords");
779
        return log;
780
    }
781
    
782
    /**
783
     * parse a logEntry and get the relavent field from it
784
     * @param fieldname
785
     * @param entry
786
     * @return
787
     */
788
    private String getLogEntryField(String fieldname, String entry)
789
    {
790
        String begin = "<" + fieldname + ">";
791
        String end = "</" + fieldname + ">";
792
        //System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
793
        String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
794
        //System.out.println("entry " + fieldname + " : " + s);
795
        return s;
796
    }
797

    
798
    /**
799
     * get the system metadata for a document with a specified guid.
800
     */
801
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
802
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
803
            InvalidRequest, NotImplemented {
804
        
805
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
806
        
807
        // Retrieve the session information from the AuthToken
808
        // If the session is expired, then the user is 'public'
809
        final SessionData sessionData = getSessionData(token);
810
                
811
        try {
812
            IdentifierManager im = IdentifierManager.getInstance();
813
            final String localId = im.getSystemMetadataId(guid.getValue());
814
            
815
            // Read system metadata from metacat's db
816
            final InputStreamFromOutputStream<String> objectStream = 
817
                new InputStreamFromOutputStream<String>() {
818
                
819
                @Override
820
                public String produce(final OutputStream dataSink) throws Exception {
821
                    try {
822
                        handler.readFromMetacat(metacatUrl, null, 
823
                                dataSink, localId, "xml",
824
                                sessionData.getUserName(), 
825
                                sessionData.getGroupNames(), true, params);
826
                    } catch (PropertyNotFoundException e) {
827
                        e.printStackTrace();
828
                        throw new ServiceFailure("1030", "Property not found while reading system metadata from metacat: " + e.getMessage());
829
                    } catch (ClassNotFoundException e) {
830
                        e.printStackTrace();
831
                        throw new ServiceFailure("1030", "Class not found while reading system metadata from metacat: " + e.getMessage());
832
                    } catch (IOException e) {
833
                        e.printStackTrace();
834
                        throw new ServiceFailure("1030", "IOException while reading system metadata from metacat: " + e.getMessage());
835
                    } catch (SQLException e) {
836
                        e.printStackTrace();
837
                        throw new ServiceFailure("1030", "SQLException while reading system metadata from metacat: " + e.getMessage());
838
                    } catch (McdbException e) {
839
                        e.printStackTrace();
840
                        throw new ServiceFailure("1030", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
841
                    } catch (ParseLSIDException e) {
842
                        e.printStackTrace();
843
                        throw new NotFound("1020", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
844
                    } catch (InsufficientKarmaException e) {
845
                        e.printStackTrace();
846
                        throw new NotAuthorized("1000", "User not authorized for get() on system metadata: " + e.getMessage());
847
                    }
848

    
849
                    return "Completed";
850
                }
851
            };
852
            
853
            // Deserialize the xml to create a SystemMetadata object
854
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
855
            String username = sessionData.getUserName();
856
            EventLog.getInstance().log(metacatUrl,
857
                    username, im.getLocalId(guid.getValue()), "read");
858
            logCrud.info("getSystemMetadata localId: " + localId + " guid:" + guid.getValue());
859
            return sysmeta;
860
            
861
        } catch (McdbDocNotFoundException e) {
862
            //e.printStackTrace();
863
            throw new NotFound("1000", e.getMessage());
864
        }                
865
    }
866
    
867
    /**
868
     * parse the date in the systemMetadata
869
     * @param s
870
     * @return
871
     * @throws Exception
872
     */
873
    private Date parseDate(String s)
874
      throws Exception
875
    {
876
        Date d = null;
877
        int tIndex = s.indexOf("T");
878
        int zIndex = s.indexOf("Z");
879
        if(tIndex != -1 && zIndex != -1)
880
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
881
            //System.out.println("original date: " + s);
882
            
883
            String date = s.substring(0, tIndex);
884
            String year = date.substring(0, date.indexOf("-"));
885
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
886
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
887
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
888
                    " month: " + new Integer(month).intValue() + " day: " + 
889
                    new Integer(day).intValue());
890
            */
891
            String time = s.substring(tIndex + 1, zIndex);
892
            String hour = time.substring(0, time.indexOf(":"));
893
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
894
            String seconds = "00";
895
            String milliseconds = "00";
896
            if(time.indexOf(".") != -1)
897
            {
898
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
899
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
900
            }
901
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
902
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
903
                    new Integer(seconds).intValue() + " milli: " + 
904
                    new Integer(milliseconds).intValue());*/
905
            
906
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
907
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
908
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
909
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
910
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
911
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
912
            d = new Date(c.getTimeInMillis());
913
            //System.out.println("d: " + d);
914
            return d;
915
        }
916
        else
917
        {  //if it's not in the expected format, try the formatter
918
            return DateFormat.getDateTimeInstance().parse(s);
919
        }
920
    }
921

    
922
    /*
923
     * Look up the information on the session using the token provided in
924
     * the AuthToken.  The Session should have all relevant user information.
925
     * If the session has expired or is invalid, the 'public' session will
926
     * be returned, giving the user anonymous access.
927
     */
928
    public static SessionData getSessionData(AuthToken token) {
929
        SessionData sessionData = null;
930
        String sessionId = "PUBLIC";
931
        if (token != null) {
932
            sessionId = token.getToken();
933
        }
934
        
935
        // if the session id is registered in SessionService, get the
936
        // SessionData for it. Otherwise, use the public session.
937
        //System.out.println("sessionid: " + sessionId);
938
        if (sessionId != null &&
939
            !sessionId.toLowerCase().equals("public") &&
940
            SessionService.getInstance().isSessionRegistered(sessionId)) 
941
        {
942
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
943
        } else {
944
            sessionData = SessionService.getInstance().getPublicSession();
945
        }
946
        
947
        return sessionData;
948
    }
949

    
950
    /** 
951
     * Determine if a given object should be treated as an XML science metadata
952
     * object. 
953
     * 
954
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
955
     * 
956
     * @param sysmeta the SystemMetadata describig the object
957
     * @return true if the object should be treated as science metadata
958
     */
959
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
960
        boolean scimeta = false;
961
        switch (sysmeta.getObjectFormat()) {
962
            case EML_2_1_0: scimeta = true; break;
963
            case EML_2_0_1: scimeta = true; break;
964
            case EML_2_0_0: scimeta = true; break;
965
            case FGDC_STD_001_1_1999: scimeta = true; break;
966
            case FGDC_STD_001_1998: scimeta = true; break;
967
            case NCML_2_2: scimeta = true; break;
968
        }
969
        
970
        return scimeta;
971
    }
972

    
973
    /**
974
     * insert a data doc
975
     * @param object
976
     * @param guid
977
     * @param sessionData
978
     * @throws ServiceFailure
979
     */
980
    private void insertDataObject(InputStream object, Identifier guid, 
981
            SessionData sessionData) throws ServiceFailure {
982
        
983
        String username = sessionData.getUserName();
984
        String[] groups = sessionData.getGroupNames();
985

    
986
        // generate guid/localId pair for object
987
        logMetacat.debug("Generating a guid/localId mapping");
988
        IdentifierManager im = IdentifierManager.getInstance();
989
        String localId = im.generateLocalId(guid.getValue(), 1);
990

    
991
        try {
992
            logMetacat.debug("Case DATA: starting to write to disk.");
993
            if (DocumentImpl.getDataFileLockGrant(localId)) {
994
    
995
                // Save the data file to disk using "localId" as the name
996
                try {
997
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
998
    
999
                    File dataDirectory = new File(datafilepath);
1000
                    dataDirectory.mkdirs();
1001
    
1002
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
1003
    
1004
                    // TODO: Check that the file size matches SystemMetadata
1005
                    //                        long size = newFile.length();
1006
                    //                        if (size == 0) {
1007
                    //                            throw new IOException("Uploaded file is 0 bytes!");
1008
                    //                        }
1009
    
1010
                    // Register the file in the database (which generates an exception
1011
                    // if the localId is not acceptable or other untoward things happen
1012
                    try {
1013
                        logMetacat.debug("Registering document...");
1014
                        DocumentImpl.registerDocument(localId, "BIN", localId,
1015
                                username, groups);
1016
                        logMetacat.debug("Registration step completed.");
1017
                    } catch (SQLException e) {
1018
                        //newFile.delete();
1019
                        logMetacat.debug("SQLE: " + e.getMessage());
1020
                        e.printStackTrace(System.out);
1021
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1022
                    } catch (AccessionNumberException e) {
1023
                        //newFile.delete();
1024
                        logMetacat.debug("ANE: " + e.getMessage());
1025
                        e.printStackTrace(System.out);
1026
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1027
                    } catch (Exception e) {
1028
                        //newFile.delete();
1029
                        logMetacat.debug("Exception: " + e.getMessage());
1030
                        e.printStackTrace(System.out);
1031
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1032
                    }
1033
    
1034
                    logMetacat.debug("Logging the creation event.");
1035
                    EventLog.getInstance().log(metacatUrl,
1036
                            username, localId, "create");
1037
    
1038
                    // Schedule replication for this data file
1039
                    logMetacat.debug("Scheduling replication.");
1040
                    ForceReplicationHandler frh = new ForceReplicationHandler(
1041
                            localId, "create", false, null);
1042
    
1043
                } catch (PropertyNotFoundException e) {
1044
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1045
                }
1046
    
1047
            }
1048
        } catch (Exception e) {
1049
            // Could not get a lock on the document, so we can not update the file now
1050
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1051
        }
1052
    }
1053

    
1054
    /**
1055
     * write a file to a stream
1056
     * @param dir
1057
     * @param fileName
1058
     * @param data
1059
     * @return
1060
     * @throws ServiceFailure
1061
     */
1062
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1063
        throws ServiceFailure {
1064
        
1065
        File newFile = new File(dir, fileName);
1066
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1067

    
1068
        try {
1069
            if (newFile.createNewFile()) {
1070
                // write data stream to desired file
1071
                OutputStream os = new FileOutputStream(newFile);
1072
                long length = IOUtils.copyLarge(data, os);
1073
                os.flush();
1074
                os.close();
1075
            } else {
1076
                logMetacat.debug("File creation failed, or file already exists.");
1077
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1078
            }
1079
        } catch (FileNotFoundException e) {
1080
            logMetacat.debug("FNF: " + e.getMessage());
1081
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1082
                    + e.getMessage());
1083
        } catch (IOException e) {
1084
            logMetacat.debug("IOE: " + e.getMessage());
1085
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1086
                    + " " + e.getMessage());
1087
        }
1088

    
1089
        return newFile;
1090
    }
1091

    
1092
    /**
1093
     * insert a systemMetadata doc
1094
     */
1095
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1096
        throws ServiceFailure 
1097
    {
1098
        logMetacat.debug("Starting to insert SystemMetadata...");
1099
    
1100
        // generate guid/localId pair for sysmeta
1101
        Identifier sysMetaGuid = new Identifier();
1102
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1103
        sysmeta.setDateSysMetadataModified(new Date());
1104

    
1105
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
1106
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
1107
        //insert the system metadata doc id into the identifiers table to 
1108
        //link it to the data or metadata document
1109
        IdentifierManager.getInstance().createSystemMetadataMapping(
1110
                sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
1111
    }
1112
    
1113
    /**
1114
     * update a systemMetadata doc
1115
     */
1116
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1117
      throws ServiceFailure
1118
    {
1119
        try
1120
        {
1121
            String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
1122
            sm.setDateSysMetadataModified(new Date());
1123
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
1124
            Identifier id = new Identifier();
1125
            id.setValue(smId);
1126
            String localId = updateDocument(xml, id, null, sessionData);
1127
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
1128
        }
1129
        catch(Exception e)
1130
        {
1131
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
1132
        }
1133
    }
1134
    
1135
    /**
1136
     * insert a document
1137
     * NOTE: this method shouldn't be used from the update or create() methods.  
1138
     * we shouldn't be putting the science metadata or data objects into memory.
1139
     */
1140
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1141
        throws ServiceFailure
1142
    {
1143
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
1144
    }
1145
    
1146
    /**
1147
     * insert a document from a stream
1148
     */
1149
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1150
      throws IOException, ServiceFailure
1151
    {
1152
        //HACK: change this eventually.  we should not be converting the stream to a string
1153
        String xml = IOUtils.toString(is);
1154
        return insertDocument(xml, guid, sessionData);
1155
    }
1156
    
1157
    /**
1158
     * update a document
1159
     * NOTE: this method shouldn't be used from the update or create() methods.  
1160
     * we shouldn't be putting the science metadata or data objects into memory.
1161
     */
1162
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1163
        throws ServiceFailure
1164
    {
1165
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
1166
    }
1167
    
1168
    /**
1169
     * update a document from a stream
1170
     */
1171
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1172
      throws IOException, ServiceFailure
1173
    {
1174
        //HACK: change this eventually.  we should not be converting the stream to a string
1175
        String xml = IOUtils.toString(is);
1176
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
1177
        IdentifierManager im = IdentifierManager.getInstance();
1178
        if(guid != null)
1179
        {
1180
          im.createMapping(guid.getValue(), localId);
1181
        }
1182
        return localId;
1183
    }
1184
    
1185
    /**
1186
     * insert a document, return the id of the document that was inserted
1187
     */
1188
    protected String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
1189
        throws ServiceFailure {
1190
        logMetacat.debug("Starting to insert xml document...");
1191
        IdentifierManager im = IdentifierManager.getInstance();
1192

    
1193
        // generate guid/localId pair for sysmeta
1194
        String localId = null;
1195
        if(insertOrUpdate.equals("insert"))
1196
        {
1197
            localId = im.generateLocalId(guid.getValue(), 1);
1198
        }
1199
        else
1200
        {
1201
            //localid should already exist in the identifier table, so just find it
1202
            try
1203
            {
1204
                localId = im.getLocalId(guid.getValue());
1205
                //increment the revision
1206
                String docid = localId.substring(0, localId.lastIndexOf("."));
1207
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1208
                int rev = new Integer(revS).intValue();
1209
                rev++;
1210
                docid = docid + "." + rev;
1211
                localId = docid;
1212
            }
1213
            catch(McdbDocNotFoundException e)
1214
            {
1215
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1216
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1217
            }
1218
        }
1219
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1220
                localId);
1221

    
1222
        String[] action = new String[1];
1223
        action[0] = insertOrUpdate;
1224
        params.put("action", action);
1225
        String[] docid = new String[1];
1226
        docid[0] = localId;
1227
        params.put("docid", docid);
1228
        String[] doctext = new String[1];
1229
        doctext[0] = xml;
1230
        logMetacat.debug(doctext[0]);
1231
        params.put("doctext", doctext);
1232
        
1233
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1234
        // onto output stream, or alternatively, capture that and parse it to 
1235
        // generate the right exceptions
1236
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1237
        //PrintWriter pw = new PrintWriter(output);
1238
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1239
                            null, params, sessionData.getUserName(), sessionData.getGroupNames());
1240
        //String outputS = new String(output.toByteArray());
1241
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1242
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1243
        return localId;
1244
    }
1245
    
1246
    /**
1247
     * serialize a system metadata doc
1248
     * @param sysmeta
1249
     * @return
1250
     * @throws ServiceFailure
1251
     */
1252
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1253
        throws ServiceFailure {
1254
        IBindingFactory bfact;
1255
        ByteArrayOutputStream sysmetaOut = null;
1256
        try {
1257
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1258
            IMarshallingContext mctx = bfact.createMarshallingContext();
1259
            sysmetaOut = new ByteArrayOutputStream();
1260
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1261
        } catch (JiBXException e) {
1262
            e.printStackTrace();
1263
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1264
        }
1265
        
1266
        return sysmetaOut;
1267
    }
1268
    
1269
    /**
1270
     * deserialize a system metadata doc
1271
     * @param xml
1272
     * @return
1273
     * @throws ServiceFailure
1274
     */
1275
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1276
        throws ServiceFailure {
1277
        try {
1278
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1279
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1280
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1281
            return sysmeta;
1282
        } catch (JiBXException e) {
1283
            e.printStackTrace();
1284
            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1285
        }    
1286
    }
1287
    
1288
    /**
1289
     * produce an md5 checksum for item
1290
     */
1291
    private String checksum(InputStream is)
1292
      throws Exception
1293
    {        
1294
        byte[] buffer = new byte[1024];
1295
        MessageDigest complete = MessageDigest.getInstance("MD5");
1296
        int numRead;
1297
        
1298
        do 
1299
        {
1300
          numRead = is.read(buffer);
1301
          if (numRead > 0) 
1302
          {
1303
            complete.update(buffer, 0, numRead);
1304
          }
1305
        } while (numRead != -1);
1306
        
1307
        
1308
        return getHex(complete.digest());
1309
    }
1310
    
1311
    /**
1312
     * convert a byte array to a hex string
1313
     */
1314
    private static String getHex( byte [] raw ) 
1315
    {
1316
        final String HEXES = "0123456789ABCDEF";
1317
        if ( raw == null ) {
1318
          return null;
1319
        }
1320
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
1321
        for ( final byte b : raw ) {
1322
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
1323
             .append(HEXES.charAt((b & 0x0F)));
1324
        }
1325
        return hex.toString();
1326
    }
1327
    
1328
    /**
1329
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
1330
     * a proper date object
1331
     * @param date
1332
     * @return
1333
     */
1334
    private Date parseMetacatDate(String date)
1335
    {
1336
        String year = date.substring(0, 4);
1337
        String month = date.substring(5, 7);
1338
        String day = date.substring(8, 10);
1339
        Calendar c = Calendar.getInstance();
1340
        c.set(new Integer(year).intValue(), 
1341
              new Integer(month).intValue(), 
1342
              new Integer(day).intValue());
1343
        return c.getTime();
1344
    }
1345
    
1346
    /**
1347
     * find the size (in bytes) of a stream
1348
     * @param is
1349
     * @return
1350
     * @throws IOException
1351
     */
1352
    private long sizeOfStream(InputStream is)
1353
        throws IOException
1354
    {
1355
        long size = 0;
1356
        byte[] b = new byte[1024];
1357
        int numread = is.read(b, 0, 1024);
1358
        while(numread != -1)
1359
        {
1360
            size += numread;
1361
            numread = is.read(b, 0, 1024);
1362
        }
1363
        return size;
1364
    }
1365
    
1366
    /**
1367
     * create system metadata with a specified id, doc and format
1368
     */
1369
    private SystemMetadata createSystemMetadata(String localId, AuthToken token)
1370
      throws Exception
1371
    {
1372
        IdentifierManager im = IdentifierManager.getInstance();
1373
        Hashtable<String, String> docInfo = im.getDocumentInfo(localId);
1374
        
1375
        //get the document text
1376
        int rev = im.getLatestRevForLocalId(localId);
1377
        Identifier identifier = new Identifier();
1378
        identifier.setValue(im.getGUID(localId, rev));
1379
        InputStream is = this.get(token, identifier);
1380
        
1381
        SystemMetadata sm = new SystemMetadata();
1382
        //set the id
1383
        sm.setIdentifier(identifier);
1384
        
1385
        //set the object format
1386
        String doctype = docInfo.get("doctype");
1387
        ObjectFormat format = ObjectFormat.convert(docInfo.get("doctype"));
1388
        if(format == null)
1389
        {
1390
            if(doctype.trim().equals("BIN"))
1391
            {
1392
                format = ObjectFormat.APPLICATIONOCTETSTREAM;
1393
            }
1394
            else
1395
            {
1396
                format = ObjectFormat.convert("text/plain");
1397
            }
1398
        }
1399
        sm.setObjectFormat(format);
1400
        
1401
        //create the checksum
1402
        String checksumS = checksum(is);
1403
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
1404
        Checksum checksum = new Checksum();
1405
        checksum.setValue(checksumS);
1406
        checksum.setAlgorithm(ca);
1407
        sm.setChecksum(checksum);
1408
        
1409
        //set the size
1410
        is = this.get(token, identifier);
1411
        sm.setSize(sizeOfStream(is));
1412
        
1413
        //submitter
1414
        Principal p = new Principal();
1415
        p.setValue(docInfo.get("user_owner"));
1416
        sm.setSubmitter(p);
1417
        sm.setRightsHolder(p);
1418
        try
1419
        {
1420
            Date dateCreated = parseMetacatDate(docInfo.get("date_created"));
1421
            sm.setDateUploaded(dateCreated);
1422
            Date dateUpdated = parseMetacatDate(docInfo.get("date_updated"));
1423
            sm.setDateSysMetadataModified(dateUpdated);
1424
        }
1425
        catch(Exception e)
1426
        {
1427
            System.out.println("couldn't parse a date: " + e.getMessage());
1428
            Date dateCreated = new Date();
1429
            sm.setDateUploaded(dateCreated);
1430
            Date dateUpdated = new Date();
1431
            sm.setDateSysMetadataModified(dateUpdated);
1432
        }
1433
        NodeReference nr = new NodeReference();
1434
        nr.setValue("metacat");
1435
        sm.setOriginMemberNode(nr);
1436
        sm.setAuthoritativeMemberNode(nr);
1437
        return sm;
1438
    }
1439
}
(1-1/2)