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.Date;
35
import java.util.Enumeration;
36
import java.util.Hashtable;
37
import java.util.Timer;
38
import java.util.List;
39

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

    
44
import org.apache.commons.io.IOUtils;
45
import org.apache.log4j.Logger;
46
import org.dataone.service.exceptions.IdentifierNotUnique;
47
import org.dataone.service.exceptions.InsufficientResources;
48
import org.dataone.service.exceptions.InvalidRequest;
49
import org.dataone.service.exceptions.InvalidSystemMetadata;
50
import org.dataone.service.exceptions.InvalidToken;
51
import org.dataone.service.exceptions.NotAuthorized;
52
import org.dataone.service.exceptions.NotFound;
53
import org.dataone.service.exceptions.NotImplemented;
54
import org.dataone.service.exceptions.ServiceFailure;
55
import org.dataone.service.exceptions.UnsupportedType;
56
import org.dataone.service.mn.MemberNodeCrud;
57
import org.dataone.service.types.AuthToken;
58
import org.dataone.service.types.Checksum;
59
import org.dataone.service.types.DescribeResponse;
60
import org.dataone.service.types.Identifier;
61
import org.dataone.service.types.LogRecordSet;
62
import org.dataone.service.types.SystemMetadata;
63
import org.jibx.runtime.BindingDirectory;
64
import org.jibx.runtime.IBindingFactory;
65
import org.jibx.runtime.IMarshallingContext;
66
import org.jibx.runtime.IUnmarshallingContext;
67
import org.jibx.runtime.JiBXException;
68

    
69
import com.gc.iotools.stream.is.InputStreamFromOutputStream;
70

    
71
import edu.ucsb.nceas.metacat.AccessionNumberException;
72
import edu.ucsb.nceas.metacat.DocumentImpl;
73
import edu.ucsb.nceas.metacat.EventLog;
74
import edu.ucsb.nceas.metacat.IdentifierManager;
75
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
76
import edu.ucsb.nceas.metacat.McdbException;
77
import edu.ucsb.nceas.metacat.MetacatHandler;
78
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
79
import edu.ucsb.nceas.metacat.properties.PropertyService;
80
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
81
import edu.ucsb.nceas.metacat.service.SessionService;
82
import edu.ucsb.nceas.metacat.util.DocumentUtil;
83
import edu.ucsb.nceas.metacat.util.SessionData;
84
import edu.ucsb.nceas.utilities.ParseLSIDException;
85
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
86

    
87
/**
88
 * 
89
 * Implements DataONE MemberNode CRUD API for Metacat. 
90
 * 
91
 * @author Matthew Jones
92
 */
93
public class CrudService implements MemberNodeCrud {
94

    
95
    /*private ServletContext servletContext;
96
    private HttpServletRequest request;
97
    private HttpServletResponse response;*/
98
    
99
    private static CrudService crudService = null;
100

    
101
    private MetacatHandler handler;
102
    private Hashtable<String, String[]> params;
103
    Logger logMetacat = null;
104
    
105
    private String metacatUrl;
106

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

    
149
        handler = new MetacatHandler(new Timer());
150

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

    
187
        logMetacat.debug("Starting CrudService.create()...");
188
        
189
        // authenticate & get user info
190
        SessionData sessionData = getSessionData(token);
191
        String username = sessionData.getUserName();
192
        String[] groups = sessionData.getGroupNames();
193

    
194
        // verify that guid == SystemMetadata.getIdentifier()
195
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
196
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
197
            throw new InvalidSystemMetadata(1180, 
198
                "GUID in method call does not match GUID in system metadata.");
199
        }
200

    
201
        logMetacat.debug("Checking if identifier exists...");
202
        // Check that the identifier does not already exist
203
        IdentifierManager im = IdentifierManager.getInstance();
204
        if (im.identifierExists(guid.getValue())) {
205
            throw new IdentifierNotUnique(1120, 
206
                "GUID is already in use by an existing object.");
207
        }
