View Javadoc
1   package ca.uhn.fhir.rest.client.exceptions;
2   
3   /*
4    * #%L
5    * HAPI FHIR - Core Library
6    * %%
7    * Copyright (C) 2014 - 2019 University Health Network
8    * %%
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   * 
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   * 
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   * #L%
21   */
22  
23  import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;
24  import ca.uhn.fhir.util.CoverageIgnore;
25  import com.google.common.base.Charsets;
26  import org.apache.commons.io.IOUtils;
27  
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.io.InputStreamReader;
31  import java.io.Reader;
32  
33  import static org.apache.commons.lang3.StringUtils.isBlank;
34  
35  @CoverageIgnore
36  public class NonFhirResponseException extends BaseServerResponseException {
37  
38  	private static final long serialVersionUID = 1L;
39  
40  	/**
41  	 * Constructor
42  	 *
43  	 * @param theMessage    The message
44  	 * @param theStatusCode The HTTP status code
45  	 */
46  	NonFhirResponseException(int theStatusCode, String theMessage) {
47  		super(theStatusCode, theMessage);
48  	}
49  
50  	public static NonFhirResponseException newInstance(int theStatusCode, String theContentType, InputStream theInputStream) {
51  		return newInstance(theStatusCode, theContentType, new InputStreamReader(theInputStream, Charsets.UTF_8));
52  	}
53  
54  	public static NonFhirResponseException newInstance(int theStatusCode, String theContentType, Reader theReader) {
55  		String responseBody = "";
56  		try {
57  			responseBody = IOUtils.toString(theReader);
58  		} catch (IOException e) {
59  			// ignore
60  		} finally {
61  			try {
62  				theReader.close();
63  			} catch (IOException theE) {
64  				// ignore
65  			}
66  		}
67  
68  		NonFhirResponseException retVal;
69  		if (isBlank(theContentType)) {
70  			retVal = new NonFhirResponseException(theStatusCode, "Response contains no Content-Type");
71  		} else if (theContentType.contains("text")) {
72  			retVal = new NonFhirResponseException(theStatusCode, "Response contains non FHIR Content-Type '" + theContentType + "' : " + responseBody);
73  		} else {
74  			retVal = new NonFhirResponseException(theStatusCode, "Response contains non FHIR Content-Type '" + theContentType + "'");
75  		}
76  
77  		retVal.setResponseBody(responseBody);
78  		return retVal;
79  	}
80  
81  }