testable version of {@link ElasticSearchSchemaService#extractResponse(Response)}
@param statusCode
@param entity
@return
779258
@VisibleForTesting
	static String doExtractResponse(int statusCode, HttpEntity entity) {
		String message = null;

		if (entity != null) {
			try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
				entity.writeTo(baos);
				message = baos.toString("UTF-8");
			}
			catch (IOException ex) {
				throw new SystemException(ex);
			}
		}

		//if the response is in the 400 range, use IllegalArgumentException, which currently translates to a 400 error
		if (statusCode>= HttpStatus.SC_BAD_REQUEST && statusCode < HttpStatus.SC_INTERNAL_SERVER_ERROR) {
			throw new IllegalArgumentException("Status code: " + statusCode + " .  Error occurred. " +  message);
		}
		//everything else that's not in the 200 range, use SystemException, which translates to a 500 error.
		if ((statusCode < HttpStatus.SC_OK) || (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES)) {
			throw new SystemException("Status code: " + statusCode + " .  Error occurred. " +  message);
		} else {
			return message;
		}
	}
186400
protected function readResponse($statusCode, $responseBody)
    {
        $unserialized = null;

        switch ($statusCode) {
            case 200:
            case 201:
                $unserialized = $this->unserialize($responseBody);
                break;
            case 400:
                $exception = null;
                $response  = json_decode($responseBody);

                foreach ($response as $error) {
                    $cieloError = new CieloError($error->Message, $error->Code);
                    $exception  = new CieloRequestException('Request Error', $statusCode, $exception);
                    $exception->setCieloError($cieloError);
                }

                throw $exception;
            case 404:
                throw new CieloRequestException('Resource not found', 404, null);
            default:
                throw new CieloRequestException('Unknown status', $statusCode);
        }

        return $unserialized;
    }
93096
public static ResponseStatus fromHttp(final int code) {
        ResponseStatus status;
        switch (code) {
            case HTTP_OK:
            case HTTP_CREATED:
            case HTTP_ACCEPTED:
                status = ResponseStatus.SUCCESS;
                break;
            case HTTP_NOT_FOUND:
                status = ResponseStatus.NOT_EXISTS;
                break;
            case HTTP_BAD_REQUEST:
                status = ResponseStatus.INVALID_ARGUMENTS;
                break;
            case HTTP_INTERNAL_ERROR:
                status = ResponseStatus.INTERNAL_ERROR;
                break;
            case HTTP_UNAUTHORIZED:
                status = ResponseStatus.ACCESS_ERROR;
                break;
            case HTTP_TOO_MANY_REQUESTS:
                status = ResponseStatus.FAILURE;
                break;
            default:
                LOGGER.warn("Unknown ResponseStatus with Protocol HTTP: {}", code);
                status = ResponseStatus.FAILURE;
        }
        return status;
    }
244798
private int getStatusCode(final byte[] response, final int request) throws UnknownResponseException {
		if (response == null || response.length < 3 || response[0] != OP_CODE_RESPONSE_CODE_KEY || response[1] != request ||
				(response[2] != DFU_STATUS_SUCCESS &&
						response[2] != SecureDfuError.OP_CODE_NOT_SUPPORTED &&
						response[2] != SecureDfuError.INVALID_PARAM &&
						response[2] != SecureDfuError.INSUFFICIENT_RESOURCES &&
						response[2] != SecureDfuError.INVALID_OBJECT &&
						response[2] != SecureDfuError.UNSUPPORTED_TYPE &&
						response[2] != SecureDfuError.OPERATION_NOT_PERMITTED &&
						response[2] != SecureDfuError.OPERATION_FAILED &&
						response[2] != SecureDfuError.EXTENDED_ERROR))
			throw new UnknownResponseException("Invalid response received", response, OP_CODE_RESPONSE_CODE_KEY, request);
		return response[2];
	}
