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 ServletContext servletContext;
93
    private HttpServletRequest request;
94
    private HttpServletResponse response;*/
95
    
96
    private static CrudService crudService = null;
97

    
98
    private MetacatHandler handler;
99
    private Hashtable<String, String[]> params;
100
    Logger logMetacat = null;
101
    
102
    private String metacatUrl;
103

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

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

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

    
257
        logMetacat.debug("Starting CrudService.create()...");
258
        
259
        // authenticate & get user info
260
        SessionData sessionData = getSessionData(token);
261
        String username = sessionData.getUserName();
262
        String[] groups = sessionData.getGroupNames();
263
        String localId = null;
264

    
265
        if (username == null || username.equals("public"))
266
        {
267
            throw new NotAuthorized("1000", "User " + username + " is not authorized to create content." +
268
                    "  If you are not logged in, please do so and retry the request.");
269
        }
270
        
271
        // verify that guid == SystemMetadata.getIdentifier()
272
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
273
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
274
            throw new InvalidSystemMetadata("1180", 
275
                "GUID in method call does not match GUID in system metadata.");
276
        }
277

    
278
        logMetacat.debug("Checking if identifier exists...");
279
        // Check that the identifier does not already exist
280
        IdentifierManager im = IdentifierManager.getInstance();
281
        if (im.identifierExists(guid.getValue())) {
282
            throw new IdentifierNotUnique("1120", 
283
                "GUID is already in use by an existing object.");
284
        }
285

    
286
        // Check if we are handling metadata or data
287
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
288
        
289
        if (isScienceMetadata) {
290
            // CASE METADATA:
291
            try {
292
                this.insertDocument(object, guid, sessionData);
293
                localId = im.getLocalId(guid.getValue());
294
            } catch (IOException e) {
295
                String msg = "Could not create string from XML stream: " +
296
                    " " + e.getMessage();
297
                logMetacat.debug(msg);
298
                throw new ServiceFailure("1190", msg);
299
            } catch(Exception e) {
300
                String msg = "Unexpected error in CrudService.create: " + e.getMessage();
301
                logMetacat.debug(msg);
302
                throw new ServiceFailure("1190", msg);
303
            }
304
            
305

    
306
        } else {
307
            // DEFAULT CASE: DATA (needs to be checked and completed)
308
            insertDataObject(object, guid, sessionData);
309
            
310
        }
311

    
312
        // For Metadata and Data, insert the system metadata into the object store too
313
        insertSystemMetadata(sysmeta, sessionData);
314
        logMetacat.debug("Returning from CrudService.create()");
315
        EventLog.getInstance().log(metacatUrl,
316
                username, localId, "create");
317
        return guid;
318
    }
319
    
320
    /**
321
     * update an existing object with a new object.  Change the system metadata
322
     * to reflect the changes and update it as well.
323
     */
324
    public Identifier update(AuthToken token, Identifier guid, 
325
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
326
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
327
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
328
            NotImplemented {
329
        try
330
        {
331
            SessionData sessionData = getSessionData(token);
332
            
333
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
334
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
335
            //change sm.old's obsoletedBy field 
336
            List l = sm.getObsoletedByList();
337
            l.add(guid);
338
            sm.setObsoletedByList(l);
339
            //update sm.old
340
            updateSystemMetadata(sm, sessionData);
341
            
342
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
343
            sysmeta.addObsolete(obsoletedGuid);
344
            //insert sm.new
345
            insertSystemMetadata(sysmeta, sessionData);
346
            
347
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
348
            if(isScienceMetadata)
349
            {
350
                //update the doc
351
                updateDocument(object, obsoletedGuid, guid, sessionData);
352
            }
353
            else
354
            {
355
                //update a data file, not xml
356
                insertDataObject(object, guid, sessionData);
357
            }
358
            
359
            IdentifierManager im = IdentifierManager.getInstance();
360
            String username = sessionData.getUserName();
361
            EventLog.getInstance().log(metacatUrl,
362
                    username, im.getLocalId(guid.getValue()), "update");
363
            return guid;
364
        }
365
        catch(Exception e)
366
        {
367
            throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
368
        }
369
    }
370
    
371
    /**
372
     * set the permission on the document
373
     * @param token
374
     * @param principal
375
     * @param permission
376
     * @param permissionType
377
     * @param permissionOrder
378
     * @return
379
     */
380
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
381
            String permissionType, String permissionOrder)
