Checks for a valid response code and throws and exception with the response code if an error

@param connection
@throws RepositoryHttpException
@throws IOException
326304
private static void checkHttpResponseCodeValid(URLConnection connection) throws RepositoryHttpException, IOException {
        // if HTTP URL not File URL
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) connection;
            conn.setRequestMethod("GET");
            int respCode = conn.getResponseCode();
            if (respCode < 200 || respCode >= 300) {
                throw new RepositoryHttpException("HTTP connection returned error code " + respCode, respCode, null);
            }
        }
    }
252435
public static void throwExceptionOnError(ResponseEntity<?> response) {
		if (!response.getStatusCode().equals(HttpStatus.OK)) {
			throw new CredHubException(response.getStatusCode());
		}
	}
127150
private byte[] readResponse(URLConnection connection) throws RpcException {
        byte[] resBytes;
        InputStream in = null;
        HttpURLConnection httpconnection = (HttpURLConnection) connection;
        try {
            if (httpconnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                in = httpconnection.getInputStream();
            } else {
                if (httpconnection.getContentType()
                        .equals(serializeHandler.getProtocol().getName())
                        && httpconnection.getErrorStream() != null) {
                    in = httpconnection.getErrorStream();
                } else {
                    in = httpconnection.getInputStream();
                }
            }
            int len = httpconnection.getContentLength();
            if (len <= 0) {
                throw new RpcException("Response data length should not be zero");
            }
            resBytes = ByteUtil.readStream(in, len);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Read " + resBytes.length + " bytes response done");
            }
        } catch (IOException e) {
            throw new RpcException("Rpc read response from server has IO problems - "
                    + e.getMessage(), e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOG.error("Close read response connection error");
                }
            }
        }
        return resBytes;
    }
1063880
protected void handleExceptionIfNeeded(HttpResponse response) throws GloboDnsException, IOException {
		int statusCode = response.getStatusCode();
		if (statusCode/100 == 2) {
			// 200 family code
			// Successful return, do nothing
			return;
		} else if (statusCode/100 == 4 || statusCode/100 == 5) {
			// 400 and 500 family codes
			// Something was wrong, produce an error result
			String responseAsString = response.parseAsString();
			if (responseAsString == null || !responseAsString.startsWith("{")) {
				// Response not well formed!
				throw new GloboDnsHttpException("Unknown error in GloboDNS: " + responseAsString, statusCode);
			}
			
			GloboDnsRoot<ErrorMessage> responseObj = this.parse(responseAsString, ErrorMessage.class);
			ErrorMessage errorMsg = responseObj.getFirstObject();
			if (errorMsg != null && errorMsg.getMsg() != null) {
				throw new GloboDnsHttpException(errorMsg.getMsg(), statusCode);
			} else {
				throw new GloboDnsHttpException(responseAsString, statusCode);
			}
		} else {
			// Unknown error code, return generic exception with description
			throw new GloboDnsHttpException(response.parseAsString(), statusCode);
		}
	}
583486
public void sendError(int code,String message) 
        throws IOException
    {        
        setStatus(code,message);
        
        // Generate normal error page.
        HttpRequest request=getHttpRequest();
        
        // If we are allowed to have a body 
        if (code!=__204_No_Content &&
            code!=__304_Not_Modified &&
            code!=__206_Partial_Content &&
            code>=200)
        {
            if (getHttpContext()!=null)
            {   
                Object o=
                    getHttpContext().getAttribute(HttpContext.__ErrorHandler);
                if (o!=null && o instanceof HttpHandler)
                    ((HttpHandler)o).handle(request.getPath(), null, request, this);
            }
        }
        else if (code!=__206_Partial_Content) 
        {
            _header.remove(HttpFields.__ContentType);
            _header.remove(HttpFields.__ContentLength);
            _characterEncoding=null;
            _mimeType=null;
        }
        
        commit();
    }
