Processes gateway response
773931
protected function processResponse()
    {
        if ($this->response->isSuccessful()) {
            $this->updateOrderStatus();
            $this->addTransaction();
            $this->redirectSuccess();
        } else if ($this->response->isRedirect()) {
            $this->response->redirect();
        } else {
            $this->controller->redirect('', $this->response->getMessage(), 'warning', true);
        }
    }
740633
def _process_response(self, response):
        
        assert self._state == self._STATE_RUNNING, "Should be running if processing response"
        cols = None
        data = []
        for r in response:
            if not cols:
                cols = [(f, r._fields[f].db_type) for f in r._fields]
            data.append([getattr(r, f) for f in r._fields])
        self._data = data
        self._columns = cols
        self._state = self._STATE_FINISHED
1366772
def get_gateway_socket(gateway):
    
    if not gateway:
        raise NATPMPNetworkError(NATPMP_GATEWAY_NO_VALID_GATEWAY,
                                 error_str(NATPMP_GATEWAY_NO_VALID_GATEWAY))
    response_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    response_socket.setblocking(0)
    response_socket.connect((gateway, NATPMP_PORT))
    return response_socket
1342191
def process_response(self, request, response):
        
        if hasattr(threadlocal, 'actionslog'):
            pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])

        return response
893953
def convert_to_api_gateway(status, headers, body)
      base64 = headers["x-jets-base64"] == 'yes'
      body = body.respond_to?(:read) ? body.read : body
      body = Base64.encode64(body) if base64

      resp = {
        "statusCode" => status,
        "headers" => headers,
        "body" => body,
        "isBase64Encoded" => base64,
      }
      adjust_for_elb(resp)
      resp
    end
228365
private void processResponse(Response<ByteArray, Object> response, Pipeline pipeline) {
        if(response == null) {
            logger.warn("RoutingTimedout on waiting for async ops; parallelResponseToWait: "
                        + numNodesPendingResponse + "; preferred-1: " + (preferred - 1)
                        + "; quorumOK: " + quorumSatisfied + "; zoneOK: " + zonesSatisfied);
        } else {
            numNodesPendingResponse = numNodesPendingResponse - 1;
            numResponsesGot = numResponsesGot + 1;
            if(response.getValue() instanceof Exception
               && !(response.getValue() instanceof ObsoleteVersionException)) {
                if(logger.isDebugEnabled()) {
                    logger.debug("PUT {key:" + key + "} handling async put error");
                }
                if(response.getValue() instanceof QuotaExceededException) {
                    /**
                     * TODO Not sure if we need to count this Exception for
                     * stats or silently ignore and just log a warning. While
                     * QuotaExceededException thrown from other places mean the
                     * operation failed, this one does not fail the operation
                     * but instead stores slops. Introduce a new Exception in
                     * client side to just monitor how mamy Async writes fail on
                     * exceeding Quota?
                     * 
                     */
                    if(logger.isDebugEnabled()) {
                        logger.debug("Received quota exceeded exception after a successful "
                                     + pipeline.getOperation().getSimpleName() + " call on node "
                                     + response.getNode().getId() + ", store '"
                                     + pipelineData.getStoreName() + "', master-node '"
                                     + pipelineData.getMaster().getId() + "'");
                    }
                } else if(handleResponseError(response, pipeline, failureDetector)) {
                    if(logger.isDebugEnabled()) {
                        logger.debug("PUT {key:" + key
                                     + "} severe async put error, exiting parallel put stage");
                    }

                    return;
                }
                if(PipelineRoutedStore.isSlopableFailure(response.getValue())
                   || response.getValue() instanceof QuotaExceededException) {
                    /**
                     * We want to slop ParallelPuts which fail due to
                     * QuotaExceededException.
                     * 
                     * TODO Though this is not the right way of doing things, in
                     * order to avoid inconsistencies and data loss, we chose to
                     * slop the quota failed parallel puts.
                     * 
                     * As a long term solution - 1) either Quota management
                     * should be hidden completely in a routing layer like
                     * Coordinator or 2) the Server should be able to
                     * distinguish between serial and parallel puts and should
                     * only quota for serial puts
                     * 
                     */
                    pipelineData.getSynchronizer().tryDelegateSlop(response.getNode());
                }

                if(logger.isDebugEnabled()) {
                    logger.debug("PUT {key:" + key + "} handled async put error");
                }

            } else {
                pipelineData.incrementSuccesses();
                failureDetector.recordSuccess(response.getNode(), response.getRequestTime());
                pipelineData.getZoneResponses().add(response.getNode().getZoneId());
            }
        }
    }