208

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

    
223
        } else {
224
            // DEFAULT CASE: DATA (needs to be checked and completed)
225
            insertDataObject(object, guid, sessionData);
226
            
227
        }
228

    
229
        // For Metadata and Data, insert the system metadata into the object store too
230
        insertSystemMetadata(sysmeta, sessionData);
231

    
232
        logMetacat.debug("Returning from CrudService.create()");
233
        return guid;
234
    }
235

    
236
    public Identifier delete(AuthToken token, Identifier guid)
237
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
238
            NotImplemented {
239
        throw new NotImplemented(1000, "This method not yet implemented.");
240
    }
241

    
242
    public DescribeResponse describe(AuthToken token, Identifier guid)
243
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
244
            NotImplemented {
245
        throw new NotImplemented(1000, "This method not yet implemented.");
246
    }
247
    
248
    public InputStream get(AuthToken token, Identifier guid)
249
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
250
            NotImplemented {
251
        
252
        // Retrieve the session information from the AuthToken
253
        // If the session is expired, then the user is 'public'
254
        final SessionData sessionData = getSessionData(token);
255
        
256
        // Look up the localId for this global identifier
257
        IdentifierManager im = IdentifierManager.getInstance();
258
        try {
259
            final String localId = im.getLocalId(guid.getValue());
260

    
261
            final InputStreamFromOutputStream<String> objectStream = 
262
                new InputStreamFromOutputStream<String>() {
263
                
264
                @Override
265
                public String produce(final OutputStream dataSink) throws Exception {
266

    
267
                    try {
268
                        handler.readFromMetacat(metacatUrl, null, 
269
                                dataSink, localId, "xml",
270
                                sessionData.getUserName(), 
271
                                sessionData.getGroupNames(), true, params);
272
                    } catch (PropertyNotFoundException e) {
273
                        throw new ServiceFailure(1030, e.getMessage());
274
                    } catch (ClassNotFoundException e) {
275
                        throw new ServiceFailure(1030, e.getMessage());
276
                    } catch (IOException e) {
277
                        throw new ServiceFailure(1030, e.getMessage());
278
                    } catch (SQLException e) {
279
                        throw new ServiceFailure(1030, e.getMessage());
280
                    } catch (McdbException e) {
281
                        throw new ServiceFailure(1030, e.getMessage());
282
                    } catch (ParseLSIDException e) {
283
                        throw new NotFound(1020, e.getMessage());
284
                    } catch (InsufficientKarmaException e) {
285
                        throw new NotAuthorized(1000, "Not authorized for get().");
286
                    }
287

    
288
                    return "Completed";
289
                }
290
            };
291
            return objectStream;
292

    
293
        } catch (McdbDocNotFoundException e) {
294
            throw new NotFound(1020, e.getMessage());
295
        }
296
    }
297

    
298
    public Checksum getChecksum(AuthToken token, Identifier guid)
299
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
300
            InvalidRequest, NotImplemented {
301
        throw new NotImplemented(1000, "This method not yet implemented.");
302
    }
303

    
304
    public Checksum getChecksum(AuthToken token, Identifier guid, 
305
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
306
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
307
        throw new NotImplemented(1000, "This method not yet implemented.");
308
    }
309

    
310
    public LogRecordSet getLogRecords(AuthToken token, Date fromDate, Date toDate)
311
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
312
            NotImplemented {
313
        throw new NotImplemented(1000, "This method not yet implemented.");
314
    }
