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.properties.PropertyService;
74
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
75
import edu.ucsb.nceas.metacat.service.SessionService;
76
import edu.ucsb.nceas.metacat.util.DocumentUtil;
77
import edu.ucsb.nceas.metacat.util.SessionData;
78
import edu.ucsb.nceas.utilities.ParseLSIDException;
79
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
80

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

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

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

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

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

    
145
    }
146
    
147
    /**
148
     * return the context url CrudService is using.
149
     */
150
    public String getContextUrl()
151
    {
152
        return metacatUrl;
153
    }
154
    
155
    /**
156
     * set the params for this service from an HttpServletRequest param list
157
     */
158
    public void setParamsFromRequest(HttpServletRequest request)
159
    {
160
        Enumeration paramlist = request.getParameterNames();
161
        while (paramlist.hasMoreElements()) {
162
            String name = (String) paramlist.nextElement();
163
            String[] value = (String[])request.getParameterValues(name);
164
            params.put(name, value);
165
        }
166
    }
167
    
168
    /**
169
     * set the parameter values needed for this request
170
     */
171
    public void setParameter(String name, String[] value)
172
    {
173
        params.put(name, value);
174
    }
175
    
176
    public Identifier create(AuthToken token, Identifier guid, 
177
            InputStream object, SystemMetadata sysmeta) throws InvalidToken, 
178
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
179
            InsufficientResources, InvalidSystemMetadata, NotImplemented {
180

    
181
        logMetacat.debug("Starting CrudService.create()...");
182
        
183
        // authenticate & get user info
184
        SessionData sessionData = getSessionData(token);
185
        String username = sessionData.getUserName();
186
        String[] groups = sessionData.getGroupNames();
187

    
188
        // verify that guid == SystemMetadata.getIdentifier()
189
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
190
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
191
            throw new InvalidSystemMetadata("1180", 
192
                "GUID in method call does not match GUID in system metadata.");
193
        }
194

    
195
        logMetacat.debug("Checking if identifier exists...");
196
        // Check that the identifier does not already exist
197
        IdentifierManager im = IdentifierManager.getInstance();
198
        if (im.identifierExists(guid.getValue())) {
199
            throw new IdentifierNotUnique("1120", 
200
                "GUID is already in use by an existing object.");
201
        }
202

    
203
        // Check if we are handling metadata or data
204
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
205
        
206
        if (isScienceMetadata) {
207
            // CASE METADATA:
208
            try {
209
                this.insertDocument(object, guid, sessionData);
210
            } catch (IOException e) {
211
                String msg = "Could not create string from XML stream: " +
212
                    " " + e.getMessage();
213
                logMetacat.debug(msg);
214
                throw new ServiceFailure("1190", msg);
215
            }
216

    
217
        } else {
218
            // DEFAULT CASE: DATA (needs to be checked and completed)
219
            insertDataObject(object, guid, sessionData);
220
            
221
        }
222

    
223
        // For Metadata and Data, insert the system metadata into the object store too
224
        insertSystemMetadata(sysmeta, sessionData);
225

    
226
        logMetacat.debug("Returning from CrudService.create()");
227
        return guid;
228
    }
229
    
230
    /**
231
     * update an existing object with a new object.  Change the system metadata
232
     * to reflect the changes and update it as well.
233
     */
234
    public Identifier update(AuthToken token, Identifier guid, 
235
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
236
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
237
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
238
            NotImplemented {
239
        try
240
        {
241
            SessionData sessionData = getSessionData(token);
242
            
243
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
244
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
245
            //change sm.old's obsoletedBy field 
246
            List l = sm.getObsoletedByList();
247
            l.add(guid);
248
            sm.setObsoletedByList(l);
249
            //update sm.old
250
            updateSystemMetadata(sm, sessionData);
251
            
252
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
253
            sysmeta.addObsolete(obsoletedGuid);
254
            //insert sm.new
255
            insertSystemMetadata(sysmeta, sessionData);
256
            
257
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
258
            if(isScienceMetadata)
259
            {
260
                //update the doc
261
                updateDocument(object, obsoletedGuid, guid, sessionData);
262
            }
263
            else
264
            {
265
                //update a data file, not xml
266
                insertDataObject(object, guid, sessionData);
267
            }
268
            return guid;
269
        }
270
        catch(Exception e)
271
        {
272
            throw new ServiceFailure("1030", "Error updating document in CrudService: " + e.getMessage());
273
        }
274
    }
275
    
276
    /**
277
     * set the permission on the document
278
     * @param token
279
     * @param principal
280
     * @param permission
281
     * @param permissionType
282
     * @param permissionOrder
283
     * @return
284
     */
285
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
286
            String permissionType, String permissionOrder)