881297
public void processResponse(ResponseEvent responseEvent) {
    	BalancerAppContent content=(BalancerAppContent)responseEvent.getSource();
    	boolean isIpv6 = content.isIpv6();
        SipProvider sipProvider = content.getProvider();
        
        Response originalResponse = responseEvent.getResponse();
        if(logger.isDebugEnabled()) {
            logger.debug("got response :\n" + originalResponse);
        }

        updateStats(originalResponse);

        final Response response = (Response) originalResponse; 
        Node senderNode = getSenderNode(response);
        if(senderNode != null) {
        	if(logger.isDebugEnabled()) {
    			logger.debug("Updating Timestamp of sendernode: " + senderNode);
    		}
            senderNode.updateTimerStamp();
        }

        // Topmost via headers is me. As it is response to external request
        ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);

        String branch = viaHeader.getBranch();
        int versionDelimiter = branch.lastIndexOf('_');
        String version = branch.substring(versionDelimiter + 1);

        InvocationContext ctx = balancerRunner.getInvocationContext(version);

        if(viaHeader!=null && !isHeaderExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport(),isIpv6)) {
            response.removeFirst(ViaHeader.NAME);
        }
        
        viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
        String transport=viaHeader.getTransport();
        
        if(viaHeader!=null && !isHeaderExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport(),isIpv6)) {
            response.removeFirst(ViaHeader.NAME);
        }
        
       
        
        boolean fromServer = false;
        if(balancerRunner.balancerContext.isTwoEntrypoints()) {
        	if(!isIpv6)
        		fromServer = sipProvider.equals(balancerRunner.balancerContext.internalSipProvider);
        	else
        		fromServer = sipProvider.equals(balancerRunner.balancerContext.internalIpv6SipProvider);
            if(logger.isDebugEnabled()) {
            	if(!isIpv6)
            		logger.debug("fromServer : "+ fromServer + ", sipProvider " + sipProvider + ", internalSipProvider " + balancerRunner.balancerContext.internalSipProvider);
            	else
            		logger.debug("fromServer : "+ fromServer + ", sipProvider " + sipProvider + ", internalIpv6SipProvider " + balancerRunner.balancerContext.internalIpv6SipProvider);
            		
    		}
        } else {
            fromServer = senderNode == null;
            if(logger.isDebugEnabled()) {
    			logger.debug("fromServer : "+ fromServer + ", senderNode " + senderNode);
    		}
        }
        //removes rport and received from last Via header because of NEXMO patches it
        //only for external responses
        if(balancerRunner.balancerContext.isUseWithNexmo&&!fromServer)
        {
        	viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
        	if(viaHeader!=null) 
        	{
        		if(logger.isDebugEnabled())
        			logger.debug("We are going to remove rport and received parametres from :" + viaHeader + " from external response");
        		response.removeFirst(ViaHeader.NAME);
        		viaHeader.removeParameter("rport");
        		viaHeader.removeParameter("received");
			
        		try {
        			response.addFirst(viaHeader);
        		} catch (NullPointerException | SipException e) {
        			e.printStackTrace();
        		}
        		if(logger.isDebugEnabled())
        			logger.debug("After removing :" + response);
        	}
        }

        if(fromServer) {
        	if(senderNode!=null&&senderNode.getIp()!=null)
        	{
        		
        		if(balancerRunner.balancerContext.maxRequestNumberWithoutResponse!=null
      			&& balancerRunner.balancerContext.maxResponseTime!=null)
        		{
        	    	KeySip keySip = new KeySip(senderNode,isIpv6);
        	    	// adding null check for https://github.com/RestComm/load-balancer/issues/83
        	    	Node currNode = ctx.sipNodeMap(isIpv6).get(keySip);
        	    	if(currNode!=null)
        	    	{
        	    		if(logger.isDebugEnabled())
        	    			logger.debug("We are going to reset counters of health check" + currNode.getRequestNumberWithoutResponse()+ " : "+currNode.getLastTimeResponse());
        	    		currNode.setLastTimeResponse(System.currentTimeMillis());
        	    		currNode.setRequestNumberWithoutResponse(0);
        	    		if(logger.isDebugEnabled())
        	    			logger.debug("Counter of request without responses is : " + currNode.getRequestNumberWithoutResponse()+ " : "+currNode.getLastTimeResponse());
        	    	}
        	    	else
        	    	{
        	    		logger.warn("Node is null, we will not reset counters");
        	    	}
        		}
        		mediaFailureDetection(response, ctx, senderNode);
        	}
            /*
			if("true".equals(balancerRunner.balancerContext.properties.getProperty("removeNodesOn500Response")) && response.getStatusCode() == 500) {
				// If the server is broken remove it from the list and try another one with the next retransmission
				if(!(sourceNode instanceof ExtraServerNode)) {
					if(balancerRunner.balancerContext.nodes.size()>1) {
						balancerRunner.balancerContext.nodes.remove(sourceNode);
						balancerRunner.balancerContext.balancerAlgorithm.nodeRemoved(sourceNode);
					}
				}
			} 
        	*/
        	String publicIp = null;
        	if(!isIpv6)
        		publicIp = balancerRunner.balancerContext.publicIP;
        	else
        		publicIp = balancerRunner.balancerContext.publicIPv6;
        	if(publicIp != null && publicIp.trim().length() > 0) {
        		if(logger.isDebugEnabled()) {
        			logger.debug("Will add Record-Route header to response with public IP Address: "+publicIp);
        		}
                patchSipMessageForNAT(response, isIpv6);
            }
            // https://github.com/RestComm/load-balancer/issues/45 Adding sender node for the algorithm to be available
        	((ResponseExt)response).setApplicationData(senderNode);
        	
            ctx.balancerAlgorithm.processInternalResponse(response,isIpv6);
            try {	
                if(logger.isDebugEnabled()) {
                    logger.debug("from server sending response externally " + response);
                }
                if(!isIpv6)
                	balancerRunner.balancerContext.externalSipProvider.sendResponse(response);
                else
                	balancerRunner.balancerContext.externalIpv6SipProvider.sendResponse(response);

            } catch (Exception ex) {
                logger.error("Unexpected exception while forwarding the response \n" + response, ex);
            }
        } else {
        	try {
                SIPMessage message = (SIPMessage)response;

                String initialRemoteAddr = message.getPeerPacketSourceAddress().getHostAddress();
                String initialRemotePort = String.valueOf(message.getPeerPacketSourcePort());

                Header remoteAddrHeader = null;
                Header remotePortHeader = null;
                try {
                	HeaderFactory hf=SipFactory.getInstance().createHeaderFactory();
                    remoteAddrHeader = hf.createHeader("X-Sip-Balancer-InitialRemoteAddr", initialRemoteAddr);
                    remotePortHeader = hf.createHeader("X-Sip-Balancer-InitialRemotePort", initialRemotePort);
                } catch (PeerUnavailableException e) {
                    logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
                } catch (ParseException e) {
                    logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
                }
                if (remoteAddrHeader != null)
                    response.addHeader(remoteAddrHeader);
                if (remotePortHeader != null)
                    response.addHeader(remotePortHeader);
                                
                if(balancerRunner.balancerContext.isTwoEntrypoints()) {
            	    ctx.balancerAlgorithm.processExternalResponse(response,isIpv6);
                   
                    if(logger.isDebugEnabled()) {
                        logger.debug("two entry points: from external sending response " + response);
                    }
                    if(!isIpv6)
                    	balancerRunner.balancerContext.internalSipProvider.sendResponse(response);
                    else
                    	balancerRunner.balancerContext.internalIpv6SipProvider.sendResponse(response);
                } else {
                	if(!comesFromInternalNode(response,ctx,initialRemoteAddr,message.getPeerPacketSourcePort(),transport,isIpv6))
                		ctx.balancerAlgorithm.processExternalResponse(response,isIpv6);
                	else
                		ctx.balancerAlgorithm.processInternalResponse(response,isIpv6);
                	
                    if(logger.isDebugEnabled()) {
                        logger.debug("one entry point: from external sending response " + response);
                    }
                    if(!isIpv6)
                    	balancerRunner.balancerContext.externalSipProvider.sendResponse(response);
                    else
                    	balancerRunner.balancerContext.externalIpv6SipProvider.sendResponse(response);
                }
            } catch (Exception ex) {
                logger.error("Unexpected exception while forwarding the response \n" + response, ex);
            }
        }
    }
