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.sql.SQLException;
34
import java.util.*;
35
import java.text.DateFormat;
36

    
37
import javax.servlet.ServletContext;
38
import javax.servlet.http.HttpServletRequest;
39
import javax.servlet.http.HttpServletResponse;
40

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

    
61
import com.gc.iotools.stream.is.InputStreamFromOutputStream;
62

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

    
82
/**
83
 * 
84
 * Implements DataONE MemberNode CRUD API for Metacat. 
85
 * 
86
 * @author Matthew Jones
87
 */
88
public class CrudService implements MemberNodeCrud {
89

    
90
    /*private ServletContext servletContext;
91
    private HttpServletRequest request;
92
    private HttpServletResponse response;*/
93
    
94
    private static CrudService crudService = null;
95

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

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

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

    
146
    }
147
    
148
    /**
149
     * return the context url CrudService is using.
150
     */
151
    public String getContextUrl()
152
    {
153
        return metacatUrl;
154
    }
155
    
156
    /**
157
     * set the params for this service from an HttpServletRequest param list
158
     */
159
    public void setParamsFromRequest(HttpServletRequest request)
160
    {
161
        Enumeration paramlist = request.getParameterNames();
162
        while (paramlist.hasMoreElements()) {
163
            String name = (String) paramlist.nextElement();
164
            String[] value = (String[])request.getParameterValues(name);
165
            params.put(name, value);
166
        }
167
    }
168
    
169
    /**
170
     * Authenticate against metacat and get a token.
171
     * @param username
172
     * @param password
173
     * @return
174
     * @throws ServiceFailure
175
     */
176
    public AuthToken authenticate(String username, String password)
177
      throws ServiceFailure
178
    {
179
        try
180
        {
181
            MetacatRestClient restClient = new MetacatRestClient(getContextUrl());   
182
            String response = restClient.login(username, password);
183
            String sessionid = restClient.getSessionId();
184
            SessionService sessionService = SessionService.getInstance();
185
            sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
186
            AuthToken token = new AuthToken(sessionid);
187
            return token;
188
        }
189
        catch(Exception e)
190
        {
191
            throw new ServiceFailure("1000", "Error authenticating with metacat: " + e.getMessage());
192
        }
193
    }
194
    
195
    /**
196
     * set the parameter values needed for this request
197
     */
198
    public void setParameter(String name, String[] value)
199
    {
200
        params.put(name, value);
201
    }
202
    
203
    public Identifier create(AuthToken token, Identifier guid, 
204
            InputStream object, SystemMetadata sysmeta) throws InvalidToken, 
205
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
206
            InsufficientResources, InvalidSystemMetadata, NotImplemented {
207

    
208
        logMetacat.debug("Starting CrudService.create()...");
209
        
210
        // authenticate & get user info
211
        SessionData sessionData = getSessionData(token);
212
        String username = sessionData.getUserName();
213
        String[] groups = sessionData.getGroupNames();
214

    
215
        if (username == null || username.equals("public"))
216
        {
217
            throw new NotAuthorized("1000", "User " + username + " is not authorized to create content." +
218
                    "  If you are not logged in, please do so and retry the request.");
219
        }
220
        
221
        // verify that guid == SystemMetadata.getIdentifier()
222
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
223
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
224
            throw new InvalidSystemMetadata("1180", 
225
                "GUID in method call does not match GUID in system metadata.");
226
        }
227

    
228
        logMetacat.debug("Checking if identifier exists...");
229
        // Check that the identifier does not already exist
230
        IdentifierManager im = IdentifierManager.getInstance();
231
        if (im.identifierExists(guid.getValue())) {
232
            throw new IdentifierNotUnique("1120", 
233
                "GUID is already in use by an existing object.");
234
        }
235

    
236
        // Check if we are handling metadata or data
237
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
238
        
239
        if (isScienceMetadata) {
240
            // CASE METADATA:
241
            try {
242
                this.insertDocument(object, guid, sessionData);
243
            } catch (IOException e) {
244
                String msg = "Could not create string from XML stream: " +
245
                    " " + e.getMessage();
246
                logMetacat.debug(msg);
247
                throw new ServiceFailure("1190", msg);
248
            }
249

    
250
        } else {
251
            // DEFAULT CASE: DATA (needs to be checked and completed)
252
            insertDataObject(object, guid, sessionData);
253
            
254
        }
