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

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

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

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

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

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

    
94
    private ServletContext servletContext;
95
    private HttpServletRequest request;
96
    private HttpServletResponse response;
97

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

    
102
    /**
103
     * Initializes new instance by setting servlet context,request and response.
104
     * TODO: remove dependency on Servlet infrastructure
105
     * TODO: Make this a real service, and make it a Singleton
106
     */
107
    public CrudService(ServletContext servletContext,
108
            HttpServletRequest request, HttpServletResponse response) {
109
        this.servletContext = servletContext;
110
        this.request = request;
111
        this.response = response;
112
        logMetacat = Logger.getLogger(CrudService.class);
113

    
114
        handler = new MetacatHandler(this.servletContext, new Timer());
115
        initParams();
116
//        loadSessionData();
117
    }
118

    
119
    /**
120
     *  copies request parameters to a Hashtable which is given as argument to 
121
     *  native MetacatHandler functions  
122
     */
123
    private void initParams() {
124

    
125
        String name = null;
126
        String[] value = null;
127
        params = new Hashtable<String, String[]>();
128
        Enumeration paramlist = request.getParameterNames();
129
        while (paramlist.hasMoreElements()) {
130
            name = (String) paramlist.nextElement();
131
            value = request.getParameterValues(name);
132
            params.put(name, value);
133
        }
134
    }
135
    
136
    public Identifier create(AuthToken token, Identifier guid, 
137
            InputStream object, SystemMetadata sysmeta) throws InvalidToken, 
138
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
139
            InsufficientResources, InvalidSystemMetadata, NotImplemented {
140

    
141
        logMetacat.debug("Starting CrudService.create()...");
142
        
143
        // authenticate & get user info
144
        SessionData sessionData = getSessionData(token);
145
        String username = sessionData.getUserName();
146
        String[] groups = sessionData.getGroupNames();
147

    
148
        // verify that guid == SystemMetadata.getIdentifier()
149
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
150
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
151
            throw new InvalidSystemMetadata(1180, 
152
                "GUID in method call does not match GUID in system metadata.");
153
        }
154

    
155
        logMetacat.debug("Checking if identifier exists...");
156
        // Check that the identifier does not already exist
157
        IdentifierManager im = IdentifierManager.getInstance();
158
        if (im.identifierExists(guid.getValue())) {
159
            throw new IdentifierNotUnique(1120, 
160
                "GUID is already in use by an existing object.");
161
        }
162

    
163
        // Check if we are handling metadata or data
164
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
165
        
166
        if (isScienceMetadata) {
167
            // CASE METADATA:
168
            try {
169
                String xml = IOUtils.toString(object);
170
                this.insertDocument(xml, guid, sessionData);
171
            } catch (IOException e) {
172
                String msg = "Could not create string from XML stream: " +
173
                    " " + e.getMessage();
174
                logMetacat.debug(msg);
175
                throw new ServiceFailure(1190, msg);
176
            }
177

    
178
        } else {
179
            // DEFAULT CASE: DATA (needs to be checked and completed)
180
            insertDataObject(object, guid, sessionData);
181
            
182
        }
183

    
184
        // For Metadata and Data, insert the system metadata into the object store too
185
        insertSystemMetadata(sysmeta, sessionData);
186

    
187
        logMetacat.debug("Returning from CrudService.create()");
188
        return guid;
189
    }
190

    
191
    public Identifier delete(AuthToken token, Identifier guid)
192
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
193
            NotImplemented {
194
        throw new NotImplemented(1000, "This method not yet implemented.");
195
    }
196

    
197
    public DescribeResponse describe(AuthToken token, Identifier guid)
198
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
199
            NotImplemented {
200
        throw new NotImplemented(1000, "This method not yet implemented.");
201
    }
202
    
203
    public InputStream get(AuthToken token, Identifier guid)