287
      throws ServiceFailure
288
    {
289
        try
290
        {
291
            IdentifierManager im = IdentifierManager.getInstance();
292
            String docid = im.getLocalId(id.getValue());
293
            final SessionData sessionData = getSessionData(token);
294
            String permNum = "0";
295
            if(permission == "read")
296
            {
297
                permNum = "4";
298
            }
299
            else if(permission == "write")
300
            {
301
                permNum = "6";
302
            }
303
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
304
                    principal, permNum, permissionType, permissionOrder);
305
        }
306
        catch(Exception e)
307
        {
308
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
309
        }
310
    }
311
    
312
    /**
313
     *  Retrieve the list of objects present on the MN that match the calling 
314
     *  parameters. This method is required to support the process of Member 
315
     *  Node synchronization. At a minimum, this method should be able to 
316
     *  return a list of objects that match:
317
     *  startTime <= SystemMetadata.dateSysMetadataModified
318
     *  but is expected to also support date range (by also specifying endTime), 
319
     *  and should also support slicing of the matching set of records by 
320
     *  indicating the starting index of the response (where 0 is the index 
321
     *  of the first item) and the count of elements to be returned.
322
     *  
323
     *  If startTime or endTime is null, the query is not restricted by that parameter.
324
     *  
325
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
326
     * @param token
327
     * @param startTime
328
     * @param endTime
329
     * @param objectFormat
330
     * @param replicaStatus
331
     * @param start
332
     * @param count
333
     * @return ObjectList
334
     * @throws NotAuthorized
335
     * @throws InvalidRequest
336
     * @throws NotImplemented
337
     * @throws ServiceFailure
338
     * @throws InvalidToken
339
     */
340
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
341
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
342
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
343
    {
344
      ObjectList ol = new ObjectList();
345
      final SessionData sessionData = getSessionData(token);
346
      try
347
      {
348
          params.clear();
349
          params.put("returndoctype", new String[] {"http://dataone.org/service/types/SystemMetadata/0.1"});
350
          params.put("qformat", new String[] {"xml"});
351
          params.put("returnfield", new String[] {"size", "originMemberNode", 
352
                  "identifier", "objectFormat", "dateSysMetadataModified", "checksum"});
353
          params.put("anyfield", new String[] {"%"});
354
          
355
          MetacatResultSet rs = handler.query(metacatUrl, params, sessionData.getUserName(), 
356
                  sessionData.getGroupNames(), sessionData.getId());
357
          List docs = rs.getDocuments();
358
          
359
          if(count == 1000)
360
          {
361
              count = docs.size();
362
          }
363
          for(int i=start; i<count; i++)
364
          {
365
              //get the document from the results
366
              Document d = (Document)docs.get(i);
367
              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
368
              if(objectFormat != null && !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
369
              { //make sure the objectFormat is the one specified
370
                  continue;
371
              }
372
              Date dateSysMetadataModified = parseDate(d.getField("dateSysMetadataModified"));
373
              int startDateComparison = 0;
374
              int endDateComparison = 0;
375
              if(startTime != null)
376
              {
377
                  startDateComparison = dateSysMetadataModified.compareTo(startTime);
378
              }
379
              
380
              if(endTime != null)
381
              {
382
                  endDateComparison = dateSysMetadataModified.compareTo(endTime);
383
              }
384
              
385
              if(startDateComparison < 0 || endDateComparison > 0)
386
              { //this date falls outside of the startTime and endTime params, so
387
                //skip it
388
                  continue;                  
389
              }
390
              
391
              ObjectInfo info = new ObjectInfo();
392
              //add the fields to the info object
393
              Checksum cs = new Checksum();
394
              cs.setValue(d.getField("checksum"));
395
              info.setChecksum(cs);
396
              info.setDateSysMetadataModified(dateSysMetadataModified);
397
              Identifier id = new Identifier();
398
              id.setValue(d.getField("identifier"));
399
              info.setIdentifier(id);
400
              info.setObjectFormat(returnedObjectFormat);
401
              info.setSize(new Long(d.getField("size").trim()).longValue());
402
              //add the ObjectInfo to the ObjectList
403
              ol.addObjectInfo(info);
404
              //System.out.println(d.toString());
405
          }
406
      }
407
      catch(Exception e)
408
      {
409
          e.printStackTrace();
410
          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
411
      }
412
      return ol;
413
    }
414
    
415
    /**
416
     * Call listObjects with the default values for replicaStatus (true), start (0),
417
     * and count (1000).
418
     * @param token
419
     * @param startTime
420
     * @param endTime
421
     * @param objectFormat
422
     * @return
423
     * @throws NotAuthorized
424
     * @throws InvalidRequest
425
     * @throws NotImplemented
426
     * @throws ServiceFailure
427
     * @throws InvalidToken
428
     */
429
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
430
        ObjectFormat objectFormat)