255

    
256
        // For Metadata and Data, insert the system metadata into the object store too
257
        insertSystemMetadata(sysmeta, sessionData);
258

    
259
        logMetacat.debug("Returning from CrudService.create()");
260
        return guid;
261
    }
262
    
263
    /**
264
     * update an existing object with a new object.  Change the system metadata
265
     * to reflect the changes and update it as well.
266
     */
267
    public Identifier update(AuthToken token, Identifier guid, 
268
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
269
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
270
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
271
            NotImplemented {
272
        try
273
        {
274
            SessionData sessionData = getSessionData(token);
275
            
276
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
277
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
278
            //change sm.old's obsoletedBy field 
279
            List l = sm.getObsoletedByList();
280
            l.add(guid);
281
            sm.setObsoletedByList(l);
282
            //update sm.old
283
            updateSystemMetadata(sm, sessionData);
284
            
285
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
286
            sysmeta.addObsolete(obsoletedGuid);
287
            //insert sm.new
288
            insertSystemMetadata(sysmeta, sessionData);
289
            
290
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
291
            if(isScienceMetadata)
292
            {
293
                //update the doc
294
                updateDocument(object, obsoletedGuid, guid, sessionData);
295
            }
296
            else
297
            {
298
                //update a data file, not xml
299
                insertDataObject(object, guid, sessionData);
300
            }
301
            return guid;
302
        }
303
        catch(Exception e)
304
        {
305
            throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
306
        }
307
    }
308
    
309
    /**
310
     * set the permission on the document
311
     * @param token
312
     * @param principal
313
     * @param permission
314
     * @param permissionType
315
     * @param permissionOrder
316
     * @return
317
     */
318
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
319
            String permissionType, String permissionOrder)
320
      throws ServiceFailure
321
    {
322
        try
323
        {
324
            IdentifierManager im = IdentifierManager.getInstance();
325
            String docid = im.getLocalId(id.getValue());
326
            final SessionData sessionData = getSessionData(token);
327
            String permNum = "0";
328
            if(permission.equals("read"))
329
            {
330
                permNum = "4";
331
            }
332
            else if(permission.equals("write"))
333
            {
334
                permNum = "6";
335
            }
336
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
337
                    principal, permNum, permissionType, permissionOrder);
338
        }
339
        catch(Exception e)
340
        {
341
            e.printStackTrace();
342
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
343
        }
344
    }
345
    
346
    /**
347
     *  Retrieve the list of objects present on the MN that match the calling 
348
     *  parameters. This method is required to support the process of Member 
349
     *  Node synchronization. At a minimum, this method should be able to 
350
     *  return a list of objects that match:
351
     *  startTime <= SystemMetadata.dateSysMetadataModified
352
     *  but is expected to also support date range (by also specifying endTime), 
353
     *  and should also support slicing of the matching set of records by 
354
     *  indicating the starting index of the response (where 0 is the index 
355
     *  of the first item) and the count of elements to be returned.
356
     *  
357
     *  If startTime or endTime is null, the query is not restricted by that parameter.
358
     *  
359
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
360
     * @param token
361
     * @param startTime
362
     * @param endTime
363
     * @param objectFormat
364
     * @param replicaStatus
365
     * @param start
366
     * @param count
367
     * @return ObjectList
368
     * @throws NotAuthorized
369
     * @throws InvalidRequest
370
     * @throws NotImplemented
371
     * @throws ServiceFailure
372
     * @throws InvalidToken
373
     */