702645
@RequestMapping(produces = HttpHeaders.JSONAPI_CONTENT_TYPE)
	@ResponseBody
	public ResponseEntity<Document> errorToJsonApi(HttpServletRequest request) {
		Map<String, Object> body = getErrorAttributes(request,
				isIncludeStackTrace(request, MediaType.ALL));
		HttpStatus status = getStatus(request);

		ErrorDataBuilder errorDataBuilder = ErrorData.builder();
		for (Map.Entry<String, Object> attribute : body.entrySet()) {
			if (attribute.getKey().equals("status")) {
				errorDataBuilder.setStatus(attribute.getValue().toString());
			} else if (attribute.getKey().equals("error")) {
				errorDataBuilder.setTitle(attribute.getValue().toString());
			} else if (attribute.getKey().equals("message")) {
				errorDataBuilder.setDetail(attribute.getValue().toString());
			} else {
				errorDataBuilder.addMetaField(attribute.getKey(), attribute.getValue());
			}
		}
		Document document = new Document();
		document.setErrors(Arrays.asList(errorDataBuilder.build()));
		return new ResponseEntity<>(document, status);
	}
912588
private <R extends J4pResponse<T>, T extends J4pRequest> List<R> extractResponses(JSONAware pJsonResponse,
                                                                                      List<T> pRequests,
                                                                                      J4pResponseExtractor pResponseExtractor) throws J4pException {
        JSONArray responseArray = (JSONArray) pJsonResponse;
        List<R> ret = new ArrayList<R>(responseArray.size());
        J4pRemoteException remoteExceptions[] = new J4pRemoteException[responseArray.size()];
        boolean exceptionFound = false;
        for (int i = 0; i < pRequests.size(); i++) {
            T request = pRequests.get(i);
            Object jsonResp = responseArray.get(i);
            if (!(jsonResp instanceof JSONObject)) {
                throw new J4pException("Response for request Nr. " + i + " is invalid (expected a map but got " + jsonResp.getClass() + ")");
            }
            try {
                ret.add(i,pResponseExtractor.<R,T>extract(request, (JSONObject) jsonResp));
            } catch (J4pRemoteException exp) {
                remoteExceptions[i] = exp;
                exceptionFound = true;
                ret.add(i,null);
            }
        }
        if (exceptionFound) {
            List partialResults = new ArrayList();
            // Merge partial results and exceptions in a single list
            for (int i = 0;i<pRequests.size();i++) {
                J4pRemoteException exp = remoteExceptions[i];
                if (exp != null) {
                    partialResults.add(exp);
                } else {
                    partialResults.add(ret.get(i));
                }
            }
            throw new J4pBulkRemoteException(partialResults);
        }
        return ret;
    }
1188672
@SuppressWarnings("unchecked")
    private <T extends IEntity> T retrieveEntity(IntuitMessage intuitMessage) {
        T returnEntity = null;
        IntuitResponse intuitResponse = (IntuitResponse) intuitMessage.getResponseElements().getResponse();
        if (intuitResponse != null) {
            JAXBElement<? extends IntuitEntity> intuitObject = intuitResponse.getIntuitObject();
            if (intuitObject != null) {
                returnEntity = ((T) intuitObject.getValue());
            }
        }
        return returnEntity;
    }
151942
public static <T> GenericResponseBuilder<T> accepted(T entity) {
    return genericResponseBuilderFactory.create(Response.Status.ACCEPTED.getStatusCode(), entity);
  }