204
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
205
            NotImplemented {
206
        
207
        // Retrieve the session information from the AuthToken
208
        // If the session is expired, then the user is 'public'
209
        final SessionData sessionData = getSessionData(token);
210
        
211
        // Look up the localId for this global identifier
212
        IdentifierManager im = IdentifierManager.getInstance();
213
        try {
214
            final String localId = im.getLocalId(guid.getValue());
215

    
216
            final InputStreamFromOutputStream<String> objectStream = 
217
                new InputStreamFromOutputStream<String>() {
218
                
219
                @Override
220
                public String produce(final OutputStream dataSink) throws Exception {
221

    
222
                    try {
223
                        handler.readFromMetacat(request.getRemoteAddr(), null, 
224
                                dataSink, localId, "xml",
225
                                sessionData.getUserName(), 
226
                                sessionData.getGroupNames(), true, params);
227
                    } catch (PropertyNotFoundException e) {
228
                        throw new ServiceFailure(1030, e.getMessage());
229
                    } catch (ClassNotFoundException e) {
230
                        throw new ServiceFailure(1030, e.getMessage());
231
                    } catch (IOException e) {
232
                        throw new ServiceFailure(1030, e.getMessage());
233
                    } catch (SQLException e) {
234
                        throw new ServiceFailure(1030, e.getMessage());
235
                    } catch (McdbException e) {
236
                        throw new ServiceFailure(1030, e.getMessage());
237
                    } catch (ParseLSIDException e) {
238
                        throw new NotFound(1020, e.getMessage());
239
                    } catch (InsufficientKarmaException e) {
240
                        throw new NotAuthorized(1000, "Not authorized for get().");
241
                    }
242

    
243
                    return "Completed";
244
                }
245
            };
246
            return objectStream;
247

    
248
        } catch (McdbDocNotFoundException e) {
249
            throw new NotFound(1020, e.getMessage());
250
        }
251
    }
252

    
253
    public Checksum getChecksum(AuthToken token, Identifier guid)
254
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
255
            InvalidRequest, NotImplemented {
256
        throw new NotImplemented(1000, "This method not yet implemented.");
257
    }