382
      throws ServiceFailure
383
    {
384
        try
385
        {
386
            IdentifierManager im = IdentifierManager.getInstance();
387
            String docid = im.getLocalId(id.getValue());
388
            final SessionData sessionData = getSessionData(token);
389
            String permNum = "0";
390
            if(permission.equals("read"))
391
            {
392
                permNum = "4";
393
            }
394
            else if(permission.equals("write"))
395
            {
396
                permNum = "6";
397
            }
398
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
399
                    principal, permNum, permissionType, permissionOrder);
400
            
401
            String username = sessionData.getUserName();
402
            EventLog.getInstance().log(metacatUrl,
403
                    username, im.getLocalId(id.getValue()), "setAccess");
404
        }
405
        catch(Exception e)
406
        {
407
            e.printStackTrace();
408
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
409
        }
410
    }
411
    
412
    /**
413
     *  Retrieve the list of objects present on the MN that match the calling 
414
     *  parameters. This method is required to support the process of Member 
415
     *  Node synchronization. At a minimum, this method should be able to 
416
     *  return a list of objects that match:
417
     *  startTime <= SystemMetadata.dateSysMetadataModified
418
     *  but is expected to also support date range (by also specifying endTime), 
419
     *  and should also support slicing of the matching set of records by 
420
     *  indicating the starting index of the response (where 0 is the index 
421
     *  of the first item) and the count of elements to be returned.
422
     *  
423
     *  If startTime or endTime is null, the query is not restricted by that parameter.
424
     *  
425
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
426
     * @param token
427
     * @param startTime
428
     * @param endTime
429
     * @param objectFormat
430
     * @param replicaStatus
431
     * @param start
432
     * @param count
433
     * @return ObjectList
434
     * @throws NotAuthorized
435
     * @throws InvalidRequest
436
     * @throws NotImplemented
437
     * @throws ServiceFailure
438
     * @throws InvalidToken
439
     */
440
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
441
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
442
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
443
    {
444
      ObjectList ol = new ObjectList();
445
      final SessionData sessionData = getSessionData(token);
446
      try
447
      {
448
          params.clear();
449
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
450
          params.put("qformat", new String[] {"xml"});
451
          params.put("returnfield", new String[] {"size", "originMemberNode", 
452
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "@algorithm"});
453
          params.put("anyfield", new String[] {"%"});
454
          
455
          MetacatResultSet rs = handler.query(metacatUrl, params, sessionData.getUserName(), 
456
                  sessionData.getGroupNames(), sessionData.getId());
457
          List docs = rs.getDocuments();
458

    
459
          if(count == 1000)
460
          {
461
              count = docs.size();
462
          }
463
          for(int i=start; i<count; i++)
464
          {
465
              //get the document from the results
466
              Document d = (Document)docs.get(i);
467
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
468
              if(returnedObjectFormat == null)
469
              {
470
                  continue;
471
              }
472
              if(objectFormat != null && !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
473
              { //make sure the objectFormat is the one specified
474
                  continue;
475
              }
476
              
477
              String dateSMM = d.getField("dateSysMetadataModified");
478
              if(dateSMM == null)
479
              {
480
                  continue;
481
              }
482
              Date dateSysMetadataModified = parseDate(dateSMM);
483
              int startDateComparison = 0;
484
              int endDateComparison = 0;
485
              if(startTime != null)
486
              {
487
                  startDateComparison = dateSysMetadataModified.compareTo(startTime);
488
              }
489
              
490
              if(endTime != null)
491
              {
492
                  endDateComparison = dateSysMetadataModified.compareTo(endTime);
493
              }
494
              
495
              if(startDateComparison < 0 || endDateComparison > 0)
496
              { //this date falls outside of the startTime and endTime params, so
497
                //skip it
498
                  continue;                  
499
              }
500
              
501
              ObjectInfo info = new ObjectInfo();
502
              //add the fields to the info object
503
              Checksum cs = new Checksum();
504
              cs.setValue(d.getField("checksum"));
505
              String csalg = d.getField("algorithm");
506
              if(csalg == null)
507
              {
508
                  csalg = "MD5";
509
              }
510
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
511
              cs.setAlgorithm(ca);
512
              info.setChecksum(cs);
513
              info.setDateSysMetadataModified(dateSysMetadataModified);
514
              Identifier id = new Identifier();
515
              id.setValue(d.getField("identifier"));
516
              info.setIdentifier(id);
517
              info.setObjectFormat(returnedObjectFormat);
518
              info.setSize(new Long(d.getField("size").trim()).longValue());
519
              //add the ObjectInfo to the ObjectList
520
              ol.addObjectInfo(info);
521
              //System.out.println(d.toString());
522
          }
523
      }
524
      catch(Exception e)
525
      {
526
          e.printStackTrace();
527
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
528
      }
529
      String username = sessionData.getUserName();
530
      EventLog.getInstance().log(metacatUrl,
531
              username, null, "read");
532
      return ol;
533
    }
534
    
535
    /**
536
     * Call listObjects with the default values for replicaStatus (true), start (0),
537
     * and count (1000).
538
     * @param token
539
     * @param startTime
540
     * @param endTime
541
     * @param objectFormat
542
     * @return
543
     * @throws NotAuthorized
544
     * @throws InvalidRequest
545
     * @throws NotImplemented
546
     * @throws ServiceFailure
547
     * @throws InvalidToken
548
     */
549
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
550
        ObjectFormat objectFormat)