374
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
375
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
376
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
377
    {
378
      ObjectList ol = new ObjectList();
379
      final SessionData sessionData = getSessionData(token);
380
      try
381
      {
382
          params.clear();
383
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
384
          params.put("qformat", new String[] {"xml"});
385
          params.put("returnfield", new String[] {"size", "originMemberNode", 
386
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum", "@algorithm"});
387
          params.put("anyfield", new String[] {"%"});
388
          
389
          MetacatResultSet rs = handler.query(metacatUrl, params, sessionData.getUserName(), 
390
                  sessionData.getGroupNames(), sessionData.getId());
391
          List docs = rs.getDocuments();
392

    
393
          if(count == 1000)
394
          {
395
              count = docs.size();
396
          }
397
          for(int i=start; i<count; i++)
398
          {
399
              //get the document from the results
400
              Document d = (Document)docs.get(i);
401
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
402
              if(objectFormat != null && !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
403
              { //make sure the objectFormat is the one specified
404
                  continue;
405
              }
406
              Date dateSysMetadataModified = parseDate(d.getField("dateSysMetadataModified"));
407
              int startDateComparison = 0;
408
              int endDateComparison = 0;
409
              if(startTime != null)
410
              {
411
                  startDateComparison = dateSysMetadataModified.compareTo(startTime);
412
              }
413
              
414
              if(endTime != null)
415
              {
416
                  endDateComparison = dateSysMetadataModified.compareTo(endTime);
417
              }
418
              
419
              if(startDateComparison < 0 || endDateComparison > 0)
420
              { //this date falls outside of the startTime and endTime params, so
421
                //skip it
422
                  continue;                  
423
              }
424
              
425
              ObjectInfo info = new ObjectInfo();
426
              //add the fields to the info object
427
              Checksum cs = new Checksum();
428
              cs.setValue(d.getField("checksum"));
429
              String csalg = d.getField("algorithm");
430
              if(csalg == null)
431
              {
432
                  csalg = "MD5";
433
              }
434
              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
435
              cs.setAlgorithm(ca);
436
              info.setChecksum(cs);
437
              info.setDateSysMetadataModified(dateSysMetadataModified);
438
              Identifier id = new Identifier();
439
              id.setValue(d.getField("identifier"));
440
              info.setIdentifier(id);
441
              info.setObjectFormat(returnedObjectFormat);
442
              info.setSize(new Long(d.getField("size").trim()).longValue());
443
              //add the ObjectInfo to the ObjectList
444
              ol.addObjectInfo(info);
445
              //System.out.println(d.toString());
446
          }
447
      }
448
      catch(Exception e)
449
      {
450
          e.printStackTrace();
451
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
452
      }
453
      return ol;
454
    }
455
    
456
    /**
457
     * Call listObjects with the default values for replicaStatus (true), start (0),
458
     * and count (1000).
459
     * @param token
460
     * @param startTime
461
     * @param endTime
462
     * @param objectFormat
463
     * @return
464
     * @throws NotAuthorized
465
     * @throws InvalidRequest
466
     * @throws NotImplemented
467
     * @throws ServiceFailure
468
     * @throws InvalidToken
469
     */
470
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
471
        ObjectFormat objectFormat)
472
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
473
    {
474
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
475
    }
476

    
477
    /**
478
     * Delete a document.  NOT IMPLEMENTED
479
     */
480
    public Identifier delete(AuthToken token, Identifier guid)
481
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
482
            NotImplemented {
483
        throw new NotImplemented("1000", "This method not yet implemented.");
484
    }
485

    
486
    /**
487
     * describe a document.  NOT IMPLEMENTED
488
     */
489
    public DescribeResponse describe(AuthToken token, Identifier guid)
490
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
491
            NotImplemented {
492
        throw new NotImplemented("1000", "This method not yet implemented.");
493
    }
494
    
495
    /**
496
     * get a document with a specified guid.
497
     */
498
    public InputStream get(AuthToken token, Identifier guid)
499
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
500
            NotImplemented {
501
        
502
        // Retrieve the session information from the AuthToken
503
        // If the session is expired, then the user is 'public'
504
        final SessionData sessionData = getSessionData(token);
505
        
506
        // Look up the localId for this global identifier
507
        IdentifierManager im = IdentifierManager.getInstance();
508
        try {
509
            final String localId = im.getLocalId(guid.getValue());
510

    
511
            final InputStreamFromOutputStream<String> objectStream = 
512
                new InputStreamFromOutputStream<String>() {
513
                
514
                @Override
515
                public String produce(final OutputStream dataSink) throws Exception {
516

    
517
                    try {
518
                        handler.readFromMetacat(metacatUrl, null, 
519
                                dataSink, localId, "xml",
520
                                sessionData.getUserName(), 
521
                                sessionData.getGroupNames(), true, params);
522
                    } catch (PropertyNotFoundException e) {
523
                        throw new ServiceFailure("1030", e.getMessage());
524
                    } catch (ClassNotFoundException e) {
525
                        throw new ServiceFailure("1030", e.getMessage());
526
                    } catch (IOException e) {
527
                        throw new ServiceFailure("1030", e.getMessage());
528
                    } catch (SQLException e) {
529
                        throw new ServiceFailure("1030", e.getMessage());
530
                    } catch (McdbException e) {
531
                        throw new ServiceFailure("1030", e.getMessage());
532
                    } catch (ParseLSIDException e) {
533
                        throw new NotFound("1020", e.getMessage());
534
                    } catch (InsufficientKarmaException e) {
535
                        throw new NotAuthorized("1000", "Not authorized for get().");
536
                    }
537

    
538
                    return "Completed";
539
                }
540
            };
541
            return objectStream;
542

    
543
        } catch (McdbDocNotFoundException e) {
544
            throw new NotFound("1020", e.getMessage());
545
        }
546
    }
547

    
548
    /**
549
     * get the checksum for a document.  NOT IMPLEMENTED
550
     */
551
    public Checksum getChecksum(AuthToken token, Identifier guid)
552
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
553
            InvalidRequest, NotImplemented {
554
        throw new NotImplemented("1000", "This method not yet implemented.");
555
    }
556

    
557
    /**
558
     * get the checksum for a document.  NOT IMPLEMENTED
559
     */
560
    public Checksum getChecksum(AuthToken token, Identifier guid, 
561
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
562
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
563
        throw new NotImplemented("1000", "This method not yet implemented.");
564
    }
565

    
566
    /**
567
     * get log records.  NOT IMPLEMENTED
568
     */
569
    public LogRecordSet getLogRecords(AuthToken token, Date fromDate, Date toDate)
570
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
571
            NotImplemented {
572
        throw new NotImplemented("1000", "This method not yet implemented.");
573
    }
574

    
575
    /**
576
     * get the system metadata for a document with a specified guid.
577
     */
578
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
579
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
580
            InvalidRequest, NotImplemented {
581
        
582
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
583
        
584
        // Retrieve the session information from the AuthToken
585
        // If the session is expired, then the user is 'public'
586
        final SessionData sessionData = getSessionData(token);
587

    
588
        // TODO: Check access control rules
589
                
590
        try {
591
            IdentifierManager im = IdentifierManager.getInstance();
592
            final String localId = im.getSystemMetadataId(guid.getValue());
593
            
594
            // Read system metadata from metacat's db
595
            final InputStreamFromOutputStream<String> objectStream = 
596
                new InputStreamFromOutputStream<String>() {
597
                
598
                @Override
599
                public String produce(final OutputStream dataSink) throws Exception {
600
                    try {
601
                        handler.readFromMetacat(metacatUrl, null, 
602
                                dataSink, localId, "xml",
603
                                sessionData.getUserName(), 
604
                                sessionData.getGroupNames(), true, params);
605
                    } catch (PropertyNotFoundException e) {
606
                        throw new ServiceFailure("1030", e.getMessage());
607
                    } catch (ClassNotFoundException e) {
608
                        throw new ServiceFailure("1030", e.getMessage());
609
                    } catch (IOException e) {
610
                        throw new ServiceFailure("1030", e.getMessage());
611
                    } catch (SQLException e) {
612
                        throw new ServiceFailure("1030", e.getMessage());
613
                    } catch (McdbException e) {
614
                        throw new ServiceFailure("1030", e.getMessage());
615
                    } catch (ParseLSIDException e) {
616
                        throw new NotFound("1020", e.getMessage());
617
                    } catch (InsufficientKarmaException e) {
618
                        throw new NotAuthorized("1000", "Not authorized for get().");
619
                    }
620

    
621
                    return "Completed";
622
                }
623
            };
624
            
625
            // Deserialize the xml to create a SystemMetadata object
626
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
627
            return sysmeta;
628
            
629
        } catch (McdbDocNotFoundException e) {
630
            //e.printStackTrace();
631
            throw new NotFound("1000", e.getMessage());
632
        }                
633
    }
634
    
635
    /**
636
     * parse the date in the systemMetadata
637
     * @param s
638
     * @return
639
     * @throws Exception
640
     */
641
    private Date parseDate(String s)
642
      throws Exception
643
    {
644
        Date d = null;
645
        int tIndex = s.indexOf("T");
646
        int zIndex = s.indexOf("Z");
647
        if(tIndex != -1 && zIndex != -1)
648
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
649
            //System.out.println("original date: " + s);
650
            
651
            String date = s.substring(0, tIndex);
652
            String year = date.substring(0, date.indexOf("-"));
653
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
654
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
655
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
656
                    " month: " + new Integer(month).intValue() + " day: " + 
657
                    new Integer(day).intValue());
658
            */
659
            String time = s.substring(tIndex + 1, zIndex);
660
            String hour = time.substring(0, time.indexOf(":"));
661
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
662
            String seconds = "00";
663
            String milliseconds = "00";
664
            if(time.indexOf(".") != -1)
665
            {
666
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
667
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
668
            }
669
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
670
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
671
                    new Integer(seconds).intValue() + " milli: " + 
672
                    new Integer(milliseconds).intValue());*/
673
            
674
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
675
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
676
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
677
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
678
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
679
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
680
            d = new Date(c.getTimeInMillis());
681
            //System.out.println("d: " + d);
682
            return d;
683
        }