431
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
432
    {
433
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
434
    }
435

    
436
    /**
437
     * Delete a document.  NOT IMPLEMENTED
438
     */
439
    public Identifier delete(AuthToken token, Identifier guid)
440
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
441
            NotImplemented {
442
        throw new NotImplemented("1000", "This method not yet implemented.");
443
    }
444

    
445
    /**
446
     * describe a document.  NOT IMPLEMENTED
447
     */
448
    public DescribeResponse describe(AuthToken token, Identifier guid)
449
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
450
            NotImplemented {
451
        throw new NotImplemented("1000", "This method not yet implemented.");
452
    }
453
    
454
    /**
455
     * get a document with a specified guid.
456
     */
457
    public InputStream get(AuthToken token, Identifier guid)
458
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
459
            NotImplemented {
460
        
461
        // Retrieve the session information from the AuthToken
462
        // If the session is expired, then the user is 'public'
463
        final SessionData sessionData = getSessionData(token);
464
        
465
        // Look up the localId for this global identifier
466
        IdentifierManager im = IdentifierManager.getInstance();
467
        try {
468
            final String localId = im.getLocalId(guid.getValue());
469

    
470
            final InputStreamFromOutputStream<String> objectStream = 
471
                new InputStreamFromOutputStream<String>() {
472
                
473
                @Override
474
                public String produce(final OutputStream dataSink) throws Exception {
475

    
476
                    try {
477
                        handler.readFromMetacat(metacatUrl, null, 
478
                                dataSink, localId, "xml",
479
                                sessionData.getUserName(), 
480
                                sessionData.getGroupNames(), true, params);
481
                    } catch (PropertyNotFoundException e) {
482
                        throw new ServiceFailure("1030", e.getMessage());
483
                    } catch (ClassNotFoundException e) {
484
                        throw new ServiceFailure("1030", e.getMessage());
485
                    } catch (IOException e) {
486
                        throw new ServiceFailure("1030", e.getMessage());
487
                    } catch (SQLException e) {
488
                        throw new ServiceFailure("1030", e.getMessage());
489
                    } catch (McdbException e) {
490
                        throw new ServiceFailure("1030", e.getMessage());
491
                    } catch (ParseLSIDException e) {
492
                        throw new NotFound("1020", e.getMessage());
493
                    } catch (InsufficientKarmaException e) {
494
                        throw new NotAuthorized("1000", "Not authorized for get().");
495
                    }
496

    
497
                    return "Completed";
498
                }
499
            };
500
            return objectStream;
501

    
502
        } catch (McdbDocNotFoundException e) {
503
            throw new NotFound("1020", e.getMessage());
504
        }
505
    }