588026
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<E> findById(@PathVariable Integer id) {

        try {
            E entity = this.service.findById(id);
            LOG.trace("Found " + entity.getClass().getSimpleName()
                + " with ID " + entity.getId());
            return new ResponseEntity<E>(entity, HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("Error finding entity with id " + id + ": "
                + e.getMessage());
            return new ResponseEntity<E>(HttpStatus.NOT_FOUND);
        }
    }
200967
public static ResponseEntity<String> createResponseEntityForAuthnFailure(final AuthenticationException e,
                                                                             final HttpServletRequest request,
                                                                             final ApplicationContext applicationContext) {
        try {
            val authnExceptions = e.getHandlerErrors().values()
                .stream()
                .map(ex -> mapExceptionToMessage(e, request, applicationContext, ex))
                .collect(Collectors.toList());
            val errorsMap = new HashMap<String, List<String>>();
            errorsMap.put("authentication_exceptions", authnExceptions);
            LOGGER.warn("[{}] Caused by: [{}]", e.getMessage(), authnExceptions);

            return new ResponseEntity<>(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(errorsMap), HttpStatus.UNAUTHORIZED);
        } catch (final JsonProcessingException exception) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
562643
@RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<E> save(HttpServletRequest request) {

        final String simpleClassName = getEntityClass().getSimpleName();
        final String errorMessagePrefix = "Error when saving entity of type "
            + simpleClassName + ": ";

        BufferedReader reader = null;
        // read and parse the json request body
        try {
            reader = request.getReader();

            E entity = objectMapper.readValue(reader, getEntityClass());

            // ID value MUST be null to assure that
            // saveOrUpdate will save and not update
            final Integer id = entity.getId();
            if (id != null) {
                LOG.error(errorMessagePrefix + "ID value is set to " + id
                    + ", but MUST be null");
                return new ResponseEntity<E>(HttpStatus.BAD_REQUEST);
            }

            this.service.saveOrUpdate(entity);
            LOG.trace("Created " + simpleClassName + " with ID " + entity.getId());
            return new ResponseEntity<E>(entity, HttpStatus.CREATED);
        } catch (Exception e) {
            LOG.error(errorMessagePrefix + e.getMessage());
            return new ResponseEntity<E>(HttpStatus.BAD_REQUEST);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }
1104552
private <T> T send(String method, Class<T> responseType, @Nullable Object entity) {
        // Narrow the response type
        if (responseType == EmoResponse.class) {
            // noinspection unchecked
            return (T) toEmoResponse(entity == null ?
                    builder().method(method, ClientResponse.class) :
                    builder().method(method, ClientResponse.class, entity));
        }

        try {
            ClientResponse response = entity == null ?
                    builder().method(method, ClientResponse.class) :
                    builder().method(method, ClientResponse.class, entity);

            // This is as per Jersey's WebResource builder() code.
            if (response.getStatus() >= 300) {
                throw new UniformInterfaceException(response);
            }

            if (!response.getType().equals(MediaType.APPLICATION_JSON_TYPE)) {
                return response.getEntity(responseType);
            }
            return EntityHelper.getEntity(response.getEntity(InputStream.class), responseType);
        } catch (UniformInterfaceException e) {
            throw asEmoClientException(e);
        }
    }
1085508
public static String getResponseContent(HttpResponse response) throws IOException {
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                entity.writeTo(out);//call this in any case!!!
                return isScOk(response) ? new String(out.toByteArray(), Charset.forName("UTF-8")) : null;
            } finally {
                //ensure entity is closed.
                EntityUtils.consume(entity);
            }
        } else {
            return null;
        }
    }
533406
public ApiResponse createEntity(Entity entity) {
        assertValidApplicationId();
        if (isEmpty(entity.getType())) {
            throw new IllegalArgumentException("Missing entity type");
        }
        ApiResponse response = apiRequest(HttpMethod.POST, null, entity,
                organizationId, applicationId, entity.getType());
        return response;
    }
647102
protected Response createOk(Object entity) {
    return Response
      .status(Response.Status.OK)
      .entity(entity)
      .build();
  }
1180006
public static void makeStringResponse(HttpResponse response, String s) {
        StringEntity entity = new StringEntity(s, ContentType.TEXT_PLAIN);
        entity.setContentEncoding("utf-8");
        response.setEntity(entity);
    }
210012
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
		PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
		byte[] buffer = null;
		try {
			InputStream in = entity.getContent();
			if (in == null) {
				throw new ServerError();
			}
			buffer = mPool.getBuf(1024);
			int count;
			while ((count = in.read(buffer)) != -1) {
				bytes.write(buffer, 0, count);
			}
			return bytes.toByteArray();
		} finally {
			try {
				// Close the InputStream and release the resources by "consuming the content".
				entity.consumeContent();
			} catch (IOException e) {
				// This can happen if there was an exception above that left the entity in
				// an invalid state.
				VolleyLog.v("Error occured when calling consumingContent");
			}
			mPool.returnBuf(buffer);
			bytes.close();
		}
	}