1126422
def _process_response(self, request, response):
        
        if request.is_ajax() and hasattr(request, 'horizon'):
            queued_msgs = request.horizon['async_messages']
            if type(response) == http.HttpResponseRedirect:
                # Drop our messages back into the session as per usual so they
                # don't disappear during the redirect. Not that we explicitly
                # use django's messages methods here.
                for tag, message, extra_tags in queued_msgs:
                    getattr(django_messages, tag)(request, message, extra_tags)
                if response['location'].startswith(settings.LOGOUT_URL):
                    redirect_response = http.HttpResponse(status=401)
                    # This header is used for handling the logout in JS
                    redirect_response['logout'] = True
                    if self.logout_reason is not None:
                        utils.add_logout_reason(
                            request, redirect_response, self.logout_reason,
                            'error')
                else:
                    redirect_response = http.HttpResponse()
                # Use a set while checking if we want a cookie's attributes
                # copied
                cookie_keys = {'max_age', 'expires', 'path', 'domain',
                               'secure', 'httponly', 'logout_reason'}
                # Copy cookies from HttpResponseRedirect towards HttpResponse
                for cookie_name, cookie in response.cookies.items():
                    cookie_kwargs = dict((
                        (key, value) for key, value in cookie.items()
                        if key in cookie_keys and value
                    ))
                    redirect_response.set_cookie(
                        cookie_name, cookie.value, **cookie_kwargs)
                redirect_response['X-Horizon-Location'] = response['location']
                upload_url_key = 'X-File-Upload-URL'
                if upload_url_key in response:
                    self._copy_headers(response, redirect_response,
                                       (upload_url_key, 'X-Auth-Token'))
                return redirect_response
            if queued_msgs:
                # TODO(gabriel): When we have an async connection to the
                # client (e.g. websockets) this should be pushed to the
                # socket queue rather than being sent via a header.
                # The header method has notable drawbacks (length limits,
                # etc.) and is not meant as a long-term solution.
                response['X-Horizon-Messages'] = json.dumps(queued_msgs)
        return response