506

    
507
    /**
508
     * get the checksum for a document.  NOT IMPLEMENTED
509
     */
510
    public Checksum getChecksum(AuthToken token, Identifier guid)
511
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
512
            InvalidRequest, NotImplemented {
513
        throw new NotImplemented("1000", "This method not yet implemented.");
514
    }
515

    
516
    /**
517
     * get the checksum for a document.  NOT IMPLEMENTED
518
     */
519
    public Checksum getChecksum(AuthToken token, Identifier guid, 
520
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
521
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
522
        throw new NotImplemented("1000", "This method not yet implemented.");
523
    }
524

    
525
    /**
526
     * get log records.  NOT IMPLEMENTED
527
     */
528
    public LogRecordSet getLogRecords(AuthToken token, Date fromDate, Date toDate)
529
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
530
            NotImplemented {
531
        throw new NotImplemented("1000", "This method not yet implemented.");
532
    }
533

    
534
    /**
535
     * get the system metadata for a document with a specified guid.
536
     */
537
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
538
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
539
            InvalidRequest, NotImplemented {
540
        
541
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
542
        
543
        // Retrieve the session information from the AuthToken
544
        // If the session is expired, then the user is 'public'
545
        final SessionData sessionData = getSessionData(token);
546

    
547
        // TODO: Check access control rules
548
                
549
        try {
550
            IdentifierManager im = IdentifierManager.getInstance();
551
            final String localId = im.getSystemMetadataId(guid.getValue());
552
            
553
            // Read system metadata from metacat's db
554
            final InputStreamFromOutputStream<String> objectStream = 
555
                new InputStreamFromOutputStream<String>() {
556
                
557
                @Override
558
                public String produce(final OutputStream dataSink) throws Exception {
559
                    try {
560
                        handler.readFromMetacat(metacatUrl, null, 
561
                                dataSink, localId, "xml",
562
                                sessionData.getUserName(), 
563
                                sessionData.getGroupNames(), true, params);
564
                    } catch (PropertyNotFoundException e) {
565
                        throw new ServiceFailure("1030", e.getMessage());
566
                    } catch (ClassNotFoundException e) {
567
                        throw new ServiceFailure("1030", e.getMessage());
568
                    } catch (IOException e) {
569
                        throw new ServiceFailure("1030", e.getMessage());
570
                    } catch (SQLException e) {
571
                        throw new ServiceFailure("1030", e.getMessage());
572
                    } catch (McdbException e) {
573
                        throw new ServiceFailure("1030", e.getMessage());
574
                    } catch (ParseLSIDException e) {
575
                        throw new NotFound("1020", e.getMessage());
576
                    } catch (InsufficientKarmaException e) {
577
                        throw new NotAuthorized("1000", "Not authorized for get().");
578
                    }
579

    
580
                    return "Completed";
581
                }
582
            };
583
            
584
            // Deserialize the xml to create a SystemMetadata object
585
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
586
            return sysmeta;
587
            
588
        } catch (McdbDocNotFoundException e) {
589
            //e.printStackTrace();
590
            throw new NotFound("1000", e.getMessage());
591
        }                
592
    }
593
    
594
    /**
595
     * parse the date in the systemMetadata
596
     * @param s
597
     * @return
598
     * @throws Exception
599
     */
600
    private Date parseDate(String s)
601
      throws Exception
602
    {
603
        Date d = null;
604
        int tIndex = s.indexOf("T");
605
        int zIndex = s.indexOf("Z");
606
        if(tIndex != -1 && zIndex != -1)
607
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
608
            //System.out.println("original date: " + s);
609
            
610
            String date = s.substring(0, tIndex);
611
            String year = date.substring(0, date.indexOf("-"));
612
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
613
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
614
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
615
                    " month: " + new Integer(month).intValue() + " day: " + 
616
                    new Integer(day).intValue());
617
            */
618
            String time = s.substring(tIndex + 1, zIndex);