258

    
259
    public Checksum getChecksum(AuthToken token, Identifier guid, 
260
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
261
            NotAuthorized, NotFound, InvalidRequest, NotImplemented {
262
        throw new NotImplemented(1000, "This method not yet implemented.");
263
    }
264

    
265
    public LogRecordSet getLogRecords(AuthToken token, Date fromDate, Date toDate)
266
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
267
            NotImplemented {
268
        throw new NotImplemented(1000, "This method not yet implemented.");
269
    }
270

    
271
    public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
272
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
273
            InvalidRequest, NotImplemented {
274
        
275
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
276
        
277
        // Retrieve the session information from the AuthToken
278
        // If the session is expired, then the user is 'public'
279
        final SessionData sessionData = getSessionData(token);
280

    
281
        // TODO: Check access control rules
282
                
283
        try {
284
            IdentifierManager im = IdentifierManager.getInstance();
285
            // This is a test id of an existing sysmeta document -- for temporary testing
286
            String testGuid = "autogen.20101192441566.1";
287
            // TODO: Look up ID of system metadata based on guid
288
            // TODO: Initially from document, later from entry in table?
289
//            String localId = im.getLocalId(guid.getValue());
290
            final String localId = im.getLocalId(testGuid);
291
            
292
            // Read system metadata from metacat's db
293
            final InputStreamFromOutputStream<String> objectStream = 
294
                new InputStreamFromOutputStream<String>() {
295
                
296
                @Override
297
                public String produce(final OutputStream dataSink) throws Exception {
298
                    try {
299
                        handler.readFromMetacat(request.getRemoteAddr(), null, 
300
                                dataSink, localId, "xml",
301
                                sessionData.getUserName(), 
302
                                sessionData.getGroupNames(), true, params);
303
                    } catch (PropertyNotFoundException e) {
304
                        throw new ServiceFailure(1030, e.getMessage());
305
                    } catch (ClassNotFoundException e) {
306
                        throw new ServiceFailure(1030, e.getMessage());
307
                    } catch (IOException e) {
308
                        throw new ServiceFailure(1030, e.getMessage());
309
                    } catch (SQLException e) {
310
                        throw new ServiceFailure(1030, e.getMessage());
311
                    } catch (McdbException e) {
312
                        throw new ServiceFailure(1030, e.getMessage());
313
                    } catch (ParseLSIDException e) {
314
                        throw new NotFound(1020, e.getMessage());
315
                    } catch (InsufficientKarmaException e) {
316
                        throw new NotAuthorized(1000, "Not authorized for get().");
317
                    }
318

    
319
                    return "Completed";
320
                }
321
            };
322
            
323
            // Deserialize the xml to create a SystemMetadata object
324
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
325
            return sysmeta;
326
            
327
        } catch (McdbDocNotFoundException e) {
328
            throw new NotFound(1000, e.getMessage());
329
        }                
330
    }
331

    
332
    public Identifier update(AuthToken token, Identifier guid, 
333
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
334
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
335
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
336
            NotImplemented {
337
        throw new NotImplemented(1000, "This method not yet implemented.");
338
    }
339

    
340
    /*
341
     * Look up the information on the session using the token provided in
342
     * the AuthToken.  The Session should have all relevant user information.
343
     * If the session has expired or is invalid, the 'public' session will
344
     * be returned, giving the user anonymous access.
345
     */
346
    private static SessionData getSessionData(AuthToken token) {
347
        SessionData sessionData = null;
348
        String sessionId = "PUBLIC";
349
        if (token != null) {
350
            sessionId = token.getToken();
351
        }
352
        
353
        // if the session id is registered in SessionService, get the
354
        // SessionData for it. Otherwise, use the public session.
355
        if (SessionService.isSessionRegistered(sessionId)) {
356
            sessionData = SessionService.getRegisteredSession(sessionId);
357
        } else {
358
            sessionData = SessionService.getPublicSession();
359
        }
360
        
361
        return sessionData;
362
    }
363

    
364
    /** 
365
     * Determine if a given object should be treated as an XML science metadata
366
     * object. 
367
     * 
368
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
369
     * 
370
     * @param sysmeta the SystemMetadata describig the object
371
     * @return true if the object should be treated as science metadata
372
     */
373
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
374
        boolean scimeta = false;
375
        switch (sysmeta.getObjectFormat()) {
376
            case EML_2_1_0: scimeta = true; break;
377
            case EML_2_0_1: scimeta = true; break;
378
            case EML_2_0_0: scimeta = true; break;
379
            case FGDC_STD_001_1_1999: scimeta = true; break;
380
            case FGDC_STD_001_1998: scimeta = true; break;
381
            case NCML_2_2: scimeta = true; break;
382
        }
383
        
384
        return scimeta;
385
    }
386

    
387
    private void insertDataObject(InputStream object, Identifier guid, 
388
            SessionData sessionData) throws ServiceFailure {
389
        
390
        String username = sessionData.getUserName();
391
        String[] groups = sessionData.getGroupNames();
392

    
393
        // generate guid/localId pair for object
394
        logMetacat.debug("Generating a guid/localId mapping");
395
        IdentifierManager im = IdentifierManager.getInstance();
396
        String localId = im.generateLocalId(guid.getValue(), 1);
397

    
398
        try {
399
            logMetacat.debug("Case DATA: starting to write to disk.");
400
            if (DocumentImpl.getDataFileLockGrant(localId)) {
401
    
402
                // Save the data file to disk using "localId" as the name
403
                try {
404
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
405
    
406
                    File dataDirectory = new File(datafilepath);
407
                    dataDirectory.mkdirs();
408
    
409
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
410
    
411
                    // TODO: Check that the file size matches SystemMetadata
412
                    //                        long size = newFile.length();
413
                    //                        if (size == 0) {
414
                    //                            throw new IOException("Uploaded file is 0 bytes!");
415
                    //                        }
416
    
417
                    // Register the file in the database (which generates an exception
418
                    // if the localId is not acceptable or other untoward things happen
419
                    try {
420
                        logMetacat.debug("Registering document...");
421
                        DocumentImpl.registerDocument(localId, "BIN", localId,
422
                                username, groups);
423
                        logMetacat.debug("Registration step completed.");
424
                    } catch (SQLException e) {
425
                        //newFile.delete();
426
                        logMetacat.debug("SQLE: " + e.getMessage());
427
                        e.printStackTrace(System.out);
428
                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
429
                    } catch (AccessionNumberException e) {
430
                        //newFile.delete();
431
                        logMetacat.debug("ANE: " + e.getMessage());
432
                        e.printStackTrace(System.out);
433
                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
434
                    } catch (Exception e) {
435
                        //newFile.delete();
436
                        logMetacat.debug("Exception: " + e.getMessage());
437
                        e.printStackTrace(System.out);
438
                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
439
                    }
440
    
441
                    logMetacat.debug("Logging the creation event.");
442
                    EventLog.getInstance().log(request.getRemoteAddr(),
443
                            username, localId, "create");
444
    
445
                    // Schedule replication for this data file
446
                    logMetacat.debug("Scheduling replication.");
447
                    ForceReplicationHandler frh = new ForceReplicationHandler(
448
                            localId, "insert", false, null);
449
    
450
                } catch (PropertyNotFoundException e) {
451
                    throw new ServiceFailure(1190, "Could not lock file for writing:" + e.getMessage());
452
                }
453
    
454
            }
455
        } catch (Exception e) {
456
            // Could not get a lock on the document, so we can not update the file now
457
            throw new ServiceFailure(1190, "Failed to lock file: " + e.getMessage());
458
        }
459
    }
460

    
461
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
462
        throws ServiceFailure {
463
        
464
        File newFile = new File(dir, fileName);
465
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
466

    
467
        try {
468
            if (newFile.createNewFile()) {
469
                // write data stream to desired file
470
                OutputStream os = new FileOutputStream(newFile);
471
                long length = IOUtils.copyLarge(data, os);
472
                os.flush();
473
                os.close();
474
            } else {
475
                logMetacat.debug("File creation failed, or file already exists.");
476
                throw new ServiceFailure(1190, "File already exists: " + fileName);
477
            }
478
        } catch (FileNotFoundException e) {
479
            logMetacat.debug("FNF: " + e.getMessage());
480
            throw new ServiceFailure(1190, "File not found: " + fileName + " " 
481
                    + e.getMessage());
482
        } catch (IOException e) {
483
            logMetacat.debug("IOE: " + e.getMessage());
484
            throw new ServiceFailure(1190, "File was not written: " + fileName 
485
                    + " " + e.getMessage());
486
        }
487

    
488
        return newFile;
489
    }
490

    
491
    private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
492
        throws ServiceFailure {
493
        logMetacat.debug("Starting to insert SystemMetadata...");
494
        IdentifierManager im = IdentifierManager.getInstance();
495
    
496
        // generate guid/localId pair for sysmeta
497
        Identifier sysMetaGuid = new Identifier();
498
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
499
        sysmeta.setDateSysMetadataModified(new Date());
500

    
501
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
502
        insertDocument(xml, sysMetaGuid, sessionData);
503
    }
504
    
505
    private void insertDocument(String xml, Identifier guid, SessionData sessionData) 
506
        throws ServiceFailure {
507
        logMetacat.debug("Starting to insert xml document...");
508
        IdentifierManager im = IdentifierManager.getInstance();
509

    
510
        // generate guid/localId pair for sysmeta
511
        String localId = im.generateLocalId(guid.getValue(), 1);
512
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
513
                localId);
514

    
515
        String[] action = new String[1];
516
        action[0] = "insert";
517
        params.put("action", action);
518
        String[] docid = new String[1];
519
        docid[0] = localId;
520
        params.put("docid", docid);
521
        String[] doctext = new String[1];
522
        doctext[0] = xml;
523
        logMetacat.debug(doctext[0]);
524
        params.put("doctext", doctext);
525
        
526
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
527
        // onto output stream, or alternatively, capture that and parse it to 
528
        // generate the right exceptions
529
        ByteArrayOutputStream output = new ByteArrayOutputStream();
530
        PrintWriter pw = new PrintWriter(output);
531
        handler.handleInsertOrUpdateAction(request.getRemoteAddr(), response, 
532
                pw, params, sessionData.getUserName(),
533
                sessionData.getGroupNames());
534
        String outputS = new String(output.toByteArray());
535
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + outputS);
536
//        if (!(outputS.indexOf("<success>") > 0 && outputS.indexOf(localId) > 0)) {
537
//            throw new ServiceFailure(1190, outputS);
538
//        }
539
        logMetacat.debug("Finsished inserting xml document.");
540
    }
541
    
542
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
543
        throws ServiceFailure {
544
        IBindingFactory bfact;
545
        ByteArrayOutputStream sysmetaOut = null;
546
        try {
547
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
548
            IMarshallingContext mctx = bfact.createMarshallingContext();
549
            sysmetaOut = new ByteArrayOutputStream();
550
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
551
        } catch (JiBXException e) {
552
            throw new ServiceFailure(1190, "Failed to serialize and insert SystemMetadata: " + e.getMessage());
553
        }
554
        
555
        return sysmetaOut;
556
    }
557
    
558
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
559
        throws ServiceFailure {
560
        try {
561
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
562
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
563
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
564
            return sysmeta;
565
        } catch (JiBXException e) {
566
            throw new ServiceFailure(1190, "Failed to serialize and insert SystemMetadata: " + e.getMessage());
567
        }    
568
    }
569
}
    (1-1/1)