684
        else
685
        {  //if it's not in the expected format, try the formatter
686
            return DateFormat.getDateTimeInstance().parse(s);
687
        }
688
    }
689

    
690
    /*
691
     * Look up the information on the session using the token provided in
692
     * the AuthToken.  The Session should have all relevant user information.
693
     * If the session has expired or is invalid, the 'public' session will
694
     * be returned, giving the user anonymous access.
695
     */
696
    private static SessionData getSessionData(AuthToken token) {
697
        SessionData sessionData = null;
698
        String sessionId = "PUBLIC";
699
        if (token != null) {
700
            sessionId = token.getToken();
701
        }
702
        
703
        // if the session id is registered in SessionService, get the
704
        // SessionData for it. Otherwise, use the public session.
705
        if (SessionService.getInstance().isSessionRegistered(sessionId)) {
706
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
707
        } else {
708
            sessionData = SessionService.getInstance().getPublicSession();
709
        }
710
        
711
        return sessionData;
712
    }
713

    
714
    /** 
715
     * Determine if a given object should be treated as an XML science metadata
716
     * object. 
717
     * 
718
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
719
     * 
720
     * @param sysmeta the SystemMetadata describig the object
721
     * @return true if the object should be treated as science metadata
722
     */
723
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
724
        boolean scimeta = false;