619
            String hour = time.substring(0, time.indexOf(":"));
620
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
621
            String seconds = "00";
622
            String milliseconds = "00";
623
            if(time.indexOf(".") != -1)
624
            {
625
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
626
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
627
            }
628
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
629
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
630
                    new Integer(seconds).intValue() + " milli: " + 
631
                    new Integer(milliseconds).intValue());*/
632
            
633
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
634
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
635
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
636
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
637
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
638
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
639
            d = new Date(c.getTimeInMillis());
640
            //System.out.println("d: " + d);
641
            return d;
642
        }
643
        else
644
        {  //if it's not in the expected format, try the formatter
645
            return DateFormat.getDateTimeInstance().parse(s);
646
        }
647
    }
648

    
649
    /*
650
     * Look up the information on the session using the token provided in
651
     * the AuthToken.  The Session should have all relevant user information.
652
     * If the session has expired or is invalid, the 'public' session will
653
     * be returned, giving the user anonymous access.
654
     */
655
    private static SessionData getSessionData(AuthToken token) {
656
        SessionData sessionData = null;
657
        String sessionId = "PUBLIC";
658
        if (token != null) {
659
            sessionId = token.getToken();
660
        }
661
        
662
        // if the session id is registered in SessionService, get the
663
        // SessionData for it. Otherwise, use the public session.
664
        if (SessionService.isSessionRegistered(sessionId)) {
665
            sessionData = SessionService.getRegisteredSession(sessionId);
666
        } else {
667
            sessionData = SessionService.getPublicSession();
668
        }
669
        
670
        return sessionData;
671
    }
672

    
673
    /** 
674
     * Determine if a given object should be treated as an XML science metadata
675
     * object. 
676
     * 
677
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
678
     * 
679
     * @param sysmeta the SystemMetadata describig the object
680
     * @return true if the object should be treated as science metadata
681
     */
682
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
683
        boolean scimeta = false;
684
        switch (sysmeta.getObjectFormat()) {
685
            case EML_2_1_0: scimeta = true; break;
686
            case EML_2_0_1: scimeta = true; break;
687
            case EML_2_0_0: scimeta = true; break;
688
            case FGDC_STD_001_1_1999: scimeta = true; break;
689
            case FGDC_STD_001_1998: scimeta = true; break;
690
            case NCML_2_2: scimeta = true; break;
691
        }
692
        
693
        return scimeta;
694
    }
695

    
696
    /**
697
     * insert a data doc
698
     * @param object
699
     * @param guid
700
     * @param sessionData
701
     * @throws ServiceFailure
702
     */
703
    private void insertDataObject(InputStream object, Identifier guid, 
704
            SessionData sessionData) throws ServiceFailure {
705
        
706
        String username = sessionData.getUserName();
707
        String[] groups = sessionData.getGroupNames();
708

    
709
        // generate guid/localId pair for object
710
        logMetacat.debug("Generating a guid/localId mapping");
711
        IdentifierManager im = IdentifierManager.getInstance();
712
        String localId = im.generateLocalId(guid.getValue(), 1);
713

    
714
        try {
715
            logMetacat.debug("Case DATA: starting to write to disk.");
716
            if (DocumentImpl.getDataFileLockGrant(localId)) {
717
    
718
                // Save the data file to disk using "localId" as the name
719
                try {
720
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
721
    
722
                    File dataDirectory = new File(datafilepath);
723
                    dataDirectory.mkdirs();
724
    
725
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
726
    
727
                    // TODO: Check that the file size matches SystemMetadata
728
                    //                        long size = newFile.length();
729
                    //                        if (size == 0) {
730
                    //                            throw new IOException("Uploaded file is 0 bytes!");
731
                    //                        }
732
    
733
                    // Register the file in the database (which generates an exception
734
                    // if the localId is not acceptable or other untoward things happen
735
                    try {
736
                        logMetacat.debug("Registering document...");
737
                        System.out.println("inserting data object: localId: " + localId);
738
                        DocumentImpl.registerDocument(localId, "BIN", localId,
739
                                username, groups);
740
                        logMetacat.debug("Registration step completed.");
741
                    } catch (SQLException e) {
742
                        //newFile.delete();
743
                        logMetacat.debug("SQLE: " + e.getMessage());
744
                        e.printStackTrace(System.out);
745
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
746
                    } catch (AccessionNumberException e) {
747
                        //newFile.delete();
748
                        logMetacat.debug("ANE: " + e.getMessage());
749
                        e.printStackTrace(System.out);
750
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
751
                    } catch (Exception e) {
752
                        //newFile.delete();
753
                        logMetacat.debug("Exception: " + e.getMessage());
754
                        e.printStackTrace(System.out);
755
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
756
                    }
757
    
758
                    logMetacat.debug("Logging the creation event.");
759
                    EventLog.getInstance().log(metacatUrl,
760
                            username, localId, "create");
761
    
762
                    // Schedule replication for this data file
763
                    logMetacat.debug("Scheduling replication.");
764
                    ForceReplicationHandler frh = new ForceReplicationHandler(
765
                            localId, "insert", false, null);
766
    
767
                } catch (PropertyNotFoundException e) {
768
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
769
                }
770
    
771
            }
772
        } catch (Exception e) {
773
            // Could not get a lock on the document, so we can not update the file now
774
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
775
        }
776
    }