551
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
552
    {
553
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
554
    }
555

    
556
    /**
557
     * Delete a document.  NOT IMPLEMENTED
558
     */
559
    public Identifier delete(AuthToken token, Identifier guid)
560
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
561
            NotImplemented {
562
        throw new NotImplemented("1000", "This method not yet implemented.");
563
    }
564

    
565
    /**
566
     * describe a document.  NOT IMPLEMENTED
567
     */
568
    public DescribeResponse describe(AuthToken token, Identifier guid)
569
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
570
            NotImplemented {
571
        throw new NotImplemented("1000", "This method not yet implemented.");
572
    }
573
    
574
    /**
575
     * get a document with a specified guid.
576
     */
577
    public InputStream get(AuthToken token, Identifier guid)
578
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
579
            NotImplemented {
580
        
581
        // Retrieve the session information from the AuthToken
582
        // If the session is expired, then the user is 'public'
583
        final SessionData sessionData = getSessionData(token);
584
        
585
        // Look up the localId for this global identifier
586
        IdentifierManager im = IdentifierManager.getInstance();
587
        try {
588
            final String localId = im.getLocalId(guid.getValue());
589

    
590
            final InputStreamFromOutputStream<String> objectStream = 
591
                new InputStreamFromOutputStream<String>() {
592
                
593
                @Override
594
                public String produce(final OutputStream dataSink) throws Exception {
595

    
596
                    try {
597
                        handler.readFromMetacat(metacatUrl, null, 
598
                                dataSink, localId, "xml",
599
                                sessionData.getUserName(), 
600
                                sessionData.getGroupNames(), true, params);
601
                    } catch (PropertyNotFoundException e) {
602
                        e.printStackTrace();
603
                        throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
604
                    } catch (ClassNotFoundException e) {
605
                        e.printStackTrace();
606
                        throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
607
                    } catch (IOException e) {
608
                        e.printStackTrace();
609
                        throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
610
                    } catch (SQLException e) {
611
                        e.printStackTrace();
612
                        throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
613
                    } catch (McdbException e) {
614
                        e.printStackTrace();
615
                        throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
616
                    } catch (ParseLSIDException e) {
617
                        e.printStackTrace();
618
                        throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
619
                    } catch (InsufficientKarmaException e) {
620
                        e.printStackTrace();
621
                        throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
622
                    }
623

    
624
                    return "Completed";
625
                }
626
            };
627
            
628
            String username = sessionData.getUserName();
629
            EventLog.getInstance().log(metacatUrl,
630
                    username, im.getLocalId(guid.getValue()), "read");
631
            return objectStream;
632

    
633
        } catch (McdbDocNotFoundException e) {
634
            throw new NotFound("1020", e.getMessage());
635
        }
636
    }
637

    
638
    /**
639
     * get the checksum for a document.  NOT IMPLEMENTED
640
     */
641
    public Checksum getChecksum(AuthToken token, Identifier guid)
642
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
643
            InvalidRequest, NotImplemented {
644
        throw new NotImplemented("1000", "This method not yet implemented.");
645
    }
646

    
647
    /**
648
     * get the checksum for a document.  NOT IMPLEMENTED
649
     */