1244259
private void checkResponseCode(String message) throws ResponseException {

        if (this.responseCode != 200 && this.responseCode != 204) {

            HashMap<Integer, String> responseCodes = new HashMap<Integer, String>() {{
                put(206, "PartialContent");
                put(400, "Bad request");
                put(401, "Unauthorized");
                put(403, "Prohibition to use the method");
                put(404, "Not found");
                put(405, "Method not allowed");
                put(413, "Request entity too large");
                put(422, "Unprocessable entity");
                put(500, "Internal server error");
                put(501, "Not implemented");
            }};

            ResponseException responseException = new ResponseException(message);
            responseException.setResponseHttpCode(this.responseCode);

            if (responseCodes.containsKey(this.responseCode)) {
                responseException.setResponseHttpDescription(responseCodes.get(this.responseCode));
            } else {
                responseException.setResponseHttpDescription("Unknown response error");
            }

            if (message != null) {
                JsonObject error = new JsonParser().parse(message).getAsJsonObject();
                for (Entry<String, JsonElement> entry : error.entrySet()) {

                    switch (entry.getKey().toLowerCase()) {
                        case "message":
                            responseException.setApiMessage(entry.getValue().getAsString());
                            break;
                        case "type":
                            responseException.setType(entry.getValue().getAsString());
                            break;
                        case "id":
                            responseException.setId(entry.getValue().getAsString());
                            break;
                        case "date":
                            responseException.setDate((int) entry.getValue().getAsDouble());
                            break;
                        case "errors":
                            if (entry.getValue() == null) break;

                            if (entry.getValue().isJsonNull()) break;

                            for (Entry<String, JsonElement> errorEntry : entry.getValue().getAsJsonObject().entrySet()) {
                                if (!responseException.getErrors().containsKey(errorEntry.getKey()))
                                    responseException.getErrors().put(errorEntry.getKey(), errorEntry.getValue().getAsString());
                                else {
                                    String description = responseException.getErrors().get(errorEntry.getKey());
                                    description = " | " + errorEntry.getValue().getAsString();

                                    responseException.getErrors().put(errorEntry.getKey(), description);
                                }
                            }
                            break;
                    }
                }
            }

            throw responseException;
        }
    }
713479
def _validate_response(self, method, response):
        '''  '''
        # TODO Fill this out using the error codes here: https://developer.wunderlist.com/documentation/concepts/formats
        # The expected results can change based on API version, so validate this here
        if self.api_version:
            if response.status_code >= 400:
                raise ValueError('{} {}'.format(response.status_code, str(response.json())))
            if method == 'GET':
                assert response.status_code == 200
            elif method == 'POST':
                assert response.status_code == 201
            elif method == 'PATCH':
                assert response.status_code == 200
            elif method == 'DELETE':
                assert response.status_code == 204
537653
public static void bailResponse(HttpContext cx, HttpResponse response) throws IOException, HttpException {
        HttpServerConnection conn = getConnection(cx);
        conn.sendResponseHeader(response);
        conn.sendResponseEntity(response);
        conn.flush();
    }
584814
void connectionError(final SibRaMessagingEngineConnection connection,
            final SIException exception) {

        final String methodName = "connectionError";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName, new Object[] { connection,
                    exception });
        }

        /*
         * Close the connection - any future work will attempt to create a new
         * connection
         */

        closeConnection(connection.getConnection().getMeUuid(), true);

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, methodName);
        }

    }
1211380
private void handleQueries(
      final HttpServletResponse response,
      final Map<String, List<String>> queries,
      final String version) throws IOException {

    LOG.log(Level.INFO, "HttpServerReefEventHandler handleQueries is called");

    for (final Map.Entry<String, List<String>> entry : queries.entrySet()) {
      final String queryTarget = entry.getKey().toLowerCase();

      switch (queryTarget) {
      case "id":
        if (version.equals(VER)) {
          writeEvaluatorInfoJsonOutput(response, entry.getValue());
        } else {
          writeEvaluatorInfoWebOutput(response, entry.getValue());
        }
        break;
      default:
        response.getWriter().println("Unsupported query : " + queryTarget);
        break;
      }
    }
  }