315

    
316
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
317
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
318
            InvalidRequest, NotImplemented {
319
        
320
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
321
        
322
        // Retrieve the session information from the AuthToken
323
        // If the session is expired, then the user is 'public'
324
        final SessionData sessionData = getSessionData(token);
325

    
326
        // TODO: Check access control rules
327
                
328
        try {
329
            IdentifierManager im = IdentifierManager.getInstance();
330
            System.out.println("looking up systemmetadata id for guid " + guid.getValue());
331
            final String localId = im.getSystemMetadataId(guid.getValue());
332
            System.out.println("localId: " + localId);
333
            
334
            // Read system metadata from metacat's db
335
            final InputStreamFromOutputStream<String> objectStream = 
336
                new InputStreamFromOutputStream<String>() {
337
                
338
                @Override
339
                public String produce(final OutputStream dataSink) throws Exception {
340
                    try {
341
                        handler.readFromMetacat(metacatUrl, null, 
342
                                dataSink, localId, "xml",
343
                                sessionData.getUserName(), 
344
                                sessionData.getGroupNames(), true, params);
345
                    } catch (PropertyNotFoundException e) {
346
                        throw new ServiceFailure(1030, e.getMessage());
347
                    } catch (ClassNotFoundException e) {
348
                        throw new ServiceFailure(1030, e.getMessage());
349
                    } catch (IOException e) {
350
                        throw new ServiceFailure(1030, e.getMessage());
351
                    } catch (SQLException e) {
352
                        throw new ServiceFailure(1030, e.getMessage());
353
                    } catch (McdbException e) {
354
                        throw new ServiceFailure(1030, e.getMessage());
355
                    } catch (ParseLSIDException e) {
356
                        throw new NotFound(1020, e.getMessage());
357
                    } catch (InsufficientKarmaException e) {
358
                        throw new NotAuthorized(1000, "Not authorized for get().");
359
                    }
360

    
361
                    return "Completed";
362
                }
363
            };
364
            
365
            // Deserialize the xml to create a SystemMetadata object
366
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
367
            return sysmeta;
368
            
369
        } catch (McdbDocNotFoundException e) {
370
            //e.printStackTrace();
371
            throw new NotFound(1000, e.getMessage());
372
        }                
373
    }
374

    
375
    /**
376
     * update an existing object with a new object.  Change the system metadata
377
     * to reflect the changes and update it as well.
378
     */
379
    public Identifier update(AuthToken token, Identifier guid, 
380
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
381
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
382
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
383
            NotImplemented {
384
        try
385
        {
386
            SessionData sessionData = getSessionData(token);
387
            
388
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
389
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
390
            System.out.println("CS: got sm for obsoleteGuid: " + obsoletedGuid.getValue());
391
            //change sm.old's obsoletedBy field 
392
            List l = sm.getObsoletedByList();
393
            l.add(guid);
394
            sm.setObsoletedByList(l);
395
            System.out.println("CS: set obsoletedBy to id: " + ((Identifier)l.get(0)).getValue());
396
            //update sm.old
397
            System.out.println("CS: updating system metadata...");
398
            updateSystemMetadata(sm, sessionData);
399
            System.out.println("CS: updated system metadata.");
400
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
401
            System.out.println("CS: Adding obsoleteGuid to new sysmeta");
402
            sysmeta.addObsolete(obsoletedGuid);
403
            //insert sm.new
404
            System.out.println("CS: inserting new sysmeta");
405
            insertSystemMetadata(sysmeta, sessionData);
406
            //call update with sm.new.object.id for object
407
            //System.out.println("CS: updating old sm");
408
            //updateSystemMetadata(sm, sessionData);
409
            System.out.println("CS: updating doc");
410
            updateDocument(object, obsoletedGuid, guid, sessionData);
411
            System.out.println("CS: Done updating document.");
412
            return guid;
413
        }
414
        catch(Exception e)
415
        {
416
            throw new ServiceFailure(1030, "Error updating document in CrudService: " + e.getMessage());
417
        }
418
    }
419

    
420
    /*
421
     * Look up the information on the session using the token provided in
422
     * the AuthToken.  The Session should have all relevant user information.
423
     * If the session has expired or is invalid, the 'public' session will
424
     * be returned, giving the user anonymous access.
425
     */
426
    private static SessionData getSessionData(AuthToken token) {
427
        SessionData sessionData = null;
428
        String sessionId = "PUBLIC";
429
        if (token != null) {
430
            sessionId = token.getToken();
431
        }
432
        
433
        // if the session id is registered in SessionService, get the
434
        // SessionData for it. Otherwise, use the public session.
435
        if (SessionService.isSessionRegistered(sessionId)) {
436
            sessionData = SessionService.getRegisteredSession(sessionId);
437
        } else {
438
            sessionData = SessionService.getPublicSession();
439
        }
440
        
441
        return sessionData;
442
    }
443

    
444
    /** 
445
     * Determine if a given object should be treated as an XML science metadata
446
     * object. 
447
     * 
448
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
449
     * 
450
     * @param sysmeta the SystemMetadata describig the object
451
     * @return true if the object should be treated as science metadata
452
     */
453
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
454
        boolean scimeta = false;
455
        switch (sysmeta.getObjectFormat()) {
456
            case EML_2_1_0: scimeta = true; break;
457
            case EML_2_0_1: scimeta = true; break;
458
            case EML_2_0_0: scimeta = true; break;
459
            case FGDC_STD_001_1_1999: scimeta = true; break;
460
            case FGDC_STD_001_1998: scimeta = true; break;
461
            case NCML_2_2: scimeta = true; break;
462
        }
463
        
464
        return scimeta;
465
    }