725
        switch (sysmeta.getObjectFormat()) {
726
            case EML_2_1_0: scimeta = true; break;
727
            case EML_2_0_1: scimeta = true; break;
728
            case EML_2_0_0: scimeta = true; break;
729
            case FGDC_STD_001_1_1999: scimeta = true; break;
730
            case FGDC_STD_001_1998: scimeta = true; break;
731
            case NCML_2_2: scimeta = true; break;
732
        }
733
        
734
        return scimeta;
735
    }
736

    
737
    /**
738
     * insert a data doc
739
     * @param object
740
     * @param guid
741
     * @param sessionData
742
     * @throws ServiceFailure
743
     */
744
    private void insertDataObject(InputStream object, Identifier guid, 
745
            SessionData sessionData) throws ServiceFailure {
746
        
747
        String username = sessionData.getUserName();
748
        String[] groups = sessionData.getGroupNames();
749

    
750
        // generate guid/localId pair for object
751
        logMetacat.debug("Generating a guid/localId mapping");
752
        IdentifierManager im = IdentifierManager.getInstance();
753
        String localId = im.generateLocalId(guid.getValue(), 1);
754

    
755
        try {
756
            logMetacat.debug("Case DATA: starting to write to disk.");
757
            if (DocumentImpl.getDataFileLockGrant(localId)) {
758
    
759
                // Save the data file to disk using "localId" as the name
760
                try {
761
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
762
    
763
                    File dataDirectory = new File(datafilepath);
764
                    dataDirectory.mkdirs();
765
    
766
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
767
    
768
                    // TODO: Check that the file size matches SystemMetadata
769
                    //                        long size = newFile.length();
770
                    //                        if (size == 0) {
771
                    //                            throw new IOException("Uploaded file is 0 bytes!");
772
                    //                        }
773
    
774
                    // Register the file in the database (which generates an exception
775
                    // if the localId is not acceptable or other untoward things happen
776
                    try {
777
                        logMetacat.debug("Registering document...");
778
                        System.out.println("inserting data object: localId: " + localId);
779
                        DocumentImpl.registerDocument(localId, "BIN", localId,
780
                                username, groups);
781
                        logMetacat.debug("Registration step completed.");
782
                    } catch (SQLException e) {
783
                        //newFile.delete();
784
                        logMetacat.debug("SQLE: " + e.getMessage());
785
                        e.printStackTrace(System.out);
786
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
787
                    } catch (AccessionNumberException e) {
788
                        //newFile.delete();
789
                        logMetacat.debug("ANE: " + e.getMessage());
790
                        e.printStackTrace(System.out);
791
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
792
                    } catch (Exception e) {
793
                        //newFile.delete();
794
                        logMetacat.debug("Exception: " + e.getMessage());
795
                        e.printStackTrace(System.out);
796
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
797
                    }
798
    
799
                    logMetacat.debug("Logging the creation event.");
800
                    EventLog.getInstance().log(metacatUrl,
801
                            username, localId, "create");
802
    
803
                    // Schedule replication for this data file
804
                    logMetacat.debug("Scheduling replication.");
805
                    ForceReplicationHandler frh = new ForceReplicationHandler(
806
                            localId, "insert", false, null);
807
    
808
                } catch (PropertyNotFoundException e) {
809
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
810
                }
811
    
812
            }
813
        } catch (Exception e) {
814
            // Could not get a lock on the document, so we can not update the file now
815
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
816
        }
817
    }
