Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000-2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author:  $'
7
 *     '$Date:  $'
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

    
24
package edu.ucsb.nceas.metacat.dataone;
25

    
26
import java.io.ByteArrayInputStream;
27
import java.io.ByteArrayOutputStream;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileOutputStream;
31
import java.io.IOException;
32
import java.io.InputStream;
33
import java.io.InputStreamReader;
34
import java.io.OutputStreamWriter;
35
import java.io.UnsupportedEncodingException;
36
import java.io.Writer;
37
import java.math.BigInteger;
38
import java.net.URISyntaxException;
39
import java.security.NoSuchAlgorithmException;
40
import java.sql.SQLException;
41
import java.util.ArrayList;
42
import java.util.Calendar;
43
import java.util.Date;
44
import java.util.HashMap;
45
import java.util.HashSet;
46
import java.util.Hashtable;
47
import java.util.List;
48
import java.util.Map;
49
import java.util.Set;
50
import java.util.Timer;
51
import java.util.UUID;
52
import java.util.Vector;
53

    
54
import javax.servlet.http.HttpServletRequest;
55

    
56
import org.apache.commons.io.IOUtils;
57
import org.apache.log4j.Logger;
58
import org.dataone.client.v2.CNode;
59
import org.dataone.client.v2.itk.D1Client;
60
import org.dataone.client.v2.MNode;
61
import org.dataone.client.v2.formats.ObjectFormatCache;
62
import org.dataone.client.auth.CertificateManager;
63
import org.dataone.client.v2.formats.ObjectFormatInfo;
64
import org.dataone.configuration.Settings;
65
import org.dataone.ore.ResourceMapFactory;
66
import org.dataone.service.exceptions.BaseException;
67
import org.dataone.service.exceptions.IdentifierNotUnique;
68
import org.dataone.service.exceptions.InsufficientResources;
69
import org.dataone.service.exceptions.InvalidRequest;
70
import org.dataone.service.exceptions.InvalidSystemMetadata;
71
import org.dataone.service.exceptions.InvalidToken;
72
import org.dataone.service.exceptions.NotAuthorized;
73
import org.dataone.service.exceptions.NotFound;
74
import org.dataone.service.exceptions.NotImplemented;
75
import org.dataone.service.exceptions.ServiceFailure;
76
import org.dataone.service.exceptions.SynchronizationFailed;
77
import org.dataone.service.exceptions.UnsupportedType;
78
import org.dataone.service.mn.tier1.v2.MNCore;
79
import org.dataone.service.mn.tier1.v2.MNRead;
80
import org.dataone.service.mn.tier2.v2.MNAuthorization;
81
import org.dataone.service.mn.tier3.v2.MNStorage;
82
import org.dataone.service.mn.tier4.v2.MNReplication;
83
import org.dataone.service.mn.v2.MNPackage;
84
import org.dataone.service.mn.v2.MNQuery;
85
import org.dataone.service.mn.v2.MNView;
86
import org.dataone.service.types.v1.AccessRule;
87
import org.dataone.service.types.v1.Checksum;
88
import org.dataone.service.types.v1.DescribeResponse;
89
import org.dataone.service.types.v1.Event;
90
import org.dataone.service.types.v1.Identifier;
91
import org.dataone.service.types.v2.Log;
92
import org.dataone.service.types.v2.LogEntry;
93
import org.dataone.service.types.v2.OptionList;
94
import org.dataone.service.types.v1.MonitorInfo;
95
import org.dataone.service.types.v1.MonitorList;
96
import org.dataone.service.types.v2.Node;
97
import org.dataone.service.types.v2.NodeList;
98
import org.dataone.service.types.v1.NodeReference;
99
import org.dataone.service.types.v1.NodeState;
100
import org.dataone.service.types.v1.NodeType;
101
import org.dataone.service.types.v2.ObjectFormat;
102
import org.dataone.service.types.v1.ObjectFormatIdentifier;
103
import org.dataone.service.types.v1.ObjectList;
104
import org.dataone.service.types.v1.Permission;
105
import org.dataone.service.types.v1.Ping;
106
import org.dataone.service.types.v1.ReplicationStatus;
107
import org.dataone.service.types.v1.Schedule;
108
import org.dataone.service.types.v1.Service;
109
import org.dataone.service.types.v1.Services;
110
import org.dataone.service.types.v1.Session;
111
import org.dataone.service.types.v1.Subject;
112
import org.dataone.service.types.v1.Synchronization;
113
import org.dataone.service.types.v2.SystemMetadata;
114
import org.dataone.service.types.v1.util.AuthUtils;
115
import org.dataone.service.types.v1.util.ChecksumUtil;
116
import org.dataone.service.types.v1_1.QueryEngineDescription;
117
import org.dataone.service.types.v1_1.QueryEngineList;
118
import org.dataone.service.types.v1_1.QueryField;
119
import org.dataone.service.util.Constants;
120
import org.dataone.service.util.TypeMarshaller;
121
import org.dspace.foresite.OREException;
122
import org.dspace.foresite.OREParserException;
123
import org.dspace.foresite.ORESerialiserException;
124
import org.dspace.foresite.ResourceMap;
125
import org.ecoinformatics.datamanager.parser.DataPackage;
126
import org.ecoinformatics.datamanager.parser.Entity;
127
import org.ecoinformatics.datamanager.parser.generic.DataPackageParserInterface;
128
import org.ecoinformatics.datamanager.parser.generic.Eml200DataPackageParser;
129

    
130
import edu.ucsb.nceas.ezid.EZIDException;
131
import edu.ucsb.nceas.metacat.DBQuery;
132
import edu.ucsb.nceas.metacat.DBTransform;
133
import edu.ucsb.nceas.metacat.EventLog;
134
import edu.ucsb.nceas.metacat.IdentifierManager;
135
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
136
import edu.ucsb.nceas.metacat.MetaCatServlet;
137
import edu.ucsb.nceas.metacat.MetacatHandler;
138
import edu.ucsb.nceas.metacat.common.query.EnabledQueryEngines;
139
import edu.ucsb.nceas.metacat.common.query.stream.ContentTypeByteArrayInputStream;
140
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
141
import edu.ucsb.nceas.metacat.index.MetacatSolrEngineDescriptionHandler;
142
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
143
import edu.ucsb.nceas.metacat.properties.PropertyService;
144
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
145
import edu.ucsb.nceas.metacat.util.DeleteOnCloseFileInputStream;
146
import edu.ucsb.nceas.metacat.util.DocumentUtil;
147
import edu.ucsb.nceas.metacat.util.SkinUtil;
148
import edu.ucsb.nceas.metacat.util.SystemUtil;
149
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
150
import edu.ucsb.nceas.utilities.XMLUtilities;
151
import edu.ucsb.nceas.utilities.export.HtmlToPdf;
152
import gov.loc.repository.bagit.Bag;
153
import gov.loc.repository.bagit.BagFactory;
154
import gov.loc.repository.bagit.writer.impl.ZipWriter;
155

    
156
/**
157
 * Represents Metacat's implementation of the DataONE Member Node 
158
 * service API. Methods implement the various MN* interfaces, and methods common
159
 * to both Member Node and Coordinating Node interfaces are found in the
160
 * D1NodeService base class.
161
 * 
162
 * Implements:
163
 * MNCore.ping()
164
 * MNCore.getLogRecords()
165
 * MNCore.getObjectStatistics()
166
 * MNCore.getOperationStatistics()
167
 * MNCore.getStatus()
168
 * MNCore.getCapabilities()
169
 * MNRead.get()
170
 * MNRead.getSystemMetadata()
171
 * MNRead.describe()
172
 * MNRead.getChecksum()
173
 * MNRead.listObjects()
174
 * MNRead.synchronizationFailed()
175
 * MNAuthorization.isAuthorized()
176
 * MNAuthorization.setAccessPolicy()
177
 * MNStorage.create()
178
 * MNStorage.update()
179
 * MNStorage.delete()
180
 * MNReplication.replicate()
181
 * 
182
 */
183
public class MNodeService extends D1NodeService 
184
    implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage, MNQuery, MNView, MNPackage {
185

    
186
    //private static final String PATHQUERY = "pathquery";
187
	public static final String UUID_SCHEME = "UUID";
188
	public static final String DOI_SCHEME = "DOI";
189
	private static final String UUID_PREFIX = "urn:uuid:";
190

    
191
	/* the logger instance */
192
    private Logger logMetacat = null;
193
    
194
    /* A reference to a remote Memeber Node */
195
    private MNode mn;
196
    
197
    /* A reference to a Coordinating Node */
198
    private CNode cn;
199

    
200

    
201
    /**
202
     * Singleton accessor to get an instance of MNodeService.
203
     * 
204
     * @return instance - the instance of MNodeService
205
     */
206
    public static MNodeService getInstance(HttpServletRequest request) {
207
        return new MNodeService(request);
208
    }
209

    
210
    /**
211
     * Constructor, private for singleton access
212
     */
213
    private MNodeService(HttpServletRequest request) {
214
        super(request);
215
        logMetacat = Logger.getLogger(MNodeService.class);
216
        
217
        // set the Member Node certificate file location
218
        CertificateManager.getInstance().setCertificateLocation(Settings.getConfiguration().getString("D1Client.certificate.file"));
219
    }
220

    
221
    /**
222
     * Deletes an object from the Member Node, where the object is either a 
223
     * data object or a science metadata object.
224
     * 
225
     * @param session - the Session object containing the credentials for the Subject
226
     * @param pid - The object identifier to be deleted
227
     * 
228
     * @return pid - the identifier of the object used for the deletion
229
     * 
230
     * @throws InvalidToken
231
     * @throws ServiceFailure
232
     * @throws NotAuthorized
233
     * @throws NotFound
234
     * @throws NotImplemented
235
     * @throws InvalidRequest
236
     */
237
    @Override
238
    public Identifier delete(Session session, Identifier pid) 
239
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
240

    
241
    	// only admin of  the MN or the CN is allowed a full delete
242
        boolean allowed = false;
243
        allowed = isAdminAuthorized(session);
244
        
245
        String serviceFailureCode = "2902";
246
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
247
        if(sid != null) {
248
            pid = sid;
249
        }
250
        
251
        //check if it is the authoritative member node
252
        if(!allowed) {
253
            allowed = isAuthoritativeMNodeAdmin(session, pid);
254
        }
255
        
256
        if (!allowed) { 
257
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to delete objects on the Node.");
258
        }
259
    	
260
    	// defer to superclass implementation
261
        return super.delete(session, pid);
262
    }
263

    
264
    /**
265
     * Updates an existing object by creating a new object identified by 
266
     * newPid on the Member Node which explicitly obsoletes the object 
267
     * identified by pid through appropriate changes to the SystemMetadata 
268
     * of pid and newPid
269
     * 
270
     * @param session - the Session object containing the credentials for the Subject
271
     * @param pid - The identifier of the object to be updated
272
     * @param object - the new object bytes
273
     * @param sysmeta - the new system metadata describing the object
274
     * 
275
     * @return newPid - the identifier of the new object
276
     * 
277
     * @throws InvalidToken
278
     * @throws ServiceFailure
279
     * @throws NotAuthorized
280
     * @throws NotFound
281
     * @throws NotImplemented
282
     * @throws IdentifierNotUnique
283
     * @throws UnsupportedType
284
     * @throws InsufficientResources
285
     * @throws InvalidSystemMetadata
286
     * @throws InvalidRequest
287
     */