466

    
467
    private void insertDataObject(InputStream object, Identifier guid, 
468
            SessionData sessionData) throws ServiceFailure {
469
        
470
        String username = sessionData.getUserName();
471
        String[] groups = sessionData.getGroupNames();
472

    
473
        // generate guid/localId pair for object
474
        logMetacat.debug("Generating a guid/localId mapping");
475
        IdentifierManager im = IdentifierManager.getInstance();
476
        String localId = im.generateLocalId(guid.getValue(), 1);
477

    
478
        try {
479
            logMetacat.debug("Case DATA: starting to write to disk.");
480
            if (DocumentImpl.getDataFileLockGrant(localId)) {
481
    
482
                // Save the data file to disk using "localId" as the name
483
                try {
484
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
485
    
486
                    File dataDirectory = new File(datafilepath);
487
                    dataDirectory.mkdirs();
488
    
489
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
490
    
491
                    // TODO: Check that the file size matches SystemMetadata
492
                    //                        long size = newFile.length();
493
                    //                        if (size == 0) {
494
                    //                            throw new IOException("Uploaded file is 0 bytes!");
495
                    //                        }
496
    
497
                    // Register the file in the database (which generates an exception
498
                    // if the localId is not acceptable or other untoward things happen
499
                    try {
500
                        logMetacat.debug("Registering document...");
501
                        DocumentImpl.registerDocument(localId, "BIN", localId,
502
                                username, groups);
503
                        logMetacat.debug("Registration step completed.");
504
                    } catch (SQLException e) {
505
                        //newFile.delete();
506
                        logMetacat.debug("SQLE: " + e.getMessage());
507
                        e.printStackTrace(System.out);
508
                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
509
                    } catch (AccessionNumberException e) {
510
                        //newFile.delete();
511
                        logMetacat.debug("ANE: " + e.getMessage());
512
                        e.printStackTrace(System.out);
513
                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
514
                    } catch (Exception e) {
515
                        //newFile.delete();
516
                        logMetacat.debug("Exception: " + e.getMessage());
517
                        e.printStackTrace(System.out);
518
                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
519
                    }
520
    
521
                    logMetacat.debug("Logging the creation event.");
522
                    EventLog.getInstance().log(metacatUrl,
523
                            username, localId, "create");
524
    
525
                    // Schedule replication for this data file
526
                    logMetacat.debug("Scheduling replication.");
527
                    ForceReplicationHandler frh = new ForceReplicationHandler(
528
                            localId, "insert", false, null);
529
    
530
                } catch (PropertyNotFoundException e) {
531
                    throw new ServiceFailure(1190, "Could not lock file for writing:" + e.getMessage());
532
                }
533
    
534
            }
535
        } catch (Exception e) {
536
            // Could not get a lock on the document, so we can not update the file now
537
            throw new ServiceFailure(1190, "Failed to lock file: " + e.getMessage());
538
        }
539
    }