650
    public Checksum getChecksum(AuthToken token, Identifier guid, 
651
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
652
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
653
        throw new NotImplemented("1000", "This method not yet implemented.");
654
    }
655

    
656
    /**
657
     * get log records.  
658
     */
659
    public LogRecordSet getLogRecords(AuthToken token, Date fromDate, Date toDate)
660
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
661
            NotImplemented 
662
    {
663
        IdentifierManager im = IdentifierManager.getInstance();
664
        HashSet<LogRecord> logs = new HashSet<LogRecord>();
665
        EventLog el = EventLog.getInstance();
666
        String report = el.getReport(null, null, null, null, 
667
                new java.sql.Timestamp(fromDate.getTime()), 
668
                new java.sql.Timestamp(toDate.getTime()));
669
        
670
        String logEntry = "<logEntry>";
671
        String endLogEntry = "</logEntry>";
672
        int startIndex = 0;
673
        int foundIndex = report.indexOf(logEntry, startIndex);
674
        while(foundIndex != -1)
675
        {
676
            //parse out each entry
677
            int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
678
            String entry = report.substring(foundIndex, endEntryIndex);
679
            //System.out.println("entry: " + entry);
680
            startIndex = endEntryIndex + endLogEntry.length();
681
            foundIndex = report.indexOf(logEntry, startIndex);
682
            
683
            String entryId = getLogEntryField("entryid", entry);
684
            String ipAddress = getLogEntryField("ipAddress", entry);
685
            String principal = getLogEntryField("principal", entry);
686
            String docid = getLogEntryField("docid", entry);
687
            String event = getLogEntryField("event", entry);
688
            String dateLogged = getLogEntryField("dateLogged", entry);
689
            
690
            LogRecord lr = new LogRecord();
691
            
692
            Event e = Event.convert(event);
693
            if(e == null)
694
            { //skip any events that are not Dataone Crud events
695
                continue;
696
            }
697
            lr.setEvent(e);
698
            Identifier entryid = new Identifier();
699
            entryid.setValue(entryId);
700
            lr.setEntryId(entryid);
701
            Identifier identifier = new Identifier();
702
            try
703
            {
704
                identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
705
            }
706
            catch(Exception ex)
707
            { //try to get the guid, if that doesn't work, just use the local id
708
                identifier.setValue(docid);
709
            }
710
            
711
            lr.setIdentifier(identifier);
712
            lr.setIpAddress(ipAddress);
713
            Calendar c = Calendar.getInstance();
714
            String year = dateLogged.substring(0, 4);
715
            String month = dateLogged.substring(5, 7);
716
            String date = dateLogged.substring(8, 10);
717
            //System.out.println("year: " + year + " month: " + month + " day: " + date);
718
            c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
719
            Date logDate = c.getTime();
720
            lr.setLogDate(logDate);
721
            NodeReference memberNode = new NodeReference();
722
            memberNode.setValue(ipAddress);
723
            lr.setMemberNode(memberNode);
724
            Principal princ = new Principal();
725
            princ.setValue(principal);
726
            lr.setPrincipal(princ);
727
            lr.setUserAgent("metacat/RESTService");
728
            logs.add(lr);
729
        }
730
        
731
        LogRecordSet set = new LogRecordSet(logs);
732
        set.setRecords(logs);
733
        return set;
734
    }
735
    
736
    /**
737
     * parse a logEntry and get the relavent field from it
738
     * @param fieldname
739
     * @param entry
740
     * @return
741
     */
742
    private String getLogEntryField(String fieldname, String entry)
743
    {
744
        String begin = "<" + fieldname + ">";
745
        String end = "</" + fieldname + ">";
746
        //System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
747
        String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
748
        //System.out.println("entry " + fieldname + " : " + s);
749
        return s;
750
    }
751

    
752
    /**
753
     * get the system metadata for a document with a specified guid.
754
     */