288
    @Override
289
    public Identifier update(Session session, Identifier pid, InputStream object, 
290
        Identifier newPid, SystemMetadata sysmeta) 
291
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
292
        UnsupportedType, InsufficientResources, NotFound, 
293
        InvalidSystemMetadata, NotImplemented, InvalidRequest {
294

    
295
        //transform a sid to a pid if it is applicable
296
        String serviceFailureCode = "1310";
297
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
298
        if(sid != null) {
299
            pid = sid;
300
        }
301
        
302
        String localId = null;
303
        boolean allowed = false;
304
        boolean isScienceMetadata = false;
305
        
306
        if (session == null) {
307
        	throw new InvalidToken("1210", "No session has been provided");
308
        }
309
        Subject subject = session.getSubject();
310

    
311
        // verify the pid is valid format
312
        if (!isValidIdentifier(pid)) {
313
        	throw new InvalidRequest("1202", "The provided identifier is invalid.");
314
        }
315
        
316
        // verify the new pid is valid format
317
        if (!isValidIdentifier(newPid)) {
318
            throw new InvalidRequest("1202", "The provided identifier is invalid.");
319
        }
320
        
321
        // make sure that the newPid doesn't exists
322
        boolean idExists = true;
323
        try {
324
            idExists = IdentifierManager.getInstance().identifierExists(newPid.getValue());
325
        } catch (SQLException e) {
326
            throw new ServiceFailure("1310", 
327
                                    "The requested identifier " + newPid.getValue() +
328
                                    " couldn't be determined if it is unique since : "+e.getMessage());
329
        }
330
        if (idExists) {
331
                throw new IdentifierNotUnique("1220", 
332
                          "The requested identifier " + newPid.getValue() +
333
                          " is already used by another object and" +
334
                          "therefore can not be used for this object. Clients should choose" +
335
                          "a new identifier that is unique and retry the operation or " +
336
                          "use CN.reserveIdentifier() to reserve one.");
337
            
338
        }
339
        
340
       
341

    
342
        // check for the existing identifier
343
        try {
344
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
345
            
346
        } catch (McdbDocNotFoundException e) {
347
            throw new InvalidRequest("1202", "The object with the provided " + 
348
                "identifier was not found.");
349
            
350
        } catch (SQLException ee) {
351
            throw new ServiceFailure("1310", "The object with the provided " + 
352
                    "identifier "+pid.getValue()+" can't be identified since - "+ee.getMessage());
353
        }
354
        
355
        // set the originating node
356
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
357
        sysmeta.setOriginMemberNode(originMemberNode);
358
        
359
        // set the submitter to match the certificate
360
        sysmeta.setSubmitter(subject);
361
        // set the dates
362
        Date now = Calendar.getInstance().getTime();
363
        sysmeta.setDateSysMetadataModified(now);
364
        sysmeta.setDateUploaded(now);
365
        
366
        // make sure serial version is set to something
367
        BigInteger serialVersion = sysmeta.getSerialVersion();
368
        if (serialVersion == null) {
369
        	sysmeta.setSerialVersion(BigInteger.ZERO);
370
        }
371

    
372
        // does the subject have WRITE ( == update) priveleges on the pid?
373
        allowed = isAuthorized(session, pid, Permission.WRITE);
374

    
375
        if (allowed) {
376
        	
377
        	// check quality of SM
378
        	if (sysmeta.getObsoletedBy() != null) {
379
        		throw new InvalidSystemMetadata("1300", "Cannot include obsoletedBy when updating object");
380
        	}
381
        	if (sysmeta.getObsoletes() != null && !sysmeta.getObsoletes().getValue().equals(pid.getValue())) {
382
        		throw new InvalidSystemMetadata("1300", "The identifier provided in obsoletes does not match old Identifier");
383
        	}
384

    
385
            // get the existing system metadata for the object
386
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
387

    
388
            // check for previous update
389
            // see: https://redmine.dataone.org/issues/3336
390
            Identifier existingObsoletedBy = existingSysMeta.getObsoletedBy();
391
            if (existingObsoletedBy != null) {
392
            	throw new InvalidRequest("1202", 
393
            			"The previous identifier has already been made obsolete by: " + existingObsoletedBy.getValue());
394
            }
395
            //check the sid in the system metadata. If it exists, it should be non-exist or match the old sid in the previous system metadata.
396
            Identifier sidInSys = sysmeta.getSeriesId();
397
            if(sidInSys != null) {
398
                if (!isValidIdentifier(sidInSys)) {
399
                    throw new InvalidSystemMetadata("1300", "The provided series id in the system metadata is invalid.");
400
                }
401
                Identifier previousSid = existingSysMeta.getSeriesId();
402
                if(previousSid != null) {
403
                    // there is a previous sid, if the new sid doesn't match it, the new sid should be non-existing.
404
                    if(!sidInSys.getValue().equals(previousSid.getValue())) {
405
                        try {
406
                            idExists = IdentifierManager.getInstance().identifierExists(sidInSys.getValue());
407
                        } catch (SQLException e) {
408
                            throw new ServiceFailure("1310", 
409
                                                    "The requested identifier " + sidInSys.getValue() +
410
                                                    " couldn't be determined if it is unique since : "+e.getMessage());
411
                        }
412
                        if(idExists) {
413
                            throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata doesn't match the previous series id "
414
                                                            +previousSid.getValue()+", so it should NOT exist. However, it was used by another object.");
415
                        }
416
                    }
417
                } else {
418
                    // there is no previous sid, the new sid should be non-existing.
419
                    try {
420
                        idExists = IdentifierManager.getInstance().identifierExists(sidInSys.getValue());
421
                    } catch (SQLException e) {
422
                        throw new ServiceFailure("1310", 
423
                                                "The requested identifier " + sidInSys.getValue() +
424
                                                " couldn't be determined if it is unique since : "+e.getMessage());
425
                    }
426
                    if(idExists) {
427
                        throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata should NOT exist since the previous series id is null."
428
                                                        +"However, it was used by another object.");
429
                    }
430
                }
431
                //the series id equals the pid (new pid hasn't been registered in the system, so IdentifierManager.getInstance().identifierExists method can't exclude this scenario)
432
                if(sidInSys.getValue().equals(newPid.getValue())) {
433
                    throw new InvalidSystemMetadata("1300", "The series id "+sidInSys.getValue()+" in the system metadata shouldn't have the same value of the pid.");
434
                }
435
            }
436

    
437
            isScienceMetadata = isScienceMetadata(sysmeta);
438

    
439
            // do we have XML metadata or a data object?
440
            if (isScienceMetadata) {
441

    
442
                // update the science metadata XML document
443
                // TODO: handle non-XML metadata/data documents (like netCDF)
444
                // TODO: don't put objects into memory using stream to string
445
                //String objectAsXML = "";
446
                try {
447
                    //objectAsXML = IOUtils.toString(object, "UTF-8");
448
                    // give the old pid so we can calculate the new local id 
449
                    localId = insertOrUpdateDocument(object, "UTF-8", pid, session, "update");
450
                    // register the newPid and the generated localId
451
                    if (newPid != null) {
452
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
453

    
454
                    }
455

    
456
                } catch (IOException e) {
457
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
458
                    logMetacat.info(msg);
459
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
460

    
461
                }
462

    
463
            } else {
464

    
465
                // update the data object
466
                localId = insertDataObject(object, newPid, session);
467

    
468
            }
469
            
470
            // add the newPid to the obsoletedBy list for the existing sysmeta
471
            existingSysMeta.setObsoletedBy(newPid);
472

    
473
            // then update the existing system metadata
474
            updateSystemMetadata(existingSysMeta);
475

    
476
            // prep the new system metadata, add pid to the affected lists
477
            sysmeta.setObsoletes(pid);
478
            //sysmeta.addDerivedFrom(pid);
479

    
480
            // and insert the new system metadata
481
            insertSystemMetadata(sysmeta);
482

    
483
            // log the update event
484
            EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
485
            
486
            // attempt to register the identifier - it checks if it is a doi
487
            try {
488
    			DOIService.getInstance().registerDOI(sysmeta);
489
    		} catch (Exception e) {
490
                throw new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
491
    		}
492

    
493
        } else {
494
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
495
                    + " on the Member Node.");
496
        }
497

    
498
        return newPid;
499
    }
500

    
501
    public Identifier create(Session session, Identifier pid, InputStream object, SystemMetadata sysmeta) throws InvalidToken, ServiceFailure, NotAuthorized,
502
            IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
503

    
504
        // check for null session
505
        if (session == null) {
506
          throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
507
        }
508
        // set the submitter to match the certificate
509
        sysmeta.setSubmitter(session.getSubject());
510
        // set the originating node
511
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
512
        sysmeta.setOriginMemberNode(originMemberNode);
513
        sysmeta.setArchived(false);
514

    
515
        // set the dates
516
        Date now = Calendar.getInstance().getTime();
517
        sysmeta.setDateSysMetadataModified(now);
518
        sysmeta.setDateUploaded(now);
519
        
520
        // set the serial version
521
        sysmeta.setSerialVersion(BigInteger.ZERO);
522

    
523
        // check that we are not attempting to subvert versioning
524
        if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
525
            throw new InvalidSystemMetadata("1180", 
526
              "The supplied system metadata is invalid. " +
527
              "The obsoletes field cannot have a value when creating entries.");
528
        }
529
        
530
        if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
531
            throw new InvalidSystemMetadata("1180", 
532
              "The supplied system metadata is invalid. " +
533
              "The obsoletedBy field cannot have a value when creating entries.");
534
        }
535

    
536
        // call the shared impl
537
        Identifier resultPid = super.create(session, pid, object, sysmeta);
538
        
539
        // attempt to register the identifier - it checks if it is a doi
540
        try {
541
			DOIService.getInstance().registerDOI(sysmeta);
542
		} catch (Exception e) {
543
			ServiceFailure sf = new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
544
			sf.initCause(e);
545
            throw sf;
546
		}
547
        
548
        // return 
549
		return resultPid ;
550
    }
551

    
552
    /**
553
     * Called by a Coordinating Node to request that the Member Node create a 
554
     * copy of the specified object by retrieving it from another Member 
555
     * Node and storing it locally so that it can be made accessible to 
556
     * the DataONE system.
557
     * 
558
     * @param session - the Session object containing the credentials for the Subject
559
     * @param sysmeta - Copy of the CN held system metadata for the object
560
     * @param sourceNode - A reference to node from which the content should be 
561
     *                     retrieved. The reference should be resolved by 
562
     *                     checking the CN node registry.
563
     * 
564
     * @return true if the replication succeeds
565
     * 
566
     * @throws ServiceFailure
567
     * @throws NotAuthorized
568
     * @throws NotImplemented
569
     * @throws UnsupportedType
570
     * @throws InsufficientResources
571
     * @throws InvalidRequest
572
     */