540

    
541
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
542
        throws ServiceFailure {
543
        
544
        File newFile = new File(dir, fileName);
545
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
546

    
547
        try {
548
            if (newFile.createNewFile()) {
549
                // write data stream to desired file
550
                OutputStream os = new FileOutputStream(newFile);
551
                long length = IOUtils.copyLarge(data, os);
552
                os.flush();
553
                os.close();
554
            } else {
555
                logMetacat.debug("File creation failed, or file already exists.");
556
                throw new ServiceFailure(1190, "File already exists: " + fileName);
557
            }
558
        } catch (FileNotFoundException e) {
559
            logMetacat.debug("FNF: " + e.getMessage());
560
            throw new ServiceFailure(1190, "File not found: " + fileName + " " 
561
                    + e.getMessage());
562
        } catch (IOException e) {
563
            logMetacat.debug("IOE: " + e.getMessage());
564
            throw new ServiceFailure(1190, "File was not written: " + fileName 
565
                    + " " + e.getMessage());
566
        }
567

    
568
        return newFile;
569
    }
570

    
571
    /**
572
     * insert a systemMetadata doc
573
     */
574
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
575
        throws ServiceFailure {
576
        logMetacat.debug("Starting to insert SystemMetadata...");
577
    
578
        // generate guid/localId pair for sysmeta
579
        Identifier sysMetaGuid = new Identifier();
580
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
581
        sysmeta.setDateSysMetadataModified(new Date());
582

    
583
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
584
        String localId = insertDocument(xml, sysMetaGuid, sessionData);
585
        //insert the system metadata doc id into the identifiers table to 
586
        //link it to the data or metadata document
587
        System.out.println("mapping systemmetadata id to docid in im.insertSystemMetadata");
588
        IdentifierManager.getInstance().createSystemMetadataMapping(sysmeta.getIdentifier().getValue(), sysMetaGuid.getValue());
589
    }
590
    
591
    /**
592
     * update a systemMetadata doc
593
     */
594
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
595
      throws ServiceFailure
596
    {
597
        try
598
        {
599
            System.out.println("Updating SystemMetadata with id " + sm.getIdentifier().getValue());
600
            String smId = IdentifierManager.getInstance().getSystemMetadataId(sm.getIdentifier().getValue());
601
            System.out.println("smId: " + smId);
602
            sm.setDateSysMetadataModified(new Date());
603
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
604
            Identifier id = new Identifier();
605
            id.setValue(smId);
606
            System.out.println("updating sysmeta doc with new id " + id.getValue());
607
            String localId = updateDocument(xml, id, null, sessionData);
608
            System.out.println("new updated localId: " + localId);
609
            System.out.println("CS: updateDocument returned localId: " + localId);
610
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
611
        }
612
        catch(Exception e)
613
        {
614
            throw new ServiceFailure(1030, "Error updating system metadata: " + e.getMessage());
615
        }
616
    }
617
    
618
    /**
619
     * insert a document
620
     * NOTE: this method shouldn't be used from the update or create() methods.  
621
     * we shouldn't be putting the science metadata or data objects into memory.
622
     */
623
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
624
        throws ServiceFailure
625
    {
626
        return insertOrUpdateDocument(xml, guid, sessionData, "insert");
627
    }
628
    
629
    /**
630
     * insert a document from a stream
631
     */
632
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
633
      throws IOException, ServiceFailure
634
    {
635
        //HACK: change this eventually.  we should not be converting the stream to a string
636
        String xml = IOUtils.toString(is);
637
        return insertDocument(xml, guid, sessionData);
638
    }
639
    
640
    /**
641
     * update a document
642
     * NOTE: this method shouldn't be used from the update or create() methods.  
643
     * we shouldn't be putting the science metadata or data objects into memory.
644
     */
