/*
(non-Javadoc)

@see
com.emc.ecs.nfsclient.rpc.RpcResponseHandler#checkResponse(com.emc.ecs.
nfsclient.rpc.RpcRequest)
490271
public void checkResponse(RpcRequest request) throws IOException {
        if (getResponse().getRejectStatus() == RejectStatus.AUTH_ERROR.getValue()) {
            request.setUsePrivilegedPort(true);
        }
        if (getResponse().getState() != NfsStatus.NFS3_OK.getValue()) {
            int responseState = getResponse().getState();
            if (responseState == NfsStatus.NFS3ERR_NOENT.getValue()) {
                throw new FileNotFoundException(request.getErrorMessage());
            }
            NfsStatus status = NfsStatus.fromValue(responseState);
            throw new NfsException(status, request.getErrorMessage() + " error code:" + status.toString());
        }
    }
920890
private boolean responseIsInValid() {
        if (response == null) {
            return true;
        }
        else if (!response.isHeadless() && validityCheck) {
            return request.getTransactionID() != response.getTransactionID();
        }
        else {
            return false;
        }
    }
542898
public boolean waitForResponse ()
        throws TimeoutException
    {
        if (_success == 0) {
            synchronized (this) {
                try {
                    // wait for the response, timing out after a while
                    if (_timeout == NO_TIMEOUT) {
                        wait();

                    } else {
                        wait(1000L * _timeout);
                    }
                    // if we get here without some sort of response, then we've timed out
                    if (_success == 0) {
                        throw new TimeoutException();
                    }

                } catch (InterruptedException ie) {
                    throw (TimeoutException)
                        new TimeoutException().initCause(ie);
                }
            }
        }

        return (_success > 0);
    }
436764
private boolean checkAndRespond(Request request) {
        if (!URIBean.checkUri(request.getUrl())) {
            ServerResponseBean responseBean = new ServerResponseBean();
            responseBean.setMsgId(request.getMsgId());
            responseBean.setHttpContentType(HttpContentType.APPLICATION_JSON);
            responseBean.setResponseBody(UnitResponse.createError(Group.CODE_BAD_REQUEST, null, String.format("URI %s is illegal.", request.getUrl()))
                    .toVoJSONString());
            IServerResponder.singleton.response(responseBean);
            return false;
        }
        return true;
    }
424534
public static DeleteRequest checkRequest(final HttpServletRequest request,
			final DeleteResponse deleteResponse) {
		final DeleteRequestType type = checkType(request, deleteResponse);
		if (type != null) {
			return new DeleteRequest(type);
		}

		return null;
	}
780945
synchronized public void check() {
		if(lastCheckpoint < 0) {
			lastCheckpoint = System.currentTimeMillis();
		}
		
		requests++;
		long interval = System.currentTimeMillis() - lastCheckpoint;
		if(requests >= maxRequests) {
			try {
				long sleepTime = minInterval - interval;
				if(sleepTime > 0) {
					logger.info("Request limit reached. Wait for " + sleepTime/1000 + " seconds");
					Thread.sleep(sleepTime);
				}
			} catch (InterruptedException e) {
				logger.error(e.getMessage());
				return;
			}
			finally {
				requests = 0;
				lastCheckpoint = System.currentTimeMillis();
			}
		}
		else if(interval > minInterval) {
			requests = 0;
			lastCheckpoint = System.currentTimeMillis();
		}
	}
739959
@Override
	public void receiveResponse(Tree message) {

		// Verify protocol version
		if (checkVersion) {
			String ver = message.get("ver", "unknown");
			if (!PROTOCOL_VERSION.equals(ver)) {
				logger.warn("Invalid protocol version (" + ver + ")!");
				return;
			}
		}

		// Get response's unique ID
		String id = message.get("id", (String) null);
		if (id == null || id.isEmpty()) {
			logger.warn("Missing \"id\" property!", message);
			return;
		}

		// Incoming (response) stream handling
		IncomingStream responseStream;
		responseStreamReadLock.lock();
		try {
			responseStream = responseStreams.get(id);
		} finally {
			responseStreamReadLock.unlock();
		}
		if (responseStream != null) {
			boolean remove = false;
			try {
				if (responseStream.receive(message)) {
					remove = true;
				}
			} catch (Throwable error) {
				remove = true;

				// Write error to log file
				if (writeErrorsToLog) {
					logger.error("Unexpected error occurred while streaming!", error);
				}
			}
			if (remove) {
				responseStreamWriteLock.lock();
				try {
					responseStreams.remove(id);
				} finally {
					responseStreamWriteLock.unlock();
				}
			}
			return;
		}
		if (message.get("stream", false)) {
			responseStreamWriteLock.lock();
			try {
				responseStream = responseStreams.get(id);
				if (responseStream == null) {
					responseStream = new IncomingStream(nodeID, scheduler, streamTimeout);
					responseStreams.put(id, responseStream);
				}
			} finally {
				responseStreamWriteLock.unlock();
			}
			if (responseStream.receive(message)) {
				responseStreamWriteLock.lock();
				try {
					responseStreams.remove(id);
				} finally {
					responseStreamWriteLock.unlock();
				}
			}
			message.putObject("data", responseStream.getPacketStream());
		}

		// Get stored promise
		PendingPromise pending = promises.remove(id);
		if (pending == null) {
			logger.warn("Unknown (maybe timeouted) response received!", message);
			return;
		}
		try {

			// Get response status (successed or not?)
			boolean success = message.get("success", true);
			if (success) {

				// Ok -> resolve
				pending.promise.complete(message.get("data"));

			} else {

				// Failed -> reject
				Tree error = message.get("error");
				MoleculerError moleculerError;
				if (error == null) {
					moleculerError = new MoleculerError("Remote invocation failed!", null, "MoleculerError",
							pending.nodeID, false, 500, "UNKNOWN_ERROR", message);
				} else {
					moleculerError = MoleculerErrorUtils.create(error);
				}

				pending.promise.complete(moleculerError);
				logger.error(moleculerError.getMessage(), moleculerError);

				return;
			}
		} catch (Throwable cause) {
			logger.error("Unable to pass on incoming response!", cause);
		}
	}
1328510
private Message handleMessageAndCheckResponse(Message request) throws JdbcServerException {
        Message response = handleMessage(request);
        checkSuccess(response);
        return response;
    }
1312028
private synchronized void awaitResponse() throws BOSHException {
        HttpEntity entity = null;
        try {
            HttpResponse httpResp = client.execute(post, context);
            entity = httpResp.getEntity();
            byte[] data = EntityUtils.toByteArray(entity);
            String encoding = entity.getContentEncoding() != null ?
                    entity.getContentEncoding().getValue() :
                    null;
            if (ZLIBCodec.getID().equalsIgnoreCase(encoding)) {
                data = ZLIBCodec.decode(data);
            } else if (GZIPCodec.getID().equalsIgnoreCase(encoding)) {
                data = GZIPCodec.decode(data);
            }
            body = StaticBody.fromString(new String(data, CHARSET));
            statusCode = httpResp.getStatusLine().getStatusCode();
            sent = true;
        } catch (IOException iox) {
            abort();
            toThrow = new BOSHException("Could not obtain response", iox);
            throw(toThrow);
        } catch (RuntimeException ex) {
            abort();
            throw(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());

    }
1285390
def _check_response(response, expected):
        

        response_code = response.status_code
        if expected == response_code:
            return

        if response_code < 400:
            raise ex.UnexpectedResponseCodeException(response.text)

        elif response_code == 401:
            raise ex.UnauthorizedException(response.text)

        elif response_code == 400:
            raise ex.BadRequestException(response.text)

        elif response_code == 403:
            raise ex.ForbiddenException(response.text)

        elif response_code == 404:
            raise ex.NotFoundException(response.text)

        elif response_code == 429:
            raise ex.RateLimitedException(response.text)

        else:
            raise ex.InternalServerErrorException(response.text)
148099
public static boolean isScOk(HttpResponse response) {
        return response != null && response.getStatusLine()!= null &&
                response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    }
50930
@SuppressWarnings("unchecked")
    public void receiveResponse(Object response_value, Address sender, boolean is_exception) {
        Rsp<T> rsp;
        if(isDone() || (rsp=rsps.get(sender)) == null)
            return;

        RspFilter rsp_filter=options.rspFilter();
        lock.lock();
        try {
            if(!rsp.wasReceived()) {
                if(!(rsp.wasSuspected() || rsp.wasUnreachable()))
                    num_received++;
                if(rsp_filter == null || rsp_filter.isAcceptable(response_value, sender)) {
                    if(is_exception && response_value instanceof Throwable)
                        rsp.setException((Throwable)response_value);
                    else
                        rsp.setValue((T)response_value);
                    num_valid++;
                }
            }

            if(responsesComplete() || (rsp_filter != null && !rsp_filter.needMoreResponses())) {
                complete(this.rsps);
                corrDone();
            }
        }
        finally {
            lock.unlock();
        }
    }
544221
private static boolean hasResponseBody(int requestMethod, int responseCode) {
        return requestMethod != Request.Method.HEAD
            && !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK)
            && responseCode != HttpStatus.SC_NO_CONTENT
            && responseCode != HttpStatus.SC_NOT_MODIFIED;
    }
3736
public boolean checkSecurityConstraints(String pathInContext,
                                            HttpRequest request,
                                            HttpResponse response)
            throws HttpException, IOException
    {
        if (!super.checkSecurityConstraints(pathInContext,request,response) ||
            ! jSecurityCheck(pathInContext,request,response))
            return false;
        
        return true;
    }
950237
public void processResponse(ResponseEvent responseEvent) {
		final ResponseEventExt responseEventExt = (ResponseEventExt) responseEvent;
		final Response response = responseEventExt.getResponse();

		if(logger.isDebugEnabled()) {
			logger.debug("Response " + response.toString());
		}

		final CSeqHeader cSeqHeader = (CSeqHeader)response.getHeader(CSeqHeader.NAME);
		//if this is a response to a cancel, the response is dropped
		if(Request.CANCEL.equalsIgnoreCase(cSeqHeader.getMethod())) {
			if(logger.isDebugEnabled()) {
				logger.debug("the response is dropped accordingly to JSR 289 " +
						"since this a response to a CANCEL");
			}
			return;
		}
		// self routing makes the application data cloned, so we make sure to nullify it
		((MessageExt)response).setApplicationData(null);

		updateResponseStatistics(response, true);
		ClientTransaction clientTransaction = responseEventExt.getClientTransaction();
		final Dialog dialog = responseEventExt.getDialog();
		final boolean isForkedResponse = responseEventExt.isForkedResponse();
		final boolean isRetransmission = responseEventExt.isRetransmission();
		final ClientTransactionExt originalTransaction = responseEventExt.getOriginalTransaction();
		if(logger.isDebugEnabled()) {
			logger.debug("is Forked Response " + isForkedResponse);
			logger.debug("is Retransmission " + isRetransmission);
			logger.debug("Client Transaction " + clientTransaction);
			logger.debug("Original Transaction " + originalTransaction);
			logger.debug("Dialog " + dialog);
			if(dialog != null) {
				logger.debug("Dialog State " + dialog.getState());
			}
		}
		// Issue 1468 : Handling forking
		if(isForkedResponse && originalTransaction != null && !responseEventExt.isRetransmission()) {
			final Dialog defaultDialog = originalTransaction.getDefaultDialog();
			final Dialog orginalTransactionDialog = originalTransaction.getDialog();
			if(logger.isDebugEnabled()) {
				logger.debug("Original Transaction Dialog " + orginalTransactionDialog);
				logger.debug("Original Transaction Default Dialog " + defaultDialog);
			}
			clientTransaction = originalTransaction;
		}

		// Transate the response to SipServletResponse
		final SipServletResponseImpl sipServletResponse = (SipServletResponseImpl) sipFactoryImpl.getMobicentsSipServletMessageFactory().createSipServletResponse(
				response,
				clientTransaction,
				null,
				dialog,
				true,
				isRetransmission);
		try {
			messageDispatcherFactory.getResponseDispatcher(sipServletResponse, this).
				dispatchMessage(((SipProvider)responseEvent.getSource()), sipServletResponse);
		} catch (Throwable e) {
			logger.error("An unexpected exception happened while routing the response " +  sipServletResponse, e);
			return;
		}
	}
565325
private static boolean checkSuccess(HttpResponse response, boolean dryRun, TaskListener listener) {
        StatusLine status = response.getStatusLine();
        String content = "";
        try {
            content = ExtractorUtils.entityToString(response.getEntity());
            ExtractorUtils.validateStringNotBlank(content);
            JSONObject json = JSONObject.fromObject(content);
            String message = json.getString("message");
            if (assertResponseStatus(dryRun, listener, status, message)) {
                listener.getLogger().println(message);
                return true;
            }
        } catch (IOException e) {
            String parsingErrorStr = "Failed parsing distribution response";
            if (StringUtils.isNotBlank(content)) {
                parsingErrorStr = ": " + content;
            }
            e.printStackTrace(listener.error(parsingErrorStr));
        }
        return false;
    }