1205831
def process_response(self, request, response):
        
        self._set_request_auth_type_metric(request)
        self._set_request_user_agent_metrics(request)
        self._set_request_referer_metric(request)
        self._set_request_user_id_metric(request)

        return response
779440
def handle_gateway_ready(msg):  # pylint: disable=useless-return
    """"""
    _LOGGER.info(
        'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type,
        msg.sub_type, msg.payload)
    msg.gateway.alert(msg)
    return None
14313
@Override
	protected void respondAsLeader(ChannelHandlerContext channelHandlerContext, RoutedRequest routedRequest, T gateway) throws Exception {
		final HttpRequest request = routedRequest.getRequest();
		final String requestPath;

		// make sure we request the "index.html" in case there is a directory request
		if (routedRequest.getPath().endsWith("/")) {
			requestPath = routedRequest.getPath() + "index.html";
		}
		// in case the files being accessed are logs or stdout files, find appropriate paths.
		else if (routedRequest.getPath().equals("/jobmanager/log") || routedRequest.getPath().equals("/jobmanager/stdout")) {
			requestPath = "";
		} else {
			requestPath = routedRequest.getPath();
		}

		respondToRequest(channelHandlerContext, request, requestPath);
	}
460074
public function processResponse()
    {

        // Implode the packets, not sure if there is any split logic for multiple packets
        $buffer = new Buffer(implode('', $this->packets_response), Buffer::NUMBER_TYPE_BIGENDIAN);

        // Get the passed length in the data side of the packet
        $buffer->readInt32Signed();

        // Read off the timestamp (in milliseconds)
        $buffer->readInt64();

        // Burn the check id == 42
        $buffer->readInt8();

        // Read packetId, unused
        $buffer->readInt16Signed();

        // Read commandId, unused
        $buffer->readInt8Signed();

        // Read type, unused
        $buffer->readInt8Signed();

        $parsed = $this->parseServerParameters($buffer);

        // Set the result to a new result instance
        $result = new Result();

        // Best guess info version is the type of response to expect.  As of this commit the version is "2".
        $result->add('info_version', $parsed[0]);
        $result->add('version', $parsed[1]);
        $result->add('hostname', $parsed[2]);
        $result->add('game_descr', $parsed[3]);
        $result->add('start_time', $parsed[4]);
        $result->add('num_players', $parsed[5]);
        $result->add('max_players', $parsed[6]);
        $result->add('dedicated', 1); // All servers are dedicated as far as I can tell
        $result->add('password', 0); // Unsure if you can password servers, cant read that value
        //$result->add('map', 'Unknown');

        unset($parsed);

        return $result->fetch();
    }