818

    
819
    /**
820
     * write a file to a stream
821
     * @param dir
822
     * @param fileName
823
     * @param data
824
     * @return
825
     * @throws ServiceFailure
826
     */
827
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
828
        throws ServiceFailure {
829
        
830
        File newFile = new File(dir, fileName);
831
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
832

    
833
        try {
834
            if (newFile.createNewFile()) {
835
                // write data stream to desired file
836
                OutputStream os = new FileOutputStream(newFile);
837
                long length = IOUtils.copyLarge(data, os);
838
                os.flush();
839
                os.close();
840
            } else {
841
                logMetacat.debug("File creation failed, or file already exists.");
842
                throw new ServiceFailure("1190", "File already exists: " + fileName);
843
            }
844
        } catch (FileNotFoundException e) {
845
            logMetacat.debug("FNF: " + e.getMessage());
846
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
847
                    + e.getMessage());
848
        } catch (IOException e) {
849
            logMetacat.debug("IOE: " + e.getMessage());
850
            throw new ServiceFailure("1190", "File was not written: " + fileName 
851
                    + " " + e.getMessage());
852
        }
853

    
854
        return newFile;
855
    }
856

    
857
    /**
858
     * insert a systemMetadata doc
859
     */
860
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
861
        throws ServiceFailure {
862
        logMetacat.debug("Starting to insert SystemMetadata...");
863
    
864
        // generate guid/localId pair for sysmeta
865
        Identifier sysMetaGuid = new Identifier();
866
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
867
        sysmeta.setDateSysMetadataModified(new Date());
868

    
869
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
870
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
871
        //insert the system metadata doc id into the identifiers table to 
872
        //link it to the data or metadata document
873
        IdentifierManager.getInstance().createSystemMetadataMapping(sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
874
    }
875
    
876
    /**
877
     * update a systemMetadata doc
878
     */
879
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
880
      throws ServiceFailure
881
    {
882
        try
883
        {
884
            String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
885
            sm.setDateSysMetadataModified(new Date());
886
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
887
            Identifier id = new Identifier();
888
            id.setValue(smId);
889
            String localId = updateDocument(xml, id, null, sessionData);
890
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
891
        }
892
        catch(Exception e)
893
        {
894
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
895
        }
896
    }
897
    
898
    /**
899
     * insert a document
900
     * NOTE: this method shouldn't be used from the update or create() methods.  
901
     * we shouldn't be putting the science metadata or data objects into memory.
902
     */
903
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
904
        throws ServiceFailure
905
    {
906
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
907
    }
908
    
909
    /**
910
     * insert a document from a stream
911
     */
912
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
913
      throws IOException, ServiceFailure
914
    {
915
        //HACK: change this eventually.  we should not be converting the stream to a string
916
        String xml = IOUtils.toString(is);
917
        return insertDocument(xml, guid, sessionData);
918
    }
919
    
920
    /**
921
     * update a document
922
     * NOTE: this method shouldn't be used from the update or create() methods.  
923
     * we shouldn't be putting the science metadata or data objects into memory.
924
     */
925
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
926
        throws ServiceFailure
927
    {
928
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
929
    }
930
    
931
    /**
932
     * update a document from a stream
933
     */
934
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
935
      throws IOException, ServiceFailure
936
    {
937
        //HACK: change this eventually.  we should not be converting the stream to a string
938
        String xml = IOUtils.toString(is);
939
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
940
        IdentifierManager im = IdentifierManager.getInstance();
941
        if(guid != null)
942
        {
943
          im.createMapping(guid.getValue(), localId);
944
        }
945
        return localId;
946
    }
947
    
948
    /**
949
     * insert a document, return the id of the document that was inserted
950
     */
951
    private String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
952
        throws ServiceFailure {
953
        logMetacat.debug("Starting to insert xml document...");
954
        IdentifierManager im = IdentifierManager.getInstance();
955

    
956
        // generate guid/localId pair for sysmeta
957
        String localId = null;
958
        if(insertOrUpdate.equals("insert"))
959
        {
960
            localId = im.generateLocalId(guid.getValue(), 1);
961
        }
962
        else
963
        {
964
            //localid should already exist in the identifier table, so just find it
965
            try
966
            {
967
                localId = im.getLocalId(guid.getValue());
968
                //increment the revision
969
                String docid = localId.substring(0, localId.lastIndexOf("."));
970
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
971
                int rev = new Integer(revS).intValue();
972
                rev++;
973
                docid = docid + "." + rev;
974
                localId = docid;
975
            }
976
            catch(McdbDocNotFoundException e)
977
            {
978
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
979
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
980
            }
981
        }
982
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
983
                localId);
984

    
985
        String[] action = new String[1];
986
        action[0] = insertOrUpdate;
987
        params.put("action", action);
988
        String[] docid = new String[1];
989
        docid[0] = localId;
990
        params.put("docid", docid);
991
        String[] doctext = new String[1];
992
        doctext[0] = xml;
993
        logMetacat.debug(doctext[0]);
994
        params.put("doctext", doctext);
995
        
996
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
997
        // onto output stream, or alternatively, capture that and parse it to 
998
        // generate the right exceptions
999
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1000
        //PrintWriter pw = new PrintWriter(output);
1001
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1002
                            null, params, sessionData.getUserName(), sessionData.getGroupNames());