755
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
756
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
757
            InvalidRequest, NotImplemented {
758
        
759
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
760
        
761
        // Retrieve the session information from the AuthToken
762
        // If the session is expired, then the user is 'public'
763
        final SessionData sessionData = getSessionData(token);
764
                
765
        try {
766
            IdentifierManager im = IdentifierManager.getInstance();
767
            final String localId = im.getSystemMetadataId(guid.getValue());
768
            
769
            // Read system metadata from metacat's db
770
            final InputStreamFromOutputStream<String> objectStream = 
771
                new InputStreamFromOutputStream<String>() {
772
                
773
                @Override
774
                public String produce(final OutputStream dataSink) throws Exception {
775
                    try {
776
                        handler.readFromMetacat(metacatUrl, null, 
777
                                dataSink, localId, "xml",
778
                                sessionData.getUserName(), 
779
                                sessionData.getGroupNames(), true, params);
780
                    } catch (PropertyNotFoundException e) {
781
                        e.printStackTrace();
782
                        throw new ServiceFailure("1030", "Property not found while reading system metadata from metacat: " + e.getMessage());
783
                    } catch (ClassNotFoundException e) {
784
                        e.printStackTrace();
785
                        throw new ServiceFailure("1030", "Class not found while reading system metadata from metacat: " + e.getMessage());
786
                    } catch (IOException e) {
787
                        e.printStackTrace();
788
                        throw new ServiceFailure("1030", "IOException while reading system metadata from metacat: " + e.getMessage());
789
                    } catch (SQLException e) {
790
                        e.printStackTrace();
791
                        throw new ServiceFailure("1030", "SQLException while reading system metadata from metacat: " + e.getMessage());
792
                    } catch (McdbException e) {
793
                        e.printStackTrace();
794
                        throw new ServiceFailure("1030", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
795
                    } catch (ParseLSIDException e) {
796
                        e.printStackTrace();
797
                        throw new NotFound("1020", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
798
                    } catch (InsufficientKarmaException e) {
799
                        e.printStackTrace();
800
                        throw new NotAuthorized("1000", "User not authorized for get() on system metadata: " + e.getMessage());
801
                    }
802

    
803
                    return "Completed";
804
                }
805
            };
806
            
807
            // Deserialize the xml to create a SystemMetadata object
808
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
809
            String username = sessionData.getUserName();
810
            EventLog.getInstance().log(metacatUrl,
811
                    username, im.getLocalId(guid.getValue()), "read");
812
            return sysmeta;
813
            
814
        } catch (McdbDocNotFoundException e) {
815
            //e.printStackTrace();
816
            throw new NotFound("1000", e.getMessage());
817
        }                
818
    }
819
    
820
    /**
821
     * parse the date in the systemMetadata
822
     * @param s
823
     * @return
824
     * @throws Exception
825
     */
826
    private Date parseDate(String s)
827
      throws Exception
828
    {
829
        Date d = null;
830
        int tIndex = s.indexOf("T");
831
        int zIndex = s.indexOf("Z");
832
        if(tIndex != -1 && zIndex != -1)
833
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
834
            //System.out.println("original date: " + s);
835
            
836
            String date = s.substring(0, tIndex);
837
            String year = date.substring(0, date.indexOf("-"));
838
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
839
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
840
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
841
                    " month: " + new Integer(month).intValue() + " day: " + 
842
                    new Integer(day).intValue());
843
            */
844
            String time = s.substring(tIndex + 1, zIndex);
845
            String hour = time.substring(0, time.indexOf(":"));
846
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
847
            String seconds = "00";
848
            String milliseconds = "00";
849
            if(time.indexOf(".") != -1)
850
            {
851
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
852
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
853
            }
854
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
855
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
856
                    new Integer(seconds).intValue() + " milli: " + 
857
                    new Integer(milliseconds).intValue());*/
858
            
859
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
860
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
861
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
862
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
863
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
864
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
865
            d = new Date(c.getTimeInMillis());
866
            //System.out.println("d: " + d);
867
            return d;
868
        }
869
        else
870
        {  //if it's not in the expected format, try the formatter
871
            return DateFormat.getDateTimeInstance().parse(s);
872
        }
873
    }
874

    
875
    /*
876
     * Look up the information on the session using the token provided in
877
     * the AuthToken.  The Session should have all relevant user information.
878
     * If the session has expired or is invalid, the 'public' session will
879
     * be returned, giving the user anonymous access.
880
     */
881
    protected static SessionData getSessionData(AuthToken token) {
882
        SessionData sessionData = null;
883
        String sessionId = "PUBLIC";
884
        if (token != null) {
885
            sessionId = token.getToken();
886
        }
887
        
888
        // if the session id is registered in SessionService, get the
889
        // SessionData for it. Otherwise, use the public session.
890
        if (SessionService.getInstance().isSessionRegistered(sessionId)) {
891
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
892
        } else {
893
            sessionData = SessionService.getInstance().getPublicSession();
894
        }
895
        
896
        return sessionData;
897
    }