681726
def process_response(self, request, response):
        
        if response.status_code == 404 and not settings.DEBUG:
            domain = request.get_host()
            path = request.get_full_path()
            referer = force_text(
                request.META.get('HTTP_REFERER', ''), errors='replace')

            if not self.is_ignorable_request(request, path, domain, referer):
                ua = request.META.get('HTTP_USER_AGENT', '<none>')
                ip = request.META.get('REMOTE_ADDR', '<none>')

                user = None
                if request.user and hasattr(request.user, 'email'):
                    user = request.user.email
                content = (
                    "Referrer: %s\n"
                    "Requested URL: %s\n"
                    "User agent: %s\n"
                    "IP address: %s\n"
                    "User: %s\n"
                ) % (referer, path, ua, ip, user)
                if self.is_internal_request(domain, referer):
                    internal = 'INTERNAL '
                else:
                    internal = ''
                mail_managers(
                    "Broken %slink on %s" % (
                        internal,
                        domain
                    ),
                    content,
                    fail_silently=True)
        return response
1295374
def handle_processing_packets():
    

    host = os.getenv(
        "LISTEN_ON_HOST",
        "127.0.0.1").strip().lstrip()
    port = int(os.getenv(
        "LISTEN_ON_PORT",
        "80").strip().lstrip())
    backlog = int(os.getenv(
        "LISTEN_BACKLOG",
        "5").strip().lstrip())
    size = int(os.getenv(
        "LISTEN_SIZE",
        "102400").strip().lstrip())
    sleep_in_seconds = float(os.getenv(
        "LISTEN_SLEEP",
        "0.5").strip().lstrip())
    needs_response = bool(os.getenv(
        "LISTEN_SEND_RESPONSE",
        "0").strip().lstrip() == "1")
    shutdown_hook = os.getenv(
        "LISTEN_SHUTDOWN_HOOK",
        "/tmp/shutdown-listen-server-{}-{}".format(
            host,
            port)).strip().lstrip()
    filter_key = os.getenv(
        "IGNORE_KEY",
        INCLUDED_IGNORE_KEY).strip().lstrip()

    if os.path.exists(shutdown_hook):
        log.info(("Please remove the shutdown hook file: "
                  "\nrm -f {}")
                 .format(
                    shutdown_hook))
        sys.exit(1)

    default_filter_key = filter_key
    bytes_for_filter_key = len(default_filter_key)
    offset_to_filter_key = (-1 * bytes_for_filter_key)
    offset_to_msg = offset_to_filter_key - 1

    now = datetime.datetime.now().isoformat()
    log.info(("{} - Starting Server address={}:{} "
              "backlog={} size={} sleep={} shutdown={} "
              "filter_key={}")
             .format(
                now,
                host,
                port,
                backlog,
                size,
                sleep_in_seconds,
                shutdown_hook,
                default_filter_key))

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    s.listen(backlog)
    client, address = s.accept()

    midx = 0
    while 1:
        data = None
        address = None
        ignore_key = None

        try:
            if not client:
                client, address = s.accept()
        except Exception as e:
            log.error(("socket accept with ex={}")
                      .format(
                        e))
        try:
            if client:
                data = client.recv(size)
        except Exception as e:
            log.error(("recv - disconnected with ex={}")
                      .format(
                        e))
        if data:
            now = datetime.datetime.now().isoformat()
            packet_to_process = data[0:offset_to_msg]
            ignore_key = data[offset_to_filter_key:]
            log.info(("decoding data={} key={}")
                     .format(
                        packet_to_process,
                        ignore_key))

            msg = None
            try:
                msg = json.loads(
                            packet_to_process.decode("utf-8"))
            except Exception as e:
                msg = None
                log.error(("Invalid data={} with ex={}")
                          .format(
                            packet_to_process,
                            e))

            if msg:

                log.info(("received msg={} "
                          "data={} replying - ignore='{}'")
                         .format(
                            ppj(msg),
                            packet_to_process,
                            ignore_key))

                if msg["status"] == VALID:
                    if msg["data_type"] == TCP:
                        log.info("TCP")
                    elif msg["data_type"] == UDP:
                        log.info("TCP")
                    elif msg["data_type"] == ARP:
                        log.info("TCP")
                    elif msg["data_type"] == ICMP:
                        log.info("TCP")
                    else:
                        log.error(("unsuppported type={}")
                                  .format(
                                    msg["data_type"]))
                    # end of supported eth protocol message types
                else:
                    log.error(("unsuppported msg status={}")
                              .format(
                                msg["status"]))
                # end if msg was VALID
            # end of if found msg

            midx += 1
            if midx > 1000000:
                midx = 0
        else:
            log.debug("ignoring invalid data")
        # end of if valid msg or not

        if needs_response:
            client.send(ignore_key)
        else:
            log.info("no response")
            time.sleep(sleep_in_seconds)

        if os.path.exists(shutdown_hook):
            now = datetime.datetime.now().isoformat()
            log.info(("{} detected shutdown "
                      "file={}")
                     .format(
                        now,
                        shutdown_hook))
    # end of loop

    log.info("shutting down")
    client.close()

    log.info("done")
259625
@Override
    public Object processResponse(Object rawResponse) throws ServiceException {
        PipelineHelpers.throwIfNotSuccess((ClientResponse) rawResponse);
        return rawResponse;
    }
773121
@Override
	public Response process(Response.ResponseBuilder responseBuilder)
	{
		final String entity = process();

		responseBuilder.entity(entity);

		return responseBuilder.build();
	}
1003825
async def process(client: Client, transaction_signed_raw: str) -> ClientResponse:
    
    return await client.post(MODULE + '/process', {'transaction': transaction_signed_raw}, rtype=RESPONSE_AIOHTTP)