777

    
778
    /**
779
     * write a file to a stream
780
     * @param dir
781
     * @param fileName
782
     * @param data
783
     * @return
784
     * @throws ServiceFailure
785
     */
786
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
787
        throws ServiceFailure {
788
        
789
        File newFile = new File(dir, fileName);
790
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
791

    
792
        try {
793
            if (newFile.createNewFile()) {
794
                // write data stream to desired file
795
                OutputStream os = new FileOutputStream(newFile);
796
                long length = IOUtils.copyLarge(data, os);
797
                os.flush();
798
                os.close();
799
            } else {
800
                logMetacat.debug("File creation failed, or file already exists.");
801
                throw new ServiceFailure("1190", "File already exists: " + fileName);
802
            }
803
        } catch (FileNotFoundException e) {
804
            logMetacat.debug("FNF: " + e.getMessage());
805
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
806
                    + e.getMessage());
807
        } catch (IOException e) {
808
            logMetacat.debug("IOE: " + e.getMessage());
809
            throw new ServiceFailure("1190", "File was not written: " + fileName 
810
                    + " " + e.getMessage());
811
        }
812

    
813
        return newFile;
814
    }
815

    
816
    /**
817
     * insert a systemMetadata doc
818
     */
819
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
820
        throws ServiceFailure {
821
        logMetacat.debug("Starting to insert SystemMetadata...");
822
    
823
        // generate guid/localId pair for sysmeta
824
        Identifier sysMetaGuid = new Identifier();
825
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
826
        sysmeta.setDateSysMetadataModified(new Date());
827

    
828
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
829
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
830
        //insert the system metadata doc id into the identifiers table to 
831
        //link it to the data or metadata document
832
        IdentifierManager.getInstance().createSystemMetadataMapping(sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
833
    }
834
    
835
    /**
836
     * update a systemMetadata doc
837
     */
838
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
839
      throws ServiceFailure
840
    {
841
        try
842
        {
843
            String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
844
            sm.setDateSysMetadataModified(new Date());
845
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
846
            Identifier id = new Identifier();
847
            id.setValue(smId);
848
            String localId = updateDocument(xml, id, null, sessionData);
849
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
850
        }
851
        catch(Exception e)
852
        {
853
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getMessage());
854
        }
855
    }
856
    
857
    /**
858
     * insert a document
859
     * NOTE: this method shouldn't be used from the update or create() methods.  
860
     * we shouldn't be putting the science metadata or data objects into memory.
861
     */
862
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
863
        throws ServiceFailure
864
    {
865
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
866
    }
867
    
868
    /**
869
     * insert a document from a stream
870
     */
871
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
872
      throws IOException, ServiceFailure