898

    
899
    /** 
900
     * Determine if a given object should be treated as an XML science metadata
901
     * object. 
902
     * 
903
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
904
     * 
905
     * @param sysmeta the SystemMetadata describig the object
906
     * @return true if the object should be treated as science metadata
907
     */
908
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
909
        boolean scimeta = false;
910
        switch (sysmeta.getObjectFormat()) {
911
            case EML_2_1_0: scimeta = true; break;
912
            case EML_2_0_1: scimeta = true; break;
913
            case EML_2_0_0: scimeta = true; break;
914
            case FGDC_STD_001_1_1999: scimeta = true; break;
915
            case FGDC_STD_001_1998: scimeta = true; break;
916
            case NCML_2_2: scimeta = true; break;
917
        }
918
        
919
        return scimeta;
920
    }
921

    
922
    /**
923
     * insert a data doc
924
     * @param object
925
     * @param guid
926
     * @param sessionData
927
     * @throws ServiceFailure
928
     */
929
    private void insertDataObject(InputStream object, Identifier guid, 
930
            SessionData sessionData) throws ServiceFailure {
931
        
932
        String username = sessionData.getUserName();
933
        String[] groups = sessionData.getGroupNames();
934

    
935
        // generate guid/localId pair for object
936
        logMetacat.debug("Generating a guid/localId mapping");
937
        IdentifierManager im = IdentifierManager.getInstance();
938
        String localId = im.generateLocalId(guid.getValue(), 1);
939

    
940
        try {
941
            logMetacat.debug("Case DATA: starting to write to disk.");
942
            if (DocumentImpl.getDataFileLockGrant(localId)) {
943
    
944
                // Save the data file to disk using "localId" as the name
945
                try {
946
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
947
    
948
                    File dataDirectory = new File(datafilepath);
949
                    dataDirectory.mkdirs();
950
    
951
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
952
    
953
                    // TODO: Check that the file size matches SystemMetadata
954
                    //                        long size = newFile.length();
955
                    //                        if (size == 0) {
956
                    //                            throw new IOException("Uploaded file is 0 bytes!");
957
                    //                        }
958
    
959
                    // Register the file in the database (which generates an exception
960
                    // if the localId is not acceptable or other untoward things happen
961
                    try {
962
                        logMetacat.debug("Registering document...");
963
                        DocumentImpl.registerDocument(localId, "BIN", localId,
964
                                username, groups);
965
                        logMetacat.debug("Registration step completed.");
966
                    } catch (SQLException e) {
967
                        //newFile.delete();
968
                        logMetacat.debug("SQLE: " + e.getMessage());
969
                        e.printStackTrace(System.out);
970
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
971
                    } catch (AccessionNumberException e) {
972
                        //newFile.delete();
973
                        logMetacat.debug("ANE: " + e.getMessage());
974
                        e.printStackTrace(System.out);
975
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
976
                    } catch (Exception e) {
977
                        //newFile.delete();
978
                        logMetacat.debug("Exception: " + e.getMessage());
979
                        e.printStackTrace(System.out);
980
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
981
                    }
982
    
983
                    logMetacat.debug("Logging the creation event.");
984
                    EventLog.getInstance().log(metacatUrl,
985
                            username, localId, "create");
986
    
987
                    // Schedule replication for this data file
988
                    logMetacat.debug("Scheduling replication.");
989
                    ForceReplicationHandler frh = new ForceReplicationHandler(
990
                            localId, "create", false, null);
991
    
992
                } catch (PropertyNotFoundException e) {
993
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
994
                }
995
    
996
            }
997
        } catch (Exception e) {
998
            // Could not get a lock on the document, so we can not update the file now
999
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1000
        }
1001
    }
1002

    
1003
    /**
1004
     * write a file to a stream
1005
     * @param dir
1006
     * @param fileName
1007
     * @param data
1008
     * @return
1009
     * @throws ServiceFailure
1010
     */