573
    @Override
574
    public boolean replicate(Session session, SystemMetadata sysmeta,
575
            NodeReference sourceNode) throws NotImplemented, ServiceFailure,
576
            NotAuthorized, InvalidRequest, InsufficientResources,
577
            UnsupportedType {
578

    
579
        if (session != null && sysmeta != null && sourceNode != null) {
580
            logMetacat.info("MNodeService.replicate() called with parameters: \n" +
581
                            "\tSession.Subject      = "                           +
582
                            session.getSubject().getValue() + "\n"                +
583
                            "\tidentifier           = "                           + 
584
                            sysmeta.getIdentifier().getValue()                    +
585
                            "\n" + "\tSource NodeReference ="                     +
586
                            sourceNode.getValue());
587
        }
588
        boolean result = false;
589
        String nodeIdStr = null;
590
        NodeReference nodeId = null;
591

    
592
        // get the referenced object
593
        Identifier pid = sysmeta.getIdentifier();
594

    
595
        // get from the membernode
596
        // TODO: switch credentials for the server retrieval?
597
        this.mn = D1Client.getMN(sourceNode);
598
        this.cn = D1Client.getCN();
599
        InputStream object = null;
600
        Session thisNodeSession = null;
601
        SystemMetadata localSystemMetadata = null;
602
        BaseException failure = null;
603
        String localId = null;
604
        
605
        // TODO: check credentials
606
        // cannot be called by public
607
        if (session == null || session.getSubject() == null) {
608
            String msg = "No session was provided to replicate identifier " +
609
            sysmeta.getIdentifier().getValue();
610
            logMetacat.error(msg);
611
            throw new NotAuthorized("2152", msg);
612
            
613
        }
614

    
615

    
616
        // get the local node id
617
        try {
618
            nodeIdStr = PropertyService.getProperty("dataone.nodeId");
619
            nodeId = new NodeReference();
620
            nodeId.setValue(nodeIdStr);
621

    
622
        } catch (PropertyNotFoundException e1) {
623
            String msg = "Couldn't get dataone.nodeId property: " + e1.getMessage();
624
            failure = new ServiceFailure("2151", msg);
625
            //setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
626
            logMetacat.error(msg);
627
            //return true;
628
            throw new ServiceFailure("2151", msg);
629

    
630
        }
631
        
632

    
633
        try {
634
            // do we already have a replica?
635
            try {
636
                localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
637
                // if we have a local id, get the local object
638
                try {
639
                    object = MetacatHandler.read(localId);
640
                } catch (Exception e) {
641
                	// NOTE: we may already know about this ID because it could be a data file described by a metadata file
642
                	// https://redmine.dataone.org/issues/2572
643
                	// TODO: fix this so that we don't prevent ourselves from getting replicas
644
                	
645
                    // let the CN know that the replication failed
646
                	logMetacat.warn("Object content not found on this node despite having localId: " + localId);
647
                	String msg = "Can't read the object bytes properly, replica is invalid.";
648
                    ServiceFailure serviceFailure = new ServiceFailure("2151", msg);
649
                    setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, serviceFailure);
650
                    logMetacat.warn(msg);
651
                    throw serviceFailure;
652
                    
653
                }
654

    
655
            } catch (McdbDocNotFoundException e) {
656
                logMetacat.info("No replica found. Continuing.");
657
                
658
            } catch (SQLException ee) {
659
                throw new ServiceFailure("2151", "Couldn't identify the local id of the object with the specified identifier "
660
                                        +pid.getValue()+" since - "+ee.getMessage());
661
            }
662
            
663
            // no local replica, get a replica
664
            if ( object == null ) {
665
                // session should be null to use the default certificate
666
                // location set in the Certificate manager
667
                object = mn.getReplica(thisNodeSession, pid);
668
                logMetacat.info("MNodeService.getReplica() called for identifier "
669
                                + pid.getValue());
670

    
671
            }
672

    
673
        } catch (InvalidToken e) {            
674
            String msg = "Could not retrieve object to replicate (InvalidToken): "+ e.getMessage();
675
            failure = new ServiceFailure("2151", msg);
676
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
677
            logMetacat.error(msg);
678
            throw new ServiceFailure("2151", msg);
679

    
680
        } catch (NotFound e) {
681
            String msg = "Could not retrieve object to replicate (NotFound): "+ e.getMessage();
682
            failure = new ServiceFailure("2151", msg);
683
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
684
            logMetacat.error(msg);
685
            throw new ServiceFailure("2151", msg);
686

    
687
        } catch (NotAuthorized e) {
688
            String msg = "Could not retrieve object to replicate (NotAuthorized): "+ e.getMessage();
689
            failure = new ServiceFailure("2151", msg);
690
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
691
            logMetacat.error(msg);
692
            throw new ServiceFailure("2151", msg);
693
        } catch (NotImplemented e) {
694
            String msg = "Could not retrieve object to replicate (mn.getReplica NotImplemented): "+ e.getMessage();
695
            failure = new ServiceFailure("2151", msg);
696
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
697
            logMetacat.error(msg);
698
            throw new ServiceFailure("2151", msg);
699
        } catch (ServiceFailure e) {
700
            String msg = "Could not retrieve object to replicate (ServiceFailure): "+ e.getMessage();
701
            failure = new ServiceFailure("2151", msg);
702
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
703
            logMetacat.error(msg);
704
            throw new ServiceFailure("2151", msg);
705
        } catch (InsufficientResources e) {
706
            String msg = "Could not retrieve object to replicate (InsufficientResources): "+ e.getMessage();
707
            failure = new ServiceFailure("2151", msg);
708
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
709
            logMetacat.error(msg);
710
            throw new ServiceFailure("2151", msg);
711
        }
712

    
713
        // verify checksum on the object, if supported
714
        if (object.markSupported()) {
715
            Checksum givenChecksum = sysmeta.getChecksum();
716
            Checksum computedChecksum = null;
717
            try {
718
                computedChecksum = ChecksumUtil.checksum(object, givenChecksum.getAlgorithm());
719
                object.reset();
720

    
721
            } catch (Exception e) {
722
                String msg = "Error computing checksum on replica: " + e.getMessage();
723
                logMetacat.error(msg);
724
                ServiceFailure sf = new ServiceFailure("2151", msg);
725
                sf.initCause(e);
726
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, sf);
727
                throw sf;
728
            }
729
            if (!givenChecksum.getValue().equals(computedChecksum.getValue())) {
730
                logMetacat.error("Given    checksum for " + pid.getValue() + 
731
                    "is " + givenChecksum.getValue());
732
                logMetacat.error("Computed checksum for " + pid.getValue() + 
733
                    "is " + computedChecksum.getValue());
734
                String msg = "Computed checksum does not match declared checksum";
735
                failure = new ServiceFailure("2151", msg);
736
                setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
737
                throw new ServiceFailure("2151", msg);
738
            }
739
        }
740

    
741
        // add it to local store
742
        Identifier retPid;
743
        try {
744
            // skip the MN.create -- this mutates the system metadata and we don't want it to
745
            if ( localId == null ) {
746
                // TODO: this will fail if we already "know" about the identifier
747
            	// FIXME: see https://redmine.dataone.org/issues/2572
748
                retPid = super.create(session, pid, object, sysmeta);
749
                result = (retPid.getValue().equals(pid.getValue()));
750
            }
751
            
752
        } catch (Exception e) {
753
            String msg = "Could not save object to local store (" + e.getClass().getName() + "): " + e.getMessage();
754
            failure = new ServiceFailure("2151", msg);
755
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
756
            logMetacat.error(msg);
757
            throw new ServiceFailure("2151", msg);
758
            
759
        }
760

    
761
        // finish by setting the replication status
762
        setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.COMPLETED, null);
763
        return result;
764

    
765
    }
766

    
767
    /**
768
     * Return the object identified by the given object identifier
769
     * 
770
     * @param session - the Session object containing the credentials for the Subject
771
     * @param pid - the object identifier for the given object
772
     * 
773
     * @return inputStream - the input stream of the given object
774
     * 
775
     * @throws InvalidToken
776
     * @throws ServiceFailure
777
     * @throws NotAuthorized
778
     * @throws InvalidRequest
779
     * @throws NotImplemented
780
     */
781
    @Override
782
    public InputStream get(Session session, Identifier pid) 
783
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
784

    
785
        return super.get(session, pid);
786

    
787
    }
788

    
789
    /**
790
     * Returns a Checksum for the specified object using an accepted hashing algorithm
791
     * 
792
     * @param session - the Session object containing the credentials for the Subject
793
     * @param pid - the object identifier for the given object
794
     * @param algorithm -  the name of an algorithm that will be used to compute 
795
     *                     a checksum of the bytes of the object
796
     * 
797
     * @return checksum - the checksum of the given object
798
     * 
799
     * @throws InvalidToken
800
     * @throws ServiceFailure
801
     * @throws NotAuthorized
802
     * @throws NotFound
803
     * @throws InvalidRequest
804
     * @throws NotImplemented
805
     */
806
    @Override
807
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) 
808
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
809
        InvalidRequest, NotImplemented {
810

    
811
        Checksum checksum = null;
812
        String serviceFailure = "1410";
813
        String notFound = "1420";
814
        //Checkum only handles the pid, not sid
815
        checkV1SystemMetaPidExist(pid, serviceFailure, "The checksum for the object specified by "+pid.getValue()+" couldn't be returned ",  notFound, 
816
                "The object specified by "+pid.getValue()+" does not exist at this node.");
817
        InputStream inputStream = get(session, pid);
818

    
819
        try {
820
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
821

    
822
        } catch (NoSuchAlgorithmException e) {
823
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
824
                    + e.getMessage());
825
        } catch (IOException e) {
826
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
827
                    + e.getMessage());
828
        }
829

    
830
        if (checksum == null) {
831
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
832
        }
833

    
834
        return checksum;
835
    }
836

    
837
    /**
838
     * Return the system metadata for a given object
839
     * 
840
     * @param session - the Session object containing the credentials for the Subject
841
     * @param pid - the object identifier for the given object
842
     * 
843
     * @return inputStream - the input stream of the given system metadata object
844
     * 
845
     * @throws InvalidToken
846
     * @throws ServiceFailure
847
     * @throws NotAuthorized
848
     * @throws NotFound
849
     * @throws InvalidRequest
850
     * @throws NotImplemented
851
     */
852
    @Override
853
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) 
854
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
855
        NotImplemented {
856

    
857
        return super.getSystemMetadata(session, pid);
858
    }