1003
        //String outputS = new String(output.toByteArray());
1004
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1005
//        if (!(outputS.indexOf("<success>") > 0 && outputS.indexOf(localId) > 0)) {
1006
//            throw new ServiceFailure(1190, outputS);
1007
//        }
1008
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1009
        return localId;
1010
    }
1011
    
1012
    /**
1013
     * serialize a system metadata doc
1014
     * @param sysmeta
1015
     * @return
1016
     * @throws ServiceFailure
1017
     */
1018
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1019
        throws ServiceFailure {
1020
        IBindingFactory bfact;
1021
        ByteArrayOutputStream sysmetaOut = null;
1022
        try {
1023
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1024
            IMarshallingContext mctx = bfact.createMarshallingContext();
1025
            sysmetaOut = new ByteArrayOutputStream();
1026
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1027
        } catch (JiBXException e) {
1028
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1029
        }
1030
        
1031
        return sysmetaOut;
1032
    }
1033
    
1034
    /**
1035
     * deserialize a system metadata doc
1036
     * @param xml
1037
     * @return
1038
     * @throws ServiceFailure
1039
     */
1040
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1041
        throws ServiceFailure {
1042
        try {
1043
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1044
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1045
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1046
            return sysmeta;
1047
        } catch (JiBXException e) {
1048
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1049
        }    
1050
    }
1051
}
(1-1/2)