1011
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1012
        throws ServiceFailure {
1013
        
1014
        File newFile = new File(dir, fileName);
1015
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1016

    
1017
        try {
1018
            if (newFile.createNewFile()) {
1019
                // write data stream to desired file
1020
                OutputStream os = new FileOutputStream(newFile);
1021
                long length = IOUtils.copyLarge(data, os);
1022
                os.flush();
1023
                os.close();
1024
            } else {
1025
                logMetacat.debug("File creation failed, or file already exists.");
1026
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1027
            }
1028
        } catch (FileNotFoundException e) {
1029
            logMetacat.debug("FNF: " + e.getMessage());
1030
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1031
                    + e.getMessage());
1032
        } catch (IOException e) {
1033
            logMetacat.debug("IOE: " + e.getMessage());
1034
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1035
                    + " " + e.getMessage());
1036
        }
1037

    
1038
        return newFile;
1039
    }
1040

    
1041
    /**
1042
     * insert a systemMetadata doc
1043
     */
1044
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1045
        throws ServiceFailure 
1046
    {
1047
        logMetacat.debug("Starting to insert SystemMetadata...");
1048
    
1049
        // generate guid/localId pair for sysmeta
1050
        Identifier sysMetaGuid = new Identifier();
1051
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1052
        sysmeta.setDateSysMetadataModified(new Date());
1053

    
1054
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
1055
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
1056
        //insert the system metadata doc id into the identifiers table to 
1057
        //link it to the data or metadata document
1058
        IdentifierManager.getInstance().createSystemMetadataMapping(
1059
                sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
1060
    }
1061
    
1062
    /**
1063
     * update a systemMetadata doc
1064
     */
1065
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1066
      throws ServiceFailure
1067
    {
1068
        try
1069
        {
1070
            String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
1071
            sm.setDateSysMetadataModified(new Date());
1072
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
1073
            Identifier id = new Identifier();
1074
            id.setValue(smId);
1075
            String localId = updateDocument(xml, id, null, sessionData);
1076
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
1077
        }
1078
        catch(Exception e)
1079
        {
1080
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
1081
        }
1082
    }
1083
    
1084
    /**
1085
     * insert a document
1086
     * NOTE: this method shouldn't be used from the update or create() methods.  
1087
     * we shouldn't be putting the science metadata or data objects into memory.
1088
     */
1089
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1090
        throws ServiceFailure
1091
    {
1092
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
1093
    }
1094
    
1095
    /**
1096
     * insert a document from a stream
1097
     */
1098
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1099
      throws IOException, ServiceFailure
1100
    {
1101
        //HACK: change this eventually.  we should not be converting the stream to a string
1102
        String xml = IOUtils.toString(is);
1103
        return insertDocument(xml, guid, sessionData);
1104
    }
1105
    
1106
    /**
1107
     * update a document
1108
     * NOTE: this method shouldn't be used from the update or create() methods.  
1109
     * we shouldn't be putting the science metadata or data objects into memory.
1110
     */
1111
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1112
        throws ServiceFailure
1113
    {
1114
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
1115
    }
1116
    
1117
    /**
1118
     * update a document from a stream
1119
     */
1120
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
1121
      throws IOException, ServiceFailure
1122
    {
1123
        //HACK: change this eventually.  we should not be converting the stream to a string
1124
        String xml = IOUtils.toString(is);
1125
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
1126
        IdentifierManager im = IdentifierManager.getInstance();
1127
        if(guid != null)
1128
        {
1129
          im.createMapping(guid.getValue(), localId);
1130
        }
1131
        return localId;
1132
    }
1133
    
1134
    /**
1135
     * insert a document, return the id of the document that was inserted
1136
     */
1137
    protected String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
1138
        throws ServiceFailure {
1139
        logMetacat.debug("Starting to insert xml document...");
1140
        IdentifierManager im = IdentifierManager.getInstance();
1141

    
1142
        // generate guid/localId pair for sysmeta
1143
        String localId = null;
1144
        if(insertOrUpdate.equals("insert"))
1145
        {
1146
            localId = im.generateLocalId(guid.getValue(), 1);
1147
        }
1148
        else
1149
        {
1150
            //localid should already exist in the identifier table, so just find it
1151
            try
1152
            {
1153
                localId = im.getLocalId(guid.getValue());
1154
                //increment the revision
1155
                String docid = localId.substring(0, localId.lastIndexOf("."));
1156
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1157
                int rev = new Integer(revS).intValue();
1158
                rev++;
1159
                docid = docid + "." + rev;
1160
                localId = docid;
1161
            }
1162
            catch(McdbDocNotFoundException e)
1163
            {
1164
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1165
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1166
            }
1167
        }
1168
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1169
                localId);
1170

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