859

    
860
    /**
861
     * Retrieve the list of objects present on the MN that match the calling parameters
862
     * 
863
     * @param session - the Session object containing the credentials for the Subject
864
     * @param startTime - Specifies the beginning of the time range from which 
865
     *                    to return object (>=)
866
     * @param endTime - Specifies the beginning of the time range from which 
867
     *                  to return object (>=)
868
     * @param objectFormat - Restrict results to the specified object format
869
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
870
     * @param start - The zero-based index of the first value, relative to the 
871
     *                first record of the resultset that matches the parameters.
872
     * @param count - The maximum number of entries that should be returned in 
873
     *                the response. The Member Node may return less entries 
874
     *                than specified in this value.
875
     * 
876
     * @return objectList - the list of objects matching the criteria
877
     * 
878
     * @throws InvalidToken
879
     * @throws ServiceFailure
880
     * @throws NotAuthorized
881
     * @throws InvalidRequest
882
     * @throws NotImplemented
883
     */
884
    @Override
885
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Identifier identifier, Boolean replicaStatus, Integer start,
886
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
887

    
888
        ObjectList objectList = null;
889

    
890
        try {
891
        	// safeguard against large requests
892
            if (count == null || count > MAXIMUM_DB_RECORD_COUNT) {
893
            	count = MAXIMUM_DB_RECORD_COUNT;
894
            }
895
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
896
        } catch (Exception e) {
897
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
898
        }
899

    
900
        return objectList;
901
    }
902

    
903
    /**
904
     * Return a description of the node's capabilities and services.
905
     * 
906
     * @return node - the technical capabilities of the Member Node
907
     * 
908
     * @throws ServiceFailure
909
     * @throws NotAuthorized
910
     * @throws InvalidRequest
911
     * @throws NotImplemented
912
     */
913
    @Override
914
    public Node getCapabilities() 
915
        throws NotImplemented, ServiceFailure {
916

    
917
        String nodeName = null;
918
        String nodeId = null;
919
        String subject = null;
920
        String contactSubject = null;
921
        String nodeDesc = null;
922
        String nodeTypeString = null;
923
        NodeType nodeType = null;
924
        String mnCoreServiceVersion = null;
925
        String mnReadServiceVersion = null;
926
        String mnAuthorizationServiceVersion = null;
927
        String mnStorageServiceVersion = null;
928
        String mnReplicationServiceVersion = null;
929

    
930
        boolean nodeSynchronize = false;
931
        boolean nodeReplicate = false;
932
        boolean mnCoreServiceAvailable = false;
933
        boolean mnReadServiceAvailable = false;
934
        boolean mnAuthorizationServiceAvailable = false;
935
        boolean mnStorageServiceAvailable = false;
936
        boolean mnReplicationServiceAvailable = false;
937

    
938
        try {
939
            // get the properties of the node based on configuration information
940
            nodeName = PropertyService.getProperty("dataone.nodeName");
941
            nodeId = PropertyService.getProperty("dataone.nodeId");
942
            subject = PropertyService.getProperty("dataone.subject");
943
            contactSubject = PropertyService.getProperty("dataone.contactSubject");
944
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
945
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
946
            nodeType = NodeType.convert(nodeTypeString);
947
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
948
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
949

    
950
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
951
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
952
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
953
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
954
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
955

    
956
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
957
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
958
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
959
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
960
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
961

    
962
            // Set the properties of the node based on configuration information and
963
            // calls to current status methods
964
            String serviceName = SystemUtil.getSecureContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
965
            Node node = new Node();
966
            node.setBaseURL(serviceName + "/" + nodeTypeString);
967
            node.setDescription(nodeDesc);
968

    
969
            // set the node's health information
970
            node.setState(NodeState.UP);
971
            
972
            // set the ping response to the current value
973
            Ping canPing = new Ping();
974
            canPing.setSuccess(false);
975
            try {
976
            	Date pingDate = ping();
977
                canPing.setSuccess(pingDate != null);
978
            } catch (BaseException e) {
979
                e.printStackTrace();
980
                // guess it can't be pinged
981
            }
982
            
983
            node.setPing(canPing);
984

    
985
            NodeReference identifier = new NodeReference();
986
            identifier.setValue(nodeId);
987
            node.setIdentifier(identifier);
988
            Subject s = new Subject();
989
            s.setValue(subject);
990
            node.addSubject(s);
991
            Subject contact = new Subject();
992
            contact.setValue(contactSubject);
993
            node.addContactSubject(contact);
994
            node.setName(nodeName);
995
            node.setReplicate(nodeReplicate);
996
            node.setSynchronize(nodeSynchronize);
997

    
998
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
999
            Services services = new Services();
1000

    
1001
            Service sMNCore = new Service();
1002
            sMNCore.setName("MNCore");
1003
            sMNCore.setVersion(mnCoreServiceVersion);
1004
            sMNCore.setAvailable(mnCoreServiceAvailable);
1005

    
1006
            Service sMNRead = new Service();
1007
            sMNRead.setName("MNRead");
1008
            sMNRead.setVersion(mnReadServiceVersion);
1009
            sMNRead.setAvailable(mnReadServiceAvailable);
1010

    
1011
            Service sMNAuthorization = new Service();
1012
            sMNAuthorization.setName("MNAuthorization");
1013
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
1014
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
1015

    
1016
            Service sMNStorage = new Service();
1017
            sMNStorage.setName("MNStorage");
1018
            sMNStorage.setVersion(mnStorageServiceVersion);
1019
            sMNStorage.setAvailable(mnStorageServiceAvailable);
1020

    
1021
            Service sMNReplication = new Service();
1022
            sMNReplication.setName("MNReplication");
1023
            sMNReplication.setVersion(mnReplicationServiceVersion);
1024
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
1025

    
1026
            services.addService(sMNRead);
1027
            services.addService(sMNCore);
1028
            services.addService(sMNAuthorization);
1029
            services.addService(sMNStorage);
1030
            services.addService(sMNReplication);
1031
            node.setServices(services);
1032

    
1033
            // Set the schedule for synchronization
1034
            Synchronization synchronization = new Synchronization();
1035
            Schedule schedule = new Schedule();
1036
            Date now = new Date();
1037
            schedule.setYear(PropertyService.getProperty("dataone.nodeSynchronization.schedule.year"));
1038
            schedule.setMon(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mon"));
1039
            schedule.setMday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mday"));
1040
            schedule.setWday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.wday"));
1041
            schedule.setHour(PropertyService.getProperty("dataone.nodeSynchronization.schedule.hour"));
1042
            schedule.setMin(PropertyService.getProperty("dataone.nodeSynchronization.schedule.min"));
1043
            schedule.setSec(PropertyService.getProperty("dataone.nodeSynchronization.schedule.sec"));
1044
            synchronization.setSchedule(schedule);
1045
            synchronization.setLastHarvested(now);
1046
            synchronization.setLastCompleteHarvest(now);
1047
            node.setSynchronization(synchronization);
1048

    
1049
            node.setType(nodeType);
1050
            return node;
1051

    
1052
        } catch (PropertyNotFoundException pnfe) {
1053
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
1054
            logMetacat.error(msg);
1055
            throw new ServiceFailure("2162", msg);
1056
        }
1057
    }
1058

    
1059
    
1060

    
1061
    /**
1062
     * A callback method used by a CN to indicate to a MN that it cannot 
1063
     * complete synchronization of the science metadata identified by pid.  Log
1064
     * the event in the metacat event log.
1065
     * 
1066
     * @param session
1067
     * @param syncFailed
1068
     * 
1069
     * @throws ServiceFailure
1070
     * @throws NotAuthorized
1071
     * @throws NotImplemented
1072
     */
1073
    @Override
1074
    public boolean synchronizationFailed(Session session, SynchronizationFailed syncFailed) 
1075
        throws NotImplemented, ServiceFailure, NotAuthorized {
1076

    
1077
        String localId;
1078
        Identifier pid;
1079
        if ( syncFailed.getPid() != null ) {
1080
            pid = new Identifier();
1081
            pid.setValue(syncFailed.getPid());
1082
            boolean allowed;
1083
            
1084
            //are we allowed? only CNs
1085
            try {
1086
                allowed = isAdminAuthorized(session);
1087
                if ( !allowed ){
1088
                    throw new NotAuthorized("2162", 
1089
                            "Not allowed to call synchronizationFailed() on this node.");
1090
                }
1091
            } catch (InvalidToken e) {
1092
                throw new NotAuthorized("2162", 
1093
                        "Not allowed to call synchronizationFailed() on this node.");
1094

    
1095
            }
1096
            
1097
        } else {
1098
            throw new ServiceFailure("2161", "The identifier cannot be null.");
1099

    
1100
        }
1101
        
1102
        try {
1103
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1104
        } catch (McdbDocNotFoundException e) {
1105
            throw new ServiceFailure("2161", "The identifier specified by " + 
1106
                    syncFailed.getPid() + " was not found on this node.");
1107

    
1108
        } catch (SQLException e) {
1109
            throw new ServiceFailure("2161", "Couldn't identify the local id of the identifier specified by " + 
1110
                    syncFailed.getPid() + " since "+e.getMessage());
1111
        }
1112
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
1113
        // method is changed to include the URL as a parameter
1114
        logMetacat.debug("Synchronization for the object identified by " + 
1115
                pid.getValue() + " failed from " + syncFailed.getNodeId() + 
1116
                " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
1117
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
1118
        String principal = Constants.SUBJECT_PUBLIC;
1119
        if (session != null && session.getSubject() != null) {
1120
          principal = session.getSubject().getValue();
1121
        }
1122
        try {
1123
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
1124
        } catch (Exception e) {
1125
            throw new ServiceFailure("2161", "Could not log the error for: " + pid.getValue());
1126
        }
1127
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
1128
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
1129
        return true;
1130

    
1131
    }
1132

    
1133
    /**
1134
     * Essentially a get() but with different logging behavior
1135
     */
1136
    @Override
1137
    public InputStream getReplica(Session session, Identifier pid) 
1138
        throws NotAuthorized, NotImplemented, ServiceFailure, InvalidToken {
1139

    
1140
        logMetacat.info("MNodeService.getReplica() called.");
1141

    
1142
        // cannot be called by public
1143
        if (session == null) {
1144
        	throw new InvalidToken("2183", "No session was provided.");
1145
        }
1146
        
1147
        logMetacat.info("MNodeService.getReplica() called with parameters: \n" +
1148
             "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
1149
             "\tIdentifier           = " + pid.getValue());
1150

    
1151
        InputStream inputStream = null; // bytes to be returned
1152
        handler = new MetacatHandler(new Timer());
1153
        boolean allowed = false;
1154
        String localId; // the metacat docid for the pid
1155

    
1156
        // get the local docid from Metacat
1157
        try {
1158
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1159
        } catch (McdbDocNotFoundException e) {
1160
            throw new ServiceFailure("2181", "The object specified by " + 
1161
                    pid.getValue() + " does not exist at this node.");
1162
            
1163
        } catch (SQLException e) {
1164
            throw new ServiceFailure("2181", "The local id of the object specified by " + 
1165
                    pid.getValue() + " couldn't be identified since "+e.getMessage());
1166
        }
1167

    
1168
        Subject targetNodeSubject = session.getSubject();
1169

    
1170
        // check for authorization to replicate, null session to act as this source MN
1171
        try {
1172
            allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid);
1173
        } catch (InvalidToken e1) {
1174
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1175
                + e1.getMessage());
1176
            
1177
        } catch (NotFound e1) {
1178
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1179
                    + e1.getMessage());
1180

    
1181
        } catch (InvalidRequest e1) {
1182
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1183
                    + e1.getMessage());