780690
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.debug("Handling HttpServletRequest {}", request);
		response.setContentType(contentType);
		OutputStream output = response.getOutputStream();
		InputStream input = getRequestStream(request);
		int result = ErrorResolver.JsonError.PARSE_ERROR.code;
		int contentLength = 0;
		ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
		try {
			String acceptEncoding = request.getHeader(ACCEPT_ENCODING);
			result = handleRequest0(input, output, acceptEncoding, response, byteOutput);

			contentLength = byteOutput.size();
		} catch (Throwable t) {
			if (StreamEndedException.class.isInstance(t)) {
				logger.debug("Bad request: empty contents!");
			} else {
				logger.error(t.getMessage(), t);
			}
		}
		int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result)
				: httpStatusCodeProvider.getHttpStatusCode(result);
		response.setStatus(httpStatusCode);
		response.setContentLength(contentLength);
		byteOutput.writeTo(output);
		output.flush();
	}
111495
public void handleException(Throwable throwable) {
        log.debug("Handle exception: {} with: {}", throwable.getMessage(), exceptionHandler);
        if (exceptionHandler != null) {
            exceptionHandler.handleException(throwable);
        } else {
            log.error("Connection exception", throwable);
            throw new RuntimeException(throwable);
        }
    }
552535
private void validateContract(final Contract contract, Connection connection)
            throws RegistrationException {
        QueryRunner run = new QueryRunner();
        try {
            Api api = run.query(connection, "SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$
                    Handlers.API_HANDLER, contract.getApiOrgId(), contract.getApiId(), contract.getApiVersion());
            if (api == null) {
                String apiId = contract.getApiId();
                String orgId = contract.getApiOrgId();
                throw new ApiNotFoundException(Messages.i18n.format("JdbcRegistry.ApiNotFoundInOrg", apiId, orgId));  //$NON-NLS-1$
            }
        } catch (SQLException e) {
            throw new RegistrationException(Messages.i18n.format("JdbcRegistry.ErrorValidatingApp"), e); //$NON-NLS-1$
        }
    }
912156
private static void ensureStatusOk(HttpResponse<String> response) throws ClientErrorException,
            ServerErrorException, OtherCommunicationException {
        int responseStatus = response.getStatus();
        if (isClientError(responseStatus)) {
            throw new ClientErrorException(response.getBody());
        } else if (isServerError(responseStatus)) {
            throw new ServerErrorException();
        } else if (isOtherErrorResponse(responseStatus)) {
            throw new OtherCommunicationException();
        }
    }
475108
public static String buildHttpErrorMessage(final HttpURLConnection connection) throws IOException {
        final StringBuilder messageBuilder = new StringBuilder("(").append(connection.getResponseCode()).append(")");
        if (connection.getResponseMessage() != null) {
            messageBuilder.append(" ");
            messageBuilder.append(connection.getResponseMessage());
        }
        try (final InputStreamReader isr = new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8);
             BufferedReader br = new BufferedReader(isr)){
            String output;
            messageBuilder.append("[");
            while ((output = br.readLine()) != null) {
                messageBuilder.append(output);
            }
            messageBuilder.append("]");
        }finally {
            connection.disconnect();
        }
        return messageBuilder.toString();
    }
953060
protected static void error(
            final HttpServletResponse httpServletResponse, final String message, final HttpStatus code) {
        try {
            httpServletResponse.setContentType("text/plain");
            httpServletResponse.setStatus(code.value());
            setNoCache(httpServletResponse);
            try (PrintWriter out = httpServletResponse.getWriter()) {
                out.println("Error while processing request:");
                out.println(message);
            }

            LOGGER.error("Error while processing request: {}", message);
        } catch (IOException ex) {
            throw ExceptionUtils.getRuntimeException(ex);
        }
    }
