001package ca.uhn.fhir.rest.client.interceptor; 002 003/* 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2017 University Health Network 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import ca.uhn.fhir.rest.client.IClientInterceptor; 024import ca.uhn.fhir.rest.client.api.IHttpRequest; 025import ca.uhn.fhir.rest.client.api.IHttpResponse; 026import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 027import org.apache.http.HttpEntity; 028import org.apache.http.HttpResponse; 029 030import java.io.IOException; 031 032/** 033 * Client interceptor which simply captures request and response objects and stores them so that they can be inspected after a client 034 * call has returned 035 */ 036public class CapturingInterceptor implements IClientInterceptor { 037 038 private IHttpRequest myLastRequest; 039 private IHttpResponse myLastResponse; 040 041 /** 042 * Clear the last request and response values 043 */ 044 public void clear() { 045 myLastRequest = null; 046 myLastResponse = null; 047 } 048 049 public IHttpRequest getLastRequest() { 050 return myLastRequest; 051 } 052 053 public IHttpResponse getLastResponse() { 054 return myLastResponse; 055 } 056 057 @Override 058 public void interceptRequest(IHttpRequest theRequest) { 059 myLastRequest = theRequest; 060 } 061 062 @Override 063 public void interceptResponse(IHttpResponse theResponse) { 064 //Buffer the reponse to avoid errors when content has already been read and the entity is not repeatable 065 try { 066 if(theResponse.getResponse() instanceof HttpResponse) { 067 HttpEntity entity = ((HttpResponse) theResponse.getResponse()).getEntity(); 068 if( entity != null && !entity.isRepeatable()){ 069 theResponse.bufferEntity(); 070 } 071 } else { 072 theResponse.bufferEntity(); 073 } 074 } catch (IOException e) { 075 throw new InternalErrorException("Unable to buffer the entity for capturing", e); 076 } 077 078 079 myLastResponse = theResponse; 080 } 081 082}