1184

    
1185
        }
1186

    
1187
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
1188
            " for identifier " + pid.getValue());
1189

    
1190
        // if the person is authorized, perform the read
1191
        if (allowed) {
1192
            try {
1193
                inputStream = MetacatHandler.read(localId);
1194
            } catch (Exception e) {
1195
                throw new ServiceFailure("1020", "The object specified by " + 
1196
                    pid.getValue() + "could not be returned due to error: " + e.getMessage());
1197
            }
1198
        }
1199

    
1200
        // if we fail to set the input stream
1201
        if (inputStream == null) {
1202
            throw new ServiceFailure("2181", "The object specified by " + 
1203
                pid.getValue() + "does not exist at this node.");
1204
        }
1205

    
1206
        // log the replica event
1207
        String principal = null;
1208
        if (session.getSubject() != null) {
1209
            principal = session.getSubject().getValue();
1210
        }
1211
        EventLog.getInstance().log(request.getRemoteAddr(), 
1212
            request.getHeader("User-Agent"), principal, localId, "replicate");
1213

    
1214
        return inputStream;
1215
    }
1216

    
1217
    /**
1218
     * A method to notify the Member Node that the authoritative copy of 
1219
     * system metadata on the Coordinating Nodes has changed.
1220
     * 
1221
     * @param session   Session information that contains the identity of the 
1222
     *                  calling user as retrieved from the X.509 certificate 
1223
     *                  which must be traceable to the CILogon service.
1224
     * @param serialVersion   The serialVersion of the system metadata
1225
     * @param dateSysMetaLastModified  The time stamp for when the system metadata was changed
1226
     * @throws NotImplemented
1227
     * @throws ServiceFailure
1228
     * @throws NotAuthorized
1229
     * @throws InvalidRequest
1230
     * @throws InvalidToken
1231
     */
1232
    public boolean systemMetadataChanged(Session session, Identifier pid,
1233
        long serialVersion, Date dateSysMetaLastModified) 
1234
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
1235
        InvalidToken {
1236
        
1237
        // cannot be called by public
1238
        if (session == null) {
1239
        	throw new InvalidToken("1332", "No session was provided.");
1240
        }
1241

    
1242
        String serviceFailureCode = "1333";
1243
        Identifier sid = getPIDForSID(pid, serviceFailureCode);
1244
        if(sid != null) {
1245
            pid = sid;
1246
        }
1247
        
1248
        SystemMetadata currentLocalSysMeta = null;
1249
        SystemMetadata newSysMeta = null;
1250
        CNode cn = D1Client.getCN();
1251
        NodeList nodeList = null;
1252
        Subject callingSubject = null;
1253
        boolean allowed = false;
1254
        
1255
        // are we allowed to call this?
1256
        callingSubject = session.getSubject();
1257
        nodeList = cn.listNodes();
1258
        
1259
        for(Node node : nodeList.getNodeList()) {
1260
            // must be a CN
1261
            if ( node.getType().equals(NodeType.CN)) {
1262
               List<Subject> subjectList = node.getSubjectList();
1263
               // the calling subject must be in the subject list
1264
               if ( subjectList.contains(callingSubject)) {
1265
                   allowed = true;
1266
                   
1267
               }
1268
               
1269
            }
1270
        }
1271
        
1272
        if (!allowed ) {
1273
            String msg = "The subject identified by " + callingSubject.getValue() +
1274
              " is not authorized to call this service.";
1275
            throw new NotAuthorized("1331", msg);
1276
            
1277
        }
1278
        
1279
        // compare what we have locally to what is sent in the change notification
1280
        try {
1281
            currentLocalSysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1282
             
1283
        } catch (RuntimeException e) {
1284
            String msg = "SystemMetadata for pid " + pid.getValue() +
1285
              " couldn't be updated because it couldn't be found locally: " +
1286
              e.getMessage();
1287
            logMetacat.error(msg);
1288
            ServiceFailure sf = new ServiceFailure("1333", msg);
1289
            sf.initCause(e);
1290
            throw sf; 
1291
        }
1292
        
1293
        if (currentLocalSysMeta.getSerialVersion().longValue() < serialVersion ) {
1294
            try {
1295
                newSysMeta = cn.getSystemMetadata(null, pid);
1296
            } catch (NotFound e) {
1297
                // huh? you just said you had it
1298
            	String msg = "On updating the local copy of system metadata " + 
1299
                "for pid " + pid.getValue() +", the CN reports it is not found." +
1300
                " The error message was: " + e.getMessage();
1301
                logMetacat.error(msg);
1302
                ServiceFailure sf = new ServiceFailure("1333", msg);
1303
                sf.initCause(e);
1304
                throw sf;
1305
            }
1306
            
1307
            //check about the sid in the system metadata
1308
            Identifier newSID = newSysMeta.getSeriesId();
1309
            if(newSID != null) {
1310
                if (!isValidIdentifier(newSID)) {
1311
                    throw new InvalidRequest("1334", "The series identifier in the new system metadata is invalid.");
1312
                }
1313
                Identifier currentSID = currentLocalSysMeta.getSeriesId();
1314
                if( currentSID != null && currentSID.getValue() != null) {
1315
                    if(!newSID.getValue().equals(currentSID.getValue())) {
1316
                        //newSID doesn't match the currentSID. The newSID shouldn't be used.
1317
                        try {
1318
                            if(IdentifierManager.getInstance().identifierExists(newSID.getValue())) {
1319
                                throw new InvalidRequest("1334", "The series identifier "+newSID.getValue()+" in the new system metadata has been used by another object.");
1320
                            }
1321
                        } catch (SQLException sql) {
1322
                            throw new ServiceFailure("1333", "Couldn't determine if the SID "+newSID.getValue()+" in the system metadata exists in the node since "+sql.getMessage());
1323
                        }
1324
                        
1325
                    }
1326
                } else {
1327
                    //newSID shouldn't be used
1328
                    try {
1329
                        if(IdentifierManager.getInstance().identifierExists(newSID.getValue())) {
1330
                            throw new InvalidRequest("1334", "The series identifier "+newSID.getValue()+" in the new system metadata has been used by another object.");
1331
                        }
1332
                    } catch (SQLException sql) {
1333
                        throw new ServiceFailure("1333", "Couldn't determine if the SID "+newSID.getValue()+" in the system metadata exists in the node since "+sql.getMessage());
1334
                    }
1335
                }
1336
            }
1337
            // update the local copy of system metadata for the pid
1338
            try {
1339
                HazelcastService.getInstance().getSystemMetadataMap().put(newSysMeta.getIdentifier(), newSysMeta);
1340
                logMetacat.info("Updated local copy of system metadata for pid " +
1341
                    pid.getValue() + " after change notification from the CN.");
1342
                
1343
                // TODO: consider inspecting the change for archive
1344
                // see: https://projects.ecoinformatics.org/ecoinfo/issues/6417
1345
//                if (newSysMeta.getArchived() != null && newSysMeta.getArchived().booleanValue()) {
1346
//                	try {
1347
//						this.archive(session, newSysMeta.getIdentifier());
1348
//					} catch (NotFound e) {
1349
//						// do we care? nothing to do about it now
1350
//						logMetacat.error(e.getMessage(), e);
1351
//					}
1352
//                }
1353
                
1354
            } catch (RuntimeException e) {
1355
                String msg = "SystemMetadata for pid " + pid.getValue() +
1356
                  " couldn't be updated: " +
1357
                  e.getMessage();
1358
                logMetacat.error(msg);
1359
                ServiceFailure sf = new ServiceFailure("1333", msg);
1360
                sf.initCause(e);
1361
                throw sf;
1362
            }
1363
            
1364
            // submit for indexing
1365
            try {
1366
				MetacatSolrIndex.getInstance().submit(newSysMeta.getIdentifier(), newSysMeta, null, true);
1367
			} catch (Exception e) {
1368
                logMetacat.error("Could not submit changed systemMetadata for indexing, pid: " + newSysMeta.getIdentifier().getValue(), e);
1369
			}
1370
        }
1371
        
1372
        return true;
1373
        
1374
    }
1375
    
1376
    /*
1377
     * Set the replication status for the object on the Coordinating Node
1378
     * 
1379
     * @param session - the session for the this target node
1380
     * @param pid - the identifier of the object being updated
1381
     * @param nodeId - the identifier of this target node
1382
     * @param status - the replication status to set
1383
     * @param failure - the exception to include, if any
1384
     */
1385
    private void setReplicationStatus(Session session, Identifier pid, 
1386
        NodeReference nodeId, ReplicationStatus status, BaseException failure) 
1387
        throws ServiceFailure, NotImplemented, NotAuthorized, 
1388
        InvalidRequest {
1389
        
1390
        // call the CN as the MN to set the replication status
1391
        try {
1392
            this.cn = D1Client.getCN();
1393
            this.cn.setReplicationStatus(session, pid, nodeId,
1394
                    status, failure);
1395
            
1396
        } catch (InvalidToken e) {
1397
        	String msg = "Could not set the replication status for " + pid.getValue() + " on the CN (InvalidToken): " + e.getMessage();
1398
            logMetacat.error(msg);
1399
        	throw new ServiceFailure("2151",
1400
                    msg);
1401
            
1402
        } catch (NotFound e) {
1403
        	String msg = "Could not set the replication status for " + pid.getValue() + " on the CN (NotFound): " + e.getMessage();
1404
            logMetacat.error(msg);
1405
        	throw new ServiceFailure("2151",
1406
                    msg);
1407
            
1408
        }
1409
    }
1410
    
1411
    private SystemMetadata makePublicIfNot(SystemMetadata sysmeta, Identifier pid) throws ServiceFailure, InvalidToken, NotFound, NotImplemented, InvalidRequest {
1412
    	// check if it is publicly readable
1413
		boolean isPublic = false;
1414
		Subject publicSubject = new Subject();
1415
		publicSubject.setValue(Constants.SUBJECT_PUBLIC);
1416
		Session publicSession = new Session();
1417
		publicSession.setSubject(publicSubject);
1418
		AccessRule publicRule = new AccessRule();
1419
		publicRule.addPermission(Permission.READ);
1420
		publicRule.addSubject(publicSubject);
1421
		
1422
		// see if we need to add the rule
1423
		try {
1424
			isPublic = this.isAuthorized(publicSession, pid, Permission.READ);
1425
		} catch (NotAuthorized na) {
1426
			// well, certainly not authorized for public read!
1427
		}
1428
		if (!isPublic) {
1429
			sysmeta.getAccessPolicy().addAllow(publicRule);
1430
		}
1431
		
1432
		return sysmeta;
1433
    }
1434

    
1435
	@Override
1436
	public Identifier generateIdentifier(Session session, String scheme, String fragment)
