001package ca.uhn.fhir.rest.client.exceptions; 002 003/* 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2022 Smile CDR, Inc. 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.server.exceptions.BaseServerResponseException; 024import ca.uhn.fhir.util.CoverageIgnore; 025import com.google.common.base.Charsets; 026import org.apache.commons.io.IOUtils; 027 028import java.io.IOException; 029import java.io.InputStream; 030import java.io.InputStreamReader; 031import java.io.Reader; 032 033import static org.apache.commons.lang3.StringUtils.isBlank; 034 035@CoverageIgnore 036public class NonFhirResponseException extends BaseServerResponseException { 037 038 private static final long serialVersionUID = 1L; 039 040 /** 041 * Constructor 042 * 043 * @param theMessage The message 044 * @param theStatusCode The HTTP status code 045 */ 046 NonFhirResponseException(int theStatusCode, String theMessage) { 047 super(theStatusCode, theMessage); 048 } 049 050 public static NonFhirResponseException newInstance(int theStatusCode, String theContentType, InputStream theInputStream) { 051 return newInstance(theStatusCode, theContentType, new InputStreamReader(theInputStream, Charsets.UTF_8)); 052 } 053 054 public static NonFhirResponseException newInstance(int theStatusCode, String theContentType, Reader theReader) { 055 String responseBody = ""; 056 try { 057 responseBody = IOUtils.toString(theReader); 058 } catch (IOException e) { 059 // ignore 060 } finally { 061 try { 062 theReader.close(); 063 } catch (IOException theE) { 064 // ignore 065 } 066 } 067 068 NonFhirResponseException retVal; 069 if (isBlank(theContentType)) { 070 retVal = new NonFhirResponseException(theStatusCode, "Response contains no Content-Type"); 071 } else if (theContentType.contains("text")) { 072 retVal = new NonFhirResponseException(theStatusCode, "Response contains non FHIR Content-Type '" + theContentType + "' : " + responseBody); 073 } else { 074 retVal = new NonFhirResponseException(theStatusCode, "Response contains non FHIR Content-Type '" + theContentType + "'"); 075 } 076 077 retVal.setResponseBody(responseBody); 078 return retVal; 079 } 080 081}