873
    {
874
        //HACK: change this eventually.  we should not be converting the stream to a string
875
        String xml = IOUtils.toString(is);
876
        return insertDocument(xml, guid, sessionData);
877
    }
878
    
879
    /**
880
     * update a document
881
     * NOTE: this method shouldn't be used from the update or create() methods.  
882
     * we shouldn't be putting the science metadata or data objects into memory.
883
     */
884
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
885
        throws ServiceFailure
886
    {
887
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
888
    }
889
    
890
    /**
891
     * update a document from a stream
892
     */
893
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
894
      throws IOException, ServiceFailure
895
    {
896
        //HACK: change this eventually.  we should not be converting the stream to a string
897
        String xml = IOUtils.toString(is);
898
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
899
        IdentifierManager im = IdentifierManager.getInstance();
900
        if(guid != null)
901
        {
902
          im.createMapping(guid.getValue(), localId);
903
        }
904
        return localId;
905
    }
906
    
907
    /**
908
     * insert a document, return the id of the document that was inserted
909
     */
910
    private String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
911
        throws ServiceFailure {
912
        logMetacat.debug("Starting to insert xml document...");
913
        IdentifierManager im = IdentifierManager.getInstance();
914

    
915
        // generate guid/localId pair for sysmeta
916
        String localId = null;
917
        if(insertOrUpdate.equals("insert"))
918
        {
919
            localId = im.generateLocalId(guid.getValue(), 1);
920
        }
921
        else
922
        {
923
            //localid should already exist in the identifier table, so just find it
924
            try
925
            {
926
                localId = im.getLocalId(guid.getValue());
927
                //increment the revision
928
                String docid = localId.substring(0, localId.lastIndexOf("."));
929
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
930
                int rev = new Integer(revS).intValue();
931
                rev++;
932
                docid = docid + "." + rev;
933
                localId = docid;
934
            }
935
            catch(McdbDocNotFoundException e)
936
            {
937
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
938
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
939
            }
940
        }
941
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
942
                localId);
943

    
944
        String[] action = new String[1];
945
        action[0] = insertOrUpdate;
946
        params.put("action", action);
947
        String[] docid = new String[1];
948
        docid[0] = localId;
949
        params.put("docid", docid);
950
        String[] doctext = new String[1];
951
        doctext[0] = xml;
952
        logMetacat.debug(doctext[0]);
953
        params.put("doctext", doctext);
954
        
955
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
956
        // onto output stream, or alternatively, capture that and parse it to 
957
        // generate the right exceptions
958
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
959
        //PrintWriter pw = new PrintWriter(output);
960
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
961
                            null, params, sessionData.getUserName(), sessionData.getGroupNames());
962
        //String outputS = new String(output.toByteArray());
963
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
964
//        if (!(outputS.indexOf("<success>") > 0 && outputS.indexOf(localId) > 0)) {
965
//            throw new ServiceFailure(1190, outputS);
966
//        }
967
        logMetacat.debug("Finsished inserting xml document with id " + localId);
968
        return localId;
969
    }
970
    
971
    /**
972
     * serialize a system metadata doc
973
     * @param sysmeta
974
     * @return
975
     * @throws ServiceFailure
976
     */
977
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
978
        throws ServiceFailure {
979
        IBindingFactory bfact;
980
        ByteArrayOutputStream sysmetaOut = null;
981
        try {
982
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
983
            IMarshallingContext mctx = bfact.createMarshallingContext();
984
            sysmetaOut = new ByteArrayOutputStream();
985
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
986
        } catch (JiBXException e) {
987
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
988
        }
989
        
990
        return sysmetaOut;
991
    }
992
    
993
    /**
994
     * deserialize a system metadata doc
995
     * @param xml
996
     * @return
997
     * @throws ServiceFailure
998
     */
999
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1000
        throws ServiceFailure {
1001
        try {
1002
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1003
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1004
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1005
            return sysmeta;
1006
        } catch (JiBXException e) {
1007
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1008
        }    
1009
    }
1010
}
    (1-1/1)