645
    private String updateDocument(String xml, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
646
        throws ServiceFailure
647
    {
648
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update");
649
    }
650
    
651
    /**
652
     * update a document from a stream
653
     */
654
    private String updateDocument(InputStream is, Identifier obsoleteGuid, Identifier guid, SessionData sessionData)
655
      throws IOException, ServiceFailure
656
    {
657
        //HACK: change this eventually.  we should not be converting the stream to a string
658
        String xml = IOUtils.toString(is);
659
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData);
660
        IdentifierManager im = IdentifierManager.getInstance();
661
        if(guid != null)
662
        {
663
          im.createMapping(guid.getValue(), localId);
664
        }
665
        return localId;
666
    }
667
    
668
    /**
669
     * insert a document, return the id of the document that was inserted
670
     */
671
    private String insertOrUpdateDocument(String xml, Identifier guid, SessionData sessionData, String insertOrUpdate) 
672
        throws ServiceFailure {
673
        logMetacat.debug("Starting to insert xml document...");
674
        IdentifierManager im = IdentifierManager.getInstance();
675

    
676
        // generate guid/localId pair for sysmeta
677
        String localId = null;
678
        if(insertOrUpdate.equals("insert"))
679
        {
680
            localId = im.generateLocalId(guid.getValue(), 1);
681
        }
682
        else
683
        {
684
            //localid should already exist in the identifier table, so just find it
685
            try
686
            {
687
                localId = im.getLocalId(guid.getValue());
688
                //increment the revision
689
                String docid = localId.substring(0, localId.lastIndexOf("."));
690
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
691
                int rev = new Integer(revS).intValue();
692
                rev++;
693
                docid = docid + "." + rev;
694
                localId = docid;
695
            }
696
            catch(McdbDocNotFoundException e)
697
            {
698
                throw new ServiceFailure(1030, "CrudService.insertOrUpdateDocument(): " +
699
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
700
            }
701
        }
702
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
703
                localId);
704

    
705
        String[] action = new String[1];
706
        action[0] = insertOrUpdate;
707
        params.put("action", action);
708
        String[] docid = new String[1];
709
        System.out.println(insertOrUpdate + "ing with localId " + localId);
710
        docid[0] = localId;
711
        params.put("docid", docid);
712
        String[] doctext = new String[1];
713
        doctext[0] = xml;
714
        logMetacat.debug(doctext[0]);
715
        params.put("doctext", doctext);
716
        
717
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
718
        // onto output stream, or alternatively, capture that and parse it to 
719
        // generate the right exceptions
720
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
721
        //PrintWriter pw = new PrintWriter(output);
722
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
723
                            null, params, sessionData.getUserName(), sessionData.getGroupNames());
724
        //String outputS = new String(output.toByteArray());
725
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
726
//        if (!(outputS.indexOf("<success>") > 0 && outputS.indexOf(localId) > 0)) {
727
//            throw new ServiceFailure(1190, outputS);
728
//        }
729
        logMetacat.debug("Finsished inserting xml document with id " + localId);
730
        return localId;
731
    }
732
    
733
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
734
        throws ServiceFailure {
735
        IBindingFactory bfact;
736
        ByteArrayOutputStream sysmetaOut = null;
737
        try {
738
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
739
            IMarshallingContext mctx = bfact.createMarshallingContext();
740
            sysmetaOut = new ByteArrayOutputStream();
741
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
742
        } catch (JiBXException e) {
743
            throw new ServiceFailure(1190, "Failed to serialize and insert SystemMetadata: " + e.getMessage());
744
        }
745
        
746
        return sysmetaOut;
747
    }
748
    
749
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
750
        throws ServiceFailure {
751
        try {
752
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
753
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
754
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
755
            return sysmeta;
756
        } catch (JiBXException e) {
757
            throw new ServiceFailure(1190, "Failed to serialize and insert SystemMetadata: " + e.getMessage());
758
        }    
759
    }
760
}
    (1-1/1)