861049
private final void handleHttpWorkerResponse(
            ResponseOnSingeRequest respOnSingleReq) throws Exception {
        // Successful response from GenericAsyncHttpWorker

        // Jeff 20310411: use generic response

        String responseContent = respOnSingleReq.getResponseBody();
        response.setResponseContent(respOnSingleReq.getResponseBody());

        /**
         * Poller logic if pollable: check if need to poll/ or already complete
         * 1. init poller data and HttpPollerProcessor 2. check if task
         * complete, if not, send the request again.
         */
        if (request.isPollable()) {
            boolean scheduleNextPoll = false;
            boolean errorFindingUuid = false;

            // set JobId of the poller
            if (!pollerData.isUuidHasBeenSet()) {
                String jobId = httpPollerProcessor
                        .getUuidFromResponse(respOnSingleReq);

                if (jobId.equalsIgnoreCase(PcConstants.NA)) {
                    errorFindingUuid = true;
                    pollingErrorCount++;
                    logger.error("!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. "

                            + "DEBUG: REGEX_JOBID: "
                            + httpPollerProcessor.getJobIdRegex()

                            + "RESPONSE: "
                            + respOnSingleReq.getResponseBody()
                            + " polling Error count"
                            + pollingErrorCount
                            + " at " + PcDateUtils.getNowDateTimeStrStandard());
                    // fail fast
                    pollerData.setError(true);
                    pollerData.setComplete(true);

                } else {
                    pollerData.setJobIdAndMarkHasBeenSet(jobId);
                    // if myResponse has other errors, mark poll data as error.
                    pollerData.setError(httpPollerProcessor
                            .ifThereIsErrorInResponse(respOnSingleReq));
                }

            }
            if (!pollerData.isError()) {

                pollerData
                        .setComplete(httpPollerProcessor
                                .ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));
                pollerData.setCurrentProgress(httpPollerProcessor
                        .getProgressFromResponse(respOnSingleReq));
            }

            // poll again only if not complete AND no error; 2015: change to
            // over limit
            scheduleNextPoll = !pollerData.isComplete()
                    && (pollingErrorCount <= httpPollerProcessor
                            .getMaxPollError());

            // Schedule next poll and return. (not to answer back to manager yet
            // )
            if (scheduleNextPoll
                    && (pollingErrorCount <= httpPollerProcessor
                            .getMaxPollError())) {

                pollMessageCancellable = getContext()
                        .system()
                        .scheduler()
                        .scheduleOnce(
                                Duration.create(httpPollerProcessor
                                        .getPollIntervalMillis(),
                                        TimeUnit.MILLISECONDS), getSelf(),
                                OperationWorkerMsgType.POLL_PROGRESS,
                                getContext().system().dispatcher(), getSelf());

                logger.info("\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND"
                        + String.format("PROGRESS:%.3f, BODY:%s ",
                                pollerData.getCurrentProgress(),
                                responseContent,
                                PcDateUtils.getNowDateTimeStrStandard()));

                String responseContentNew = errorFindingUuid ? responseContent
                        + "_PollingErrorCount:" + pollingErrorCount
                        : responseContent;
                logger.info(responseContentNew);
                // log
                pollerData.getPollingHistoryMap().put(
                        "RECV_" + PcDateUtils.getNowDateTimeStrConciseNoZone(),
                        String.format("PROGRESS:%.3f, BODY:%s",
                                pollerData.getCurrentProgress(),
                                responseContent));
                return;
            } else {
                pollerData
                        .getPollingHistoryMap()
                        .put("RECV_"
                                + PcDateUtils.getNowDateTimeStrConciseNoZone(),
                                String.format(
                                        "POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s ",
                                        pollerData.getCurrentProgress(),
                                        responseContent));
            }

        }// end if (request.isPollable())

        reply(respOnSingleReq.isFailObtainResponse(),
                respOnSingleReq.getErrorMessage(),
                respOnSingleReq.getStackTrace(),
                respOnSingleReq.getStatusCode(),
                respOnSingleReq.getStatusCodeInt(),
                respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());

    }