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
              System.out.println("adding doc " + i + " to the objectList");
540
          }
541
      }
542
      catch(Exception e)
543
      {
544
          e.printStackTrace();
545
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
546
      }
547
      String username = sessionData.getUserName();
548
      EventLog.getInstance().log(metacatUrl,
549
              username, null, "read");
550
      logCrud.info("listObjects");
551
      System.out.println("ol.size: " + ol.sizeObjectInfoList());
552
      return ol;
553
    }
554
    
555
    /**
556
     * Call listObjects with the default values for replicaStatus (true), start (0),
557
     * and count (1000).
558
     * @param token
559
     * @param startTime
560
     * @param endTime
561
     * @param objectFormat
562
     * @return
563
     * @throws NotAuthorized
564
     * @throws InvalidRequest
565
     * @throws NotImplemented
566
     * @throws ServiceFailure
567
     * @throws InvalidToken
568
     */
569
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
570
        ObjectFormat objectFormat)
571
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
572
    {
573
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
574
    }
575

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1091
        return newFile;
1092
    }
1093

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

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

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

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