1437
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1438
			InvalidRequest {
1439
		
1440
		// check for null session
1441
        if (session == null) {
1442
          throw new InvalidToken("2190", "Session is required to generate an Identifier at this Node.");
1443
        }
1444
		
1445
		Identifier identifier = new Identifier();
1446
		
1447
		// handle different schemes
1448
		if (scheme.equalsIgnoreCase(UUID_SCHEME)) {
1449
			// UUID
1450
			UUID uuid = UUID.randomUUID();
1451
            identifier.setValue(UUID_PREFIX + uuid.toString());
1452
		} else if (scheme.equalsIgnoreCase(DOI_SCHEME)) {
1453
			// generate a DOI
1454
			try {
1455
				identifier = DOIService.getInstance().generateDOI();
1456
			} catch (EZIDException e) {
1457
				ServiceFailure sf = new ServiceFailure("2191", "Could not generate DOI: " + e.getMessage());
1458
				sf.initCause(e);
1459
				throw sf;
1460
			}
1461
		} else {
1462
			// default if we don't know the scheme
1463
			if (fragment != null) {
1464
				// for now, just autogen with fragment
1465
				String autogenId = DocumentUtil.generateDocumentId(fragment, 0);
1466
				identifier.setValue(autogenId);			
1467
			} else {
1468
				// autogen with no fragment
1469
				String autogenId = DocumentUtil.generateDocumentId(0);
1470
				identifier.setValue(autogenId);
1471
			}
1472
		}
1473
		
1474
		// TODO: reserve the identifier with the CN. We can only do this when
1475
		// 1) the MN is part of a CN cluster
1476
		// 2) the request is from an authenticated user
1477
		
1478
		return identifier;
1479
	}
1480

    
1481
	
1482

    
1483
	@Override
1484
	public QueryEngineDescription getQueryEngineDescription(Session session, String engine)
1485
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1486
			NotFound {
1487
	    if(engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
1488
	        if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
1489
                throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1490
            }
1491
	        QueryEngineDescription qed = new QueryEngineDescription();
1492
	        qed.setName(EnabledQueryEngines.PATHQUERYENGINE);
1493
	        qed.setQueryEngineVersion("1.0");
1494
	        qed.addAdditionalInfo("This is the traditional structured query for Metacat");
1495
	        Vector<String> pathsForIndexing = null;
1496
	        try {
1497
	            pathsForIndexing = SystemUtil.getPathsForIndexing();
1498
	        } catch (MetacatUtilException e) {
1499
	            logMetacat.warn("Could not get index paths", e);
1500
	        }
1501
	        for (String fieldName: pathsForIndexing) {
1502
	            QueryField field = new QueryField();
1503
	            field.addDescription("Indexed field for path '" + fieldName + "'");
1504
	            field.setName(fieldName);
1505
	            field.setReturnable(true);
1506
	            field.setSearchable(true);
1507
	            field.setSortable(false);
1508
	            // TODO: determine type and multivaluedness
1509
	            field.setType(String.class.getName());
1510
	            //field.setMultivalued(true);
1511
	            qed.addQueryField(field);
1512
	        }
1513
	        return qed;
1514
	    } else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
1515
	        if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
1516
                throw new NotImplemented("0000", "MNodeService.getQueryEngineDescription - the query engine "+engine +" hasn't been implemented or has been disabled.");
1517
            }
1518
	        try {
1519
	            QueryEngineDescription qed = MetacatSolrEngineDescriptionHandler.getInstance().getQueryEngineDescritpion();
1520
	            return qed;
1521
	        } catch (Exception e) {
1522
	            e.printStackTrace();
1523
	            throw new ServiceFailure("Solr server error", e.getMessage());
1524
	        }
1525
	    } else {
1526
	        throw new NotFound("404", "The Metacat member node can't find the query engine - "+engine);
1527
	    }
1528
		
1529
	}
1530

    
1531
	@Override
1532
	public QueryEngineList listQueryEngines(Session session) throws InvalidToken,
1533
			ServiceFailure, NotAuthorized, NotImplemented {
1534
		QueryEngineList qel = new QueryEngineList();
1535
		//qel.addQueryEngine(EnabledQueryEngines.PATHQUERYENGINE);
1536
		//qel.addQueryEngine(EnabledQueryEngines.SOLRENGINE);
1537
		List<String> enables = EnabledQueryEngines.getInstance().getEnabled();
1538
		for(String name : enables) {
1539
		    qel.addQueryEngine(name);
1540
		}
1541
		return qel;
1542
	}
1543

    
1544
	@Override
1545
	public InputStream query(Session session, String engine, String query) throws InvalidToken,
1546
			ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented,
1547
			NotFound {
1548
	    String user = Constants.SUBJECT_PUBLIC;
1549
        String[] groups= null;
1550
        Set<Subject> subjects = null;
1551
        if (session != null) {
1552
            user = session.getSubject().getValue();
1553
            subjects = AuthUtils.authorizedClientSubjects(session);
1554
            if (subjects != null) {
1555
                List<String> groupList = new ArrayList<String>();
1556
                for (Subject subject: subjects) {
1557
                    groupList.add(subject.getValue());
1558
                }
1559
                groups = groupList.toArray(new String[0]);
1560
            }
1561
        } else {
1562
            //add the public user subject to the set 
1563
            Subject subject = new Subject();
1564
            subject.setValue(Constants.SUBJECT_PUBLIC);
1565
            subjects = new HashSet<Subject>();
1566
            subjects.add(subject);
1567
        }
1568
        //System.out.println("====== user is "+user);
1569
        //System.out.println("====== groups are "+groups);
1570
		if (engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
1571
		    if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
1572
                throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1573
            }
1574
			try {
1575
				DBQuery queryobj = new DBQuery();
1576
				
1577
				String results = queryobj.performPathquery(query, user, groups);
1578
				ContentTypeByteArrayInputStream ctbais = new ContentTypeByteArrayInputStream(results.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1579
				ctbais.setContentType("text/xml");
1580
				return ctbais;
1581

    
1582
			} catch (Exception e) {
1583
				throw new ServiceFailure("Pathquery error", e.getMessage());
1584
			}
1585
			
1586
		} else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
1587
		    if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
1588
		        throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1589
		    }
1590
		    logMetacat.info("The query is ==================================== \n"+query);
1591
		    try {
1592
		        
1593
                return MetacatSolrIndex.getInstance().query(query, subjects);
1594
            } catch (Exception e) {
1595
                // TODO Auto-generated catch block
1596
                throw new ServiceFailure("Solr server error", e.getMessage());
1597
            } 
1598
		}
1599
		return null;
1600
	}
1601
	
1602
	/**
1603
	 * Given an existing Science Metadata PID, this method mints a DOI
1604
	 * and updates the original object "publishing" the update with the DOI.
1605
	 * This includes updating the ORE map that describes the Science Metadata+data.
1606
	 * TODO: ensure all referenced objects allow public read
1607
	 * 
1608
	 * @see https://projects.ecoinformatics.org/ecoinfo/issues/6014
1609
	 * 
1610
	 * @param originalIdentifier
1611
	 * @param request
1612
	 * @throws InvalidRequest 
1613
	 * @throws NotImplemented 
1614
	 * @throws NotAuthorized 
1615
	 * @throws ServiceFailure 
1616
	 * @throws InvalidToken 
1617
	 * @throws NotFound
1618
	 * @throws InvalidSystemMetadata 
1619
	 * @throws InsufficientResources 
1620
	 * @throws UnsupportedType 
1621
	 * @throws IdentifierNotUnique 
1622
	 */
1623
	public Identifier publish(Session session, Identifier originalIdentifier) throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented, InvalidRequest, NotFound, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata {
1624
		
1625
		
1626
		// get the original SM
1627
		SystemMetadata originalSystemMetadata = this.getSystemMetadata(session, originalIdentifier);
1628

    
1629
		// make copy of it using the marshaller to ensure DEEP copy
1630
		SystemMetadata sysmeta = null;
1631
		try {
1632
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
1633
			TypeMarshaller.marshalTypeToOutputStream(originalSystemMetadata, baos);
1634
			sysmeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, new ByteArrayInputStream(baos.toByteArray()));
1635
		} catch (Exception e) {
1636
			// report as service failure
1637
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1638
			sf.initCause(e);
1639
			throw sf;
1640
		}
1641

    
1642
		// mint a DOI for the new revision
1643
		Identifier newIdentifier = this.generateIdentifier(session, MNodeService.DOI_SCHEME, null);
1644
				
1645
		// set new metadata values
1646
		sysmeta.setIdentifier(newIdentifier);
1647
		sysmeta.setObsoletes(originalIdentifier);
1648
		sysmeta.setObsoletedBy(null);
1649
		
1650
		// ensure it is publicly readable
1651
		sysmeta = makePublicIfNot(sysmeta, originalIdentifier);
1652
		
1653
		// get the bytes
1654
		InputStream inputStream = this.get(session, originalIdentifier);
1655
		
1656
		// update the object
1657
		this.update(session, originalIdentifier, inputStream, newIdentifier, sysmeta);
1658
		
1659
		// update ORE that references the scimeta
1660
		// first try the naive method, then check the SOLR index
1661
		try {
1662
			String localId = IdentifierManager.getInstance().getLocalId(originalIdentifier.getValue());
1663
			
1664
			Identifier potentialOreIdentifier = new Identifier();
1665
			potentialOreIdentifier.setValue(SystemMetadataFactory.RESOURCE_MAP_PREFIX + localId);
1666
			
1667
			InputStream oreInputStream = null;
1668
			try {
1669
				oreInputStream = this.get(session, potentialOreIdentifier);
1670
			} catch (NotFound nf) {
1671
				// this is probably okay for many sci meta data docs
1672
				logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
1673
				// try the SOLR index
1674
				List<Identifier> potentialOreIdentifiers = this.lookupOreFor(originalIdentifier, false);
1675
				if (potentialOreIdentifiers != null) {
1676
					potentialOreIdentifier = potentialOreIdentifiers.get(0);
1677
					try {
1678
						oreInputStream = this.get(session, potentialOreIdentifier);
1679
					} catch (NotFound nf2) {
1680
						// this is probably okay for many sci meta data docs
1681
						logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
1682
					}
1683
				}
1684
			}
1685
			if (oreInputStream != null) {
1686
				Identifier newOreIdentifier = MNodeService.getInstance(request).generateIdentifier(session, MNodeService.UUID_SCHEME, null);
1687
	
1688
				Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
1689
				Map<Identifier, List<Identifier>> sciMetaMap = resourceMapStructure.get(potentialOreIdentifier);
1690
				List<Identifier> dataIdentifiers = sciMetaMap.get(originalIdentifier);
1691
					
1692
				// reconstruct the ORE with the new identifiers
1693
				sciMetaMap.remove(originalIdentifier);
1694
				sciMetaMap.put(newIdentifier, dataIdentifiers);
1695
				
1696
				ResourceMap resourceMap = ResourceMapFactory.getInstance().createResourceMap(newOreIdentifier, sciMetaMap);
1697
				String resourceMapString = ResourceMapFactory.getInstance().serializeResourceMap(resourceMap);
1698
				
1699
				// get the original ORE SM and update the values
1700
				SystemMetadata originalOreSysMeta = this.getSystemMetadata(session, potentialOreIdentifier);
1701
				SystemMetadata oreSysMeta = new SystemMetadata();
1702
				try {
1703
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
1704
					TypeMarshaller.marshalTypeToOutputStream(originalOreSysMeta, baos);
1705
					oreSysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, new ByteArrayInputStream(baos.toByteArray()));
1706
				} catch (Exception e) {
1707
					// report as service failure
1708
					ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1709
					sf.initCause(e);
1710
					throw sf;
1711
				}
1712

    
1713
				oreSysMeta.setIdentifier(newOreIdentifier);
1714
				oreSysMeta.setObsoletes(potentialOreIdentifier);
1715
				oreSysMeta.setObsoletedBy(null);
1716
				oreSysMeta.setSize(BigInteger.valueOf(resourceMapString.getBytes("UTF-8").length));
1717
				oreSysMeta.setChecksum(ChecksumUtil.checksum(resourceMapString.getBytes("UTF-8"), oreSysMeta.getChecksum().getAlgorithm()));
1718
				
1719
				// ensure ORE is publicly readable
1720
				oreSysMeta = makePublicIfNot(oreSysMeta, potentialOreIdentifier);
1721
				
1722
				// ensure all data objects allow public read
1723
				List<String> pidsToSync = new ArrayList<String>();
1724
				for (Identifier dataId: dataIdentifiers) {
1725
					SystemMetadata dataSysMeta = this.getSystemMetadata(session, dataId);
1726
					dataSysMeta = makePublicIfNot(dataSysMeta, dataId);
1727
					this.updateSystemMetadata(dataSysMeta);
1728
					pidsToSync.add(dataId.getValue());
1729
				}
1730
				SyncAccessPolicy sap = new SyncAccessPolicy();
1731
				try {
1732
					sap.sync(pidsToSync);
1733
				} catch (Exception e) {
1734
					// ignore
1735
					logMetacat.warn("Error attempting to sync access for data objects when publishing package");
1736
				}
1737
				
1738
				// save the updated ORE
1739
				this.update(
1740
						session, 
1741
						potentialOreIdentifier, 
1742
						new ByteArrayInputStream(resourceMapString.getBytes("UTF-8")), 
1743
						newOreIdentifier, 
1744
						oreSysMeta);
1745
				
1746
			} else {
1747
				// create a new ORE for them
1748
				// https://projects.ecoinformatics.org/ecoinfo/issues/6194
1749
				try {
1750
					// find the local id for the NEW package.
1751
					String newLocalId = IdentifierManager.getInstance().getLocalId(newIdentifier.getValue());
1752
	
1753
					@SuppressWarnings("unused")
1754
					SystemMetadata extraSysMeta = SystemMetadataFactory.createSystemMetadata(newLocalId, true, false);
1755
					// should be done generating the ORE here, and the same permissions were used from the metadata object
1756
					
1757
				} catch (Exception e) {
1758
					// oops, guess there was a problem - no package for you
1759
					logMetacat.error("Could not generate new ORE for published object: " + newIdentifier.getValue(), e);
1760
				}
1761
			}
1762
		} catch (McdbDocNotFoundException e) {
1763
			// report as service failure
1764
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1765
			sf.initCause(e);
1766
			throw sf;
1767
		} catch (UnsupportedEncodingException e) {
1768
			// report as service failure
1769
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1770
			sf.initCause(e);
1771
			throw sf;
1772
		} catch (OREException e) {
1773
			// report as service failure
1774
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1775
			sf.initCause(e);
1776
			throw sf;
1777
		} catch (URISyntaxException e) {
1778
			// report as service failure
1779
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1780
			sf.initCause(e);
1781
			throw sf;
1782
		} catch (OREParserException e) {
1783
			// report as service failure
1784
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1785
			sf.initCause(e);
1786
			throw sf;
1787
		} catch (ORESerialiserException e) {
1788
			// report as service failure
1789
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1790
			sf.initCause(e);
1791
			throw sf;
1792
		} catch (NoSuchAlgorithmException e) {
1793
			// report as service failure
1794
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1795
			sf.initCause(e);
1796
			throw sf;
1797
		} catch (SQLException e) {
1798
            // report as service failure
1799
            ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1800
            sf.initCause(e);
1801
            throw sf;
1802
        }
1803
		
1804
		return newIdentifier;
1805
	}
1806
	
1807
	/**
1808
	 * Determines if we already have registered an ORE map for this package
1809
	 * NOTE: uses a solr query to locate OREs for the object
1810
	 * @param guid of the EML/packaging object
1811
	 * @return list of resource map identifiers for the given pid
1812
	 */
1813
	public List<Identifier> lookupOreFor(Identifier guid, boolean includeObsolete) {
1814
		// Search for the ORE if we can find it
1815
		String pid = guid.getValue();
1816
		List<Identifier> retList = null;
1817
		try {
1818
			String query = "fl=id,resourceMap&wt=xml&q=-obsoletedBy:[* TO *]+resourceMap:[* TO *]+id:\"" + pid + "\"";
1819
			if (includeObsolete) {
1820
				query = "fl=id,resourceMap&wt=xml&q=resourceMap:[* TO *]+id:\"" + pid + "\"";
1821
			}
1822
			
1823
			InputStream results = this.query(null, "solr", query);
1824
			org.w3c.dom.Node rootNode = XMLUtilities.getXMLReaderAsDOMTreeRootNode(new InputStreamReader(results, "UTF-8"));
1825
			//String resultString = XMLUtilities.getDOMTreeAsString(rootNode);
1826
			org.w3c.dom.NodeList nodeList = XMLUtilities.getNodeListWithXPath(rootNode, "//arr[@name=\"resourceMap\"]/str");
1827
			if (nodeList != null && nodeList.getLength() > 0) {
1828
				retList = new ArrayList<Identifier>();
1829
				for (int i = 0; i < nodeList.getLength(); i++) {
1830
					String found = nodeList.item(i).getFirstChild().getNodeValue();
1831
					Identifier oreId = new Identifier();
1832
					oreId.setValue(found);
1833
					retList.add(oreId);
1834
				}
1835
			}
1836
		} catch (Exception e) {
1837
			logMetacat.error("Error checking for resourceMap[s] on pid " + pid + ". " + e.getMessage(), e);
1838
		}
1839
		
1840
		return retList;
1841
	}
1842
	
1843

    
1844
	@Override
1845
	public InputStream getPackage(Session session, ObjectFormatIdentifier formatId,
1846
			Identifier pid) throws InvalidToken, ServiceFailure,
1847
			NotAuthorized, InvalidRequest, NotImplemented, NotFound {
1848
		InputStream bagInputStream = null;
1849
		BagFactory bagFactory = new BagFactory();
1850
		Bag bag = bagFactory.createBag();
1851
		
1852
		// track the temp files we use so we can delete them when finished
1853
		List<File> tempFiles = new ArrayList<File>();
1854
		
1855
		// the pids to include in the package
1856
		List<Identifier> packagePids = new ArrayList<Identifier>();
1857
		
1858
		// catch non-D1 service errors and throw as ServiceFailures
1859
		try {
1860
			//Create a map of dataone ids and file names
1861
			Map<Identifier, String> fileNames = new HashMap<Identifier, String>();
1862
			
1863
			// track the pid-to-file mapping
1864
			StringBuffer pidMapping = new StringBuffer();
1865
			
1866
			// find the package contents
1867
			SystemMetadata sysMeta = this.getSystemMetadata(session, pid);
1868
			if (ObjectFormatCache.getInstance().getFormat(sysMeta.getFormatId()).getFormatType().equals("RESOURCE")) {
1869
				//Get the resource map as a map of Identifiers
1870
				InputStream oreInputStream = this.get(session, pid);
1871
				Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
1872
				packagePids.addAll(resourceMapStructure.keySet());
1873
				//Loop through each object in this resource map
1874
				for (Map<Identifier, List<Identifier>> entries: resourceMapStructure.values()) {
1875
					//Loop through each metadata object in this entry
1876
					Set<Identifier> metadataIdentifiers = entries.keySet();
1877
					for(Identifier metadataID: metadataIdentifiers){
1878
						try{
1879
							//Get the system metadata for this metadata object
1880
							SystemMetadata metadataSysMeta = this.getSystemMetadata(session, metadataID);
1881
							
1882
							// include user-friendly metadata
1883
							if (ObjectFormatCache.getInstance().getFormat(metadataSysMeta.getFormatId()).getFormatType().equals("METADATA")) {
1884
								InputStream metadataStream = this.get(session, metadataID);
1885
							
1886
								try {
1887
									// transform
1888
						            String format = "default";
1889

    
1890
									DBTransform transformer = new DBTransform();
1891
						            String documentContent = IOUtils.toString(metadataStream, "UTF-8");
1892
						            String sourceType = metadataSysMeta.getFormatId().getValue();
1893
						            String targetType = "-//W3C//HTML//EN";
1894
						            ByteArrayOutputStream baos = new ByteArrayOutputStream();
1895
						            Writer writer = new OutputStreamWriter(baos , "UTF-8");
1896
						            // TODO: include more params?
1897
						            Hashtable<String, String[]> params = new Hashtable<String, String[]>();
1898
						            String localId = null;
1899
									try {
1900
										localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1901
									} catch (McdbDocNotFoundException e) {
1902
										throw new NotFound("1020", e.getMessage());
1903
									}
1904
									params.put("qformat", new String[] {format});	            
1905
						            params.put("docid", new String[] {localId});
1906
						            params.put("pid", new String[] {pid.getValue()});
1907
						            params.put("displaymodule", new String[] {"printall"});
1908
						            
1909
						            transformer.transformXMLDocument(
1910
						                    documentContent , 
1911
						                    sourceType, 
1912
						                    targetType , 
1913
						                    format, 
1914
						                    writer, 
1915
						                    params, 
1916
						                    null //sessionid
1917
						                    );
1918
						            
1919
						            // finally, get the HTML back
1920
						            ContentTypeByteArrayInputStream resultInputStream = new ContentTypeByteArrayInputStream(baos.toByteArray());
1921
						            
1922
						            // write to temp file with correct css path
1923
						            File tmpDir = File.createTempFile("package_", "_dir");
1924
						            tmpDir.delete();
1925
						            tmpDir.mkdir();
1926
						            File htmlFile = File.createTempFile("metadata", ".html", tmpDir);
1927
						            File cssDir = new File(tmpDir, format);
1928
						            cssDir.mkdir();
1929
						            File cssFile = new File(tmpDir, format + "/" + format + ".css");
1930
						            String pdfFileName = metadataID.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-METADATA.pdf";
1931
						            File pdfFile = new File(tmpDir, pdfFileName);
1932
						            //File pdfFile = File.createTempFile("metadata", ".pdf", tmpDir);
1933
						            
1934
						            // put the CSS file in place for the html to find it
1935
						            String originalCssPath = SystemUtil.getContextDir() + "/style/skins/" + format + "/" + format + ".css";
1936
						            IOUtils.copy(new FileInputStream(originalCssPath), new FileOutputStream(cssFile));
1937
						            
1938
						            // write the HTML file
1939
						            IOUtils.copy(resultInputStream, new FileOutputStream(htmlFile));
1940
						            
1941
						            // convert to PDF
1942
						            HtmlToPdf.export(htmlFile.getAbsolutePath(), pdfFile.getAbsolutePath());
1943
						            
1944
						            //add to the package
1945
						            bag.addFileToPayload(pdfFile);
1946
									pidMapping.append(metadataID.getValue() + " (pdf)" +  "\t" + "data/" + pdfFile.getName() + "\n");
1947
						            
1948
						            // mark for clean up after we are done
1949
									htmlFile.delete();
1950
									cssFile.delete();
1951
									cssDir.delete();
1952
						            tempFiles.add(tmpDir);
1953
									tempFiles.add(pdfFile); // delete this first later on
1954
						            
1955
								} catch (Exception e) {
1956
									logMetacat.warn("Could not transform metadata", e);
1957
								}
1958
							}
1959

    
1960
							
1961
							//If this is in eml format, extract the filename and GUID from each entity in its package
1962
							if (metadataSysMeta.getFormatId().getValue().startsWith("eml://")) {
1963
								//Get the package
1964
								DataPackageParserInterface parser = new Eml200DataPackageParser();
1965
								InputStream emlStream = this.get(session, metadataID);
1966
								parser.parse(emlStream);
1967
								DataPackage dataPackage = parser.getDataPackage();
1968
								
1969
								//Get all the entities in this package and loop through each to extract its ID and file name
1970
								Entity[] entities = dataPackage.getEntityList();
1971
								for(Entity entity: entities){
1972
									try{
1973
										//Get the file name from the metadata
1974
										String fileNameFromMetadata = entity.getName();
1975
										
1976
										//Get the ecogrid URL from the metadata
1977
										String ecogridIdentifier = entity.getEntityIdentifier();
1978
										//Parse the ecogrid URL to get the local id
1979
										String idFromMetadata = DocumentUtil.getAccessionNumberFromEcogridIdentifier(ecogridIdentifier);
1980
										
1981
										//Get the docid and rev pair
1982
										String docid = DocumentUtil.getDocIdFromString(idFromMetadata);
1983
										String rev = DocumentUtil.getRevisionStringFromString(idFromMetadata);
1984
										
1985
										//Get the GUID
1986
										String guid = IdentifierManager.getInstance().getGUID(docid, Integer.valueOf(rev));
1987
										Identifier dataIdentifier = new Identifier();
1988
										dataIdentifier.setValue(guid);
1989
										
1990
										//Add the GUID to our GUID & file name map
1991
										fileNames.put(dataIdentifier, fileNameFromMetadata);
1992
									}
1993
									catch(Exception e){
1994
										//Prevent just one entity error
1995
										e.printStackTrace();
1996
										logMetacat.debug(e.getMessage(), e);
1997
									}
1998
								}
1999
							}
2000
						}
2001
						catch(Exception e){
2002
							//Catch errors that would prevent package download
2003
							logMetacat.debug(e.toString());
2004
						}
2005
					}
2006
					packagePids.addAll(entries.keySet());
2007
					for (List<Identifier> dataPids: entries.values()) {
2008
						packagePids.addAll(dataPids);
2009
					}
2010
				}
2011
			} else {
2012
				// just the lone pid in this package
2013
				packagePids.add(pid);
2014
			}
2015
			
2016
			//Create a temp file, then delete it and make a directory with that name
2017
			File tempDir = File.createTempFile("temp", Long.toString(System.nanoTime()));
2018
			tempDir.delete();
2019
			tempDir = new File(tempDir.getPath() + "_dir");
2020
			tempDir.mkdir();			
2021
			tempFiles.add(tempDir);
2022
			File pidMappingFile = new File(tempDir, "pid-mapping.txt");
2023
			
2024
			// loop through the package contents
2025
			for (Identifier entryPid: packagePids) {
2026
				//Get the system metadata for each item
2027
				SystemMetadata entrySysMeta = this.getSystemMetadata(session, entryPid);					
2028
				
2029
				String objectFormatType = ObjectFormatCache.getInstance().getFormat(entrySysMeta.getFormatId()).getFormatType();
2030
				String fileName = null;
2031
				
2032
				//TODO: Be more specific of what characters to replace. Make sure periods arent replaced for the filename from metadata
2033
				//Our default file name is just the ID + format type (e.g. walker.1.1-DATA)
2034
				fileName = entryPid.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-" + objectFormatType;
2035

    
2036
				if(fileNames.containsKey(entryPid)){
2037
					//Let's use the file name and extension from the metadata is we have it
2038
					fileName = entryPid.getValue().replaceAll("[^a-zA-Z0-9\\-\\.]", "_") + "-" + fileNames.get(entryPid).replaceAll("[^a-zA-Z0-9\\-\\.]", "_");
2039
				}
2040
				else{
2041
					//If we couldn't find a given file name, use the system metadata extension
2042
					String extension = ObjectFormatInfo.instance().getExtension(entrySysMeta.getFormatId().getValue());
2043
					fileName += extension;
2044
				}
2045
				
2046
		        //Create a new file for this item and add to the list
2047
				File tempFile = new File(tempDir, fileName);
2048
				tempFiles.add(tempFile);
2049
				
2050
				InputStream entryInputStream = this.get(session, entryPid);			
2051
				IOUtils.copy(entryInputStream, new FileOutputStream(tempFile));
2052
				bag.addFileToPayload(tempFile);
2053
				pidMapping.append(entryPid.getValue() + "\t" + "data/" + tempFile.getName() + "\n");
2054
			}
2055
			
2056
			//add the the pid to data file map
2057
			IOUtils.write(pidMapping.toString(), new FileOutputStream(pidMappingFile));
2058
			bag.addFileAsTag(pidMappingFile);
2059
			tempFiles.add(pidMappingFile);
2060
			
2061
			bag = bag.makeComplete();
2062
			
2063
			///Now create the zip file
2064
			//Use the pid as the file name prefix, replacing all non-word characters
2065
			String zipName = pid.getValue().replaceAll("\\W", "_");
2066
			
2067
			File bagFile = new File(tempDir, zipName+".zip");
2068
			
2069
			bag.setFile(bagFile);
2070
			ZipWriter zipWriter = new ZipWriter(bagFactory);
2071
			bag.write(zipWriter, bagFile);
2072
			bagFile = bag.getFile();
2073
			// use custom FIS that will delete the file when closed
2074
			bagInputStream = new DeleteOnCloseFileInputStream(bagFile);
2075
			// also mark for deletion on shutdown in case the stream is never closed
2076
			bagFile.deleteOnExit();
2077
			tempFiles.add(bagFile);
2078
			
2079
			// clean up other temp files
2080
			for (int i=tempFiles.size()-1; i>=0; i--){
2081
				tempFiles.get(i).delete();
2082
			}
2083
			
2084
		} catch (IOException e) {
2085
			// report as service failure
2086
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2087
			sf.initCause(e);
2088
			throw sf;
2089
		} catch (OREException e) {
2090
			// report as service failure
2091
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2092
			sf.initCause(e);
2093
			throw sf;
2094
		} catch (URISyntaxException e) {
2095
			// report as service failure
2096
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2097
			sf.initCause(e);
2098
			throw sf;
2099
		} catch (OREParserException e) {
2100
			// report as service failure
2101
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2102
			sf.initCause(e);
2103
			throw sf;
2104
		}
2105
		
2106
		return bagInputStream;
2107
	}
2108

    
2109
	@Override
2110
	public OptionList listViews(Session arg0) throws InvalidToken,
2111
			ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented {
2112
		OptionList views = new OptionList();
2113
		Vector<String> skinNames = null;
2114
		try {
2115
			skinNames = SkinUtil.getSkinNames();
2116
		} catch (PropertyNotFoundException e) {
2117
			throw new ServiceFailure("2841", e.getMessage());
2118
		}
2119
		for (String skinName: skinNames) {
2120
			views.addOption(skinName);
2121
		}
2122
		return views;
2123
	}
2124

    
2125
	@Override
2126
	public InputStream view(Session session, String format, Identifier pid)
2127
			throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest,
2128
			NotImplemented, NotFound {
2129
		InputStream resultInputStream = null;
2130
		
2131
		SystemMetadata sysMeta = this.getSystemMetadata(session, pid);
2132
		InputStream object = this.get(session, pid);
2133

    
2134
		try {
2135
			// can only transform metadata, really
2136
			ObjectFormat objectFormat = ObjectFormatCache.getInstance().getFormat(sysMeta.getFormatId());
2137
			if (objectFormat.getFormatType().equals("METADATA")) {
2138
				// transform
2139
				DBTransform transformer = new DBTransform();
2140
	            String documentContent = IOUtils.toString(object, "UTF-8");
2141
	            String sourceType = objectFormat.getFormatId().getValue();
2142
	            String targetType = "-//W3C//HTML//EN";
2143
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();
2144
	            Writer writer = new OutputStreamWriter(baos , "UTF-8");
2145
	            // TODO: include more params?
2146
	            Hashtable<String, String[]> params = new Hashtable<String, String[]>();
2147
	            String localId = null;
2148
				try {
2149
					localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
2150
				} catch (McdbDocNotFoundException e) {
2151
					throw new NotFound("1020", e.getMessage());
2152
				}
2153
	            params.put("qformat", new String[] {format});	            
2154
	            params.put("docid", new String[] {localId});
2155
	            params.put("pid", new String[] {pid.getValue()});
2156
	            transformer.transformXMLDocument(
2157
	                    documentContent , 
2158
	                    sourceType, 
2159
	                    targetType , 
2160
	                    format, 
2161
	                    writer, 
2162
	                    params, 
2163
	                    null //sessionid
2164
	                    );
2165
	            
2166
	            // finally, get the HTML back
2167
	            resultInputStream = new ContentTypeByteArrayInputStream(baos.toByteArray());
2168
	            ((ContentTypeByteArrayInputStream) resultInputStream).setContentType("text/html");
2169
	
2170
			} else {
2171
				// just return the raw bytes
2172
				resultInputStream = object;
2173
			}
2174
		} catch (IOException e) {
2175
			// report as service failure
2176
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2177
			sf.initCause(e);
2178
			throw sf;
2179
		} catch (PropertyNotFoundException e) {
2180
			// report as service failure
2181
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2182
			sf.initCause(e);
2183
			throw sf;
2184
		} catch (SQLException e) {
2185
			// report as service failure
2186
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2187
			sf.initCause(e);
2188
			throw sf;
2189
		} catch (ClassNotFoundException e) {
2190
			// report as service failure
2191
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
2192
			sf.initCause(e);
2193
			throw sf;
2194
		}
2195
		
2196
		return resultInputStream;
2197
	}	
2198
    
2199
}
(4-4/7)