Internal execute, log headers, check for errors

@param request The request object to be executed

@return HttpResponse Response replied by the server

@throws RestException
331189
private HttpResponse execute( HttpUriRequest request ) throws RestException
    {
        log.debug( ">>>> " + request.getRequestLine() );
        for ( Header header : request.getAllHeaders() )
        {
            log.trace( ">>>> " + header.getName() + ": " + header.getValue() );
        }

        HttpResponse response;
        try
        {
            response = getHttpClient().execute( request );
            log.debug( "<<<< " + response.getStatusLine() );
            for ( Header header : response.getAllHeaders() )
            {
                log.trace( "<<<< " + header.getName() + ": " + header.getValue() );
            }

            if ( response.getStatusLine().getStatusCode() == 204 )
            {
                log.debug( "Consuming quietly the response entity since server returned no content" );
                EntityUtils.consumeQuietly( response.getEntity() );
            }

            checkError( response );
            return response;
        }
        catch ( KeyManagementException | NoSuchAlgorithmException | IOException e )
        {
            throw new RuntimeRestException( e );
        }
        finally
        {
            // https://issues.apache.org/jira/browse/HTTPCLIENT-1523
            DateUtils.clearThreadLocal();
        }
    }
31390
protected RestResponse performRequest(final HttpUriRequest request) throws IOException, AppPlatformException {

        if (this.usersUri == null || this.usersUri.isEmpty()
                || this.token == null || this.token.isEmpty()
                || this.secret == null || this.secret.isEmpty()) {

            throw new MissingCredentialsException();
        }

        RestResponse restResponse = RestResponse.createRestResponse(httpClient.execute(request));

        if (restResponse.getStatus() >= 400) {
            throw new AppPlatformException(restResponse.getResponseText(), restResponse.getStatus());
        }

        return restResponse;
    }
42904
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
			ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException {

		URI expanded = new UriTemplate(url).expand(urlVariables);
		return doExecute(expanded, method, requestCallback, responseExtractor);
	}
1256930
public String DoPut(Request request) throws Exception {

        Unirest.setHttpClient(getHttpClient());

        if (request.client == null) {
            throw new Exception("client must NOT null");
        }

        String buf = "";
        if (request.client.GetEnableCrypto()) {
            buf = request.crypto.signAndEncrypt(request.body.toString().getBytes());
        } else {
            buf = request.body.toString();
        }

        Map<String, String> mapHeader = Utils.JsonToMap(request.header);
        mapHeader.put(Headers.APIKeyHeader, request.client.GetApiKey());

        if (request.client.GetRouteTag() != "") {
            mapHeader.put(Headers.FabioRouteTagHeader, request.client.GetRouteTag());
            mapHeader.put(Headers.RouteTagHeader, request.client.GetRouteTag());
        }

        HttpResponse<String> res = Unirest.put(request.url).headers(mapHeader).body(buf).asString();

        String respData = res.getBody();

        System.out.println("Got remote cipher response: " + respData);

        String oriData = "";
        if (request.client.GetEnableCrypto()) {
            oriData = request.crypto.decryptAndVerify(respData.getBytes());
        } else {
            oriData = respData;
        }
        return oriData;

    }
74749
protected <T> Response<T> doPost(Request<T> request) {
		String payload = RequestUtil.getRequestPayload(request);
		URI uri = buidURI(request);

		Timer timer = Timer.tic();
		TransportResult result = getApiClientTransportFactory().newTransport(api).doPost(uri, payload);
		timer.toc();

		log.trace(result.getStatusCode() + " " + uri.toString() + " took " + timer.getDifference() + "ms");

		Response<T> response = toResponse(timer, result, request);

		return response;
	}
1081154
public function postAction(Request $request)
    {
        $name = $request->get('name');

        try {
            if (null == $name) {
                throw new RestException('There is no name for the account given');
            }

            $em = $this->getDoctrine()->getManager();
            $account = $this->doPost($request);
            $em->persist($account);
            $em->flush();

            $accountManager = $this->getAccountManager();
            $locale = $this->getUser()->getLocale();
            $acc = $accountManager->getAccount($account, $locale);
            $view = $this->view($acc, 200);

            $context = new Context();
            $context->setGroups(self::$accountSerializationGroups);
            $view->setContext($context);
        } catch (EntityNotFoundException $enfe) {
            $view = $this->view($enfe->toArray(), 404);
        } catch (RestException $re) {
            $view = $this->view($re->toArray(), 400);
        }

        return $this->handleView($view);
    }
907558
public WellRestedResponse submitRequest(Request request, HttpEntity httpEntity, List<Header> headers) {
        try {
            if (httpEntity != null) {
                request.body(httpEntity);
            }
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(request::addHeader);
            }
            if (this.globalHeaders != null && !this.globalHeaders.isEmpty()) {
                this.globalHeaders.forEach(request::addHeader);
            }
            if (this.proxy != null) {
                request.viaProxy(proxy);
            }
            setRequestTimeout(request);
            HttpResponse httpResponse;
            if (credentials != null) {
                Executor executor;
                if (disableCookiesForAuthRequests) {
                    executor = Executor.newInstance(internalStatelessHttpClient);
                    executor.clearCookies();
                    executor.clearAuth();
                } else {
                    executor = Executor.newInstance();
                }

                if (uri.getPort() > 0) {
                    executor.authPreemptive(uri.getHost() + ":" + uri.getPort());
                } else {
                    executor.authPreemptive(uri.getHost());
                }

                executor.auth(credentials);
                httpResponse = executor.execute(request).returnResponse();
            } else {
                httpResponse = request.execute().returnResponse();
            }
            return WellRestedUtil.buildWellRestedResponse(httpResponse, uri.toString());
        } catch (ConnectTimeoutException cte) {
            log.error("Connection timeout for request: {}", request.toString(), cte);
            return WellRestedUtil.buildConnectionTimeoutWellRestedResponse(uri.toString());
        } catch (SocketTimeoutException ste) {
            log.error("Socket timeout for request: {}", request.toString(), ste);
            return WellRestedUtil.buildSocketTimeoutWellRestedResponse(uri.toString());
        } catch (IOException ex) {
            log.error("Error occurred after executing the request to: {}", uri.toString(), ex);
        }
        return WellRestedUtil.buildErrorWellRestedResponse(uri.toString());
    }
768532
public Task<HttpResponse> execute(@NonNull final HttpRequest request) {
    return dispatcher.dispatchTask(new Callable<HttpResponse>() {
      @Override
      public HttpResponse call() {
        return proxy.execute(request);
      }
    });
  }
1181107
public ExecutionResult request(Request request) {
        // Schema
        GraphQLSchema schema = schemaService.getSchema();
        // Execution
        return graphQLService.execute(
                schema,
                request.getQuery(),
                request.getVariables(),
                request.getOperationName(),
                true
        );
    }
684744
public function toResponse($request)
    {
        if(! $this->handler && ! is_callable($this->handler)) {
            throw new ErrorException("No handler set");
        }

        $parameters = array_merge(
            [$request, $this->action],
            $this->parameters
        );

        try {
            $payload = call_user_func_array($this->handler, array_values($parameters));
        }
        catch (Exception $e) {
            // We'll assume that if an Exception has an error code 
            // that is explicitly defined, we want to use it as an
            // HTTP error code. if not we'll just let the 
            // Exception handler takes care of it. 
            $code = $e->getCode();

            if (! $this->isValidHttpStatusCode($code)) {
                throw $e;
            }
            
            $this->setStatusCode($code);

            return $e instanceof HasMessageBag 
                ? $this->respondWithMessageBag($e->getMessageBag(), class_basename($e))
                : $this->respondWithError($e->getMessage(), class_basename($e));
        }   
        catch (ValidationException $e) {
            throw $e;
        }

        return $this->handlePayload($payload);
    }
640515
public GetSessionResponse getSession(GetSessionRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_SESSION,
                request.getSessionId());
        return invokeHttpClient(internalRequest, GetSessionResponse.class);
    }
1270764
private RESTResponse validateAndExecuteRequest(HttpServletRequest request) {
        Map<String, String> variableMap = new HashMap<String, String>();
        String query = extractQueryParam(request, variableMap);
        Tenant tenant = getTenant(variableMap);

        // Command matching expects an encoded URI but without the servlet context, if any.
        String uri = request.getRequestURI();
        String context = request.getContextPath();
        if (!Utils.isEmpty(context)) {
            uri = uri.substring(context.length());
        }
        ApplicationDefinition appDef = getApplication(uri, tenant);
        
        HttpMethod method = HttpMethod.methodFromString(request.getMethod());
        if (method == null) {
            throw new NotFoundException("Request does not match a known URI: " + request.getRequestURL());
        }
        
        RegisteredCommand cmd = RESTService.instance().findCommand(appDef, method, uri, query, variableMap);
        if (cmd == null) {
            throw new NotFoundException("Request does not match a known URI: " + request.getRequestURL());
        }
        validateTenantAccess(request, tenant, cmd);
        
        RESTCallback callback = cmd.getNewCallback();
        callback.setRequest(new RESTRequest(tenant, appDef, request, variableMap));
        return callback.invoke();
    }
1260909
def execute(method, path, parameters, headers = { accept: :json }, &block)
      payload = {}.merge(parameters)
      url = base_url + path

      request_arguments = {
        method:  method,
        url:     url,
        payload: payload,
        headers: headers
      }

      RestClient::Request.execute(request_arguments, &block)
    rescue RestClient::Unauthorized
      raise AuthError, "Authentication failed"
    rescue RestClient::InternalServerError
      raise ServerError, "Server error"
    rescue RestClient::Forbidden => e
      raise BadRequest, e.http_body
    end
504714
public static String getError(final HttpServletRequest request) {
		StringBuilder sb = (StringBuilder) request.getAttribute(ERROR_KEY);
		if (sb == null) {
			return "";
		}
		return sb.toString();
	}
946418
protected function handleAction($request, $action) {
        foreach($request->latestParams() as $k => $v) {
            if($v || !isset($this->urlParams[$k])) $this->urlParams[$k] = $v;
        }
        // set the action to the request method / for developing we could use an additional parameter to choose another method
        $action = $this->getMethodName($request);
        $this->action = $action;
        $this->requestParams = $request->requestVars();
        $className = $this->class;
        // create serializer
        $serializer = SerializerFactory::create_from_request($request);
        $response = $this->getResponse();
        // perform action
        try {
            if(!$this->hasAction($action)) {
                // method couldn't found on controller
                throw new RestUserException("Action '$action' isn't available on class $className.", 404);
            }
            if(!$this->checkAccessAction($action)) {
                throw new RestUserException("Action '$action' isn't allowed on class $className.", 404, 401);
            }
            $actionResult = null;
            if(method_exists($this, 'beforeCallActionHandler')) {
                // call before action hook
                $actionResult = $this->beforeCallActionHandler($request, $action);
            }
            // if action hook contains data it will be used as result, otherwise the action handler will be called
            if(!$actionResult) {
                // perform action
                $actionResult = $this->$action($request);
            }
            $body = $actionResult;
        } catch(RestUserException $ex) {
            // a user exception was caught
            $response->setStatusCode($ex->getHttpStatusCode());
            $body = [
                'message' => $ex->getMessage(),
                'code' => $ex->getCode()
            ];
            // log all data
            SS_Log::log(
                json_encode(array_merge($body, ['file' => $ex->getFile(), 'line' => $ex->getLine()])),
                SS_Log::INFO);
        } catch(RestSystemException $ex) {
            // a system exception was caught
            $response->addHeader('Content-Type', $serializer->contentType());
            $response->setStatusCode($ex->getHttpStatusCode());
            $body = [
                'message' => $ex->getMessage(),
                'code' => $ex->getCode()
            ];
            if(Director::isDev()) {
                $body = array_merge($body, [
                    'file' => $ex->getFile(),
                    'line' => $ex->getLine(),
                    'trace' => $ex->getTrace()
                ]);
            }
            // log all data
            SS_Log::log(
                json_encode(array_merge($body, ['file' => $ex->getFile(), 'line' => $ex->getLine()])),
                SS_Log::WARN);
        } catch(Exception $ex) {
            // an unexpected exception was caught
            $response->addHeader('Content-Type', $serializer->contentType());
            $response->setStatusCode("500");
            $body = [
                'message' => $ex->getMessage(),
                'code' => $ex->getCode()
            ];
            if(Director::isDev()) {
                $body = array_merge($body, [
                    'file' => $ex->getFile(),
                    'line' => $ex->getLine(),
                    'trace' => $ex->getTrace()
                ]);
            }
            // log all data and the trace to get a better understanding of the exception
            SS_Log::log(
                json_encode(array_merge(
                    $body, ['file' => $ex->getFile(), 'line' => $ex->getLine(),'trace' => $ex->getTrace()])),
                SS_Log::ERR);
        }
        // serialize content and set body of response
        $response->addHeader('Content-Type', $serializer->contentType());
        // TODO: body could be an exception; check it before the response is generated
        $response->setBody($serializer->serialize($body));
        // set CORS header from config
        $response = $this->addCORSHeaders($response);
        return $response;
    }
81943
protected void processRequest( HttpServletRequest request,
                                   HttpServletResponse response ) throws ServletException, IOException {
        String authHeader = ((HttpServletRequest)request).getHeader("Authorization");
        String pathInfo= request.getPathInfo();
        
        Object marker = request.getSession().getAttribute("login-required-marker");
        
        if (marker == null && pathInfo.equals("login.do")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm =\"Realm\"");
            request.getSession().setAttribute("login-required-marker", Boolean.FALSE);
            return;
        }

        if (pathInfo.equals("login.do")) {
            response.sendRedirect(request.getContextPath() + "/Console.html");
            return;
        }
        
        String url = request.getRequestURI();
        String servletPath = request.getServletPath();

        request.getSession(true).setAttribute("initial.uri", url);
        logger.debug("Store requested uri " + url);
        
        String dest = url.substring(0, url.indexOf(servletPath));
        response.sendRedirect(dest);
    }
163277
public HttpResponse perform(HttpRequest request) throws IOException, HttpClientException {
		
		// first check if the request is a multipart/form-data and the method is
		// not POST: if so, there's something inconsistent and we just bail out
		if(request.isMultiPartFormData() && request.getMethod() != HttpMethod.POST) {
			logger.error("multipart/form-data can only be conveyed through a POST, using {} instead", request.getMethod().name());
			throw new HttpClientException("multipart/form-data cannot be conveyed through a " + request.getMethod().name() + " request");
		}
		
		URL url = request.getURL();		
		HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy != null ? proxy : Proxy.NO_PROXY);
		// optional default is GET
		connection.setRequestMethod(request.getMethod().name());
		for(Entry<String, String> header : request.getHeaders().entrySet()) {
			connection.setRequestProperty(header.getKey(), header.getValue());
		}
		
		if(request.getMethod() == HttpMethod.POST) {
			// add headers directly to the connection (we've already looped over
			// headers in the request object, so it's too late to add headers now)
			if(request.isMultiPartFormData()) {
				connection.setRequestProperty("Content-type", "multipart/form-data, boundary=" + request.getBoundary());
			} else {
				connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
			}
						
			connection.setDoOutput(true);
//			try(MirrorOutputStream mirror = new MirrorOutputStream(connection.getOutputStream(), new FileOutputStream("target/request.dat")); DataOutputStream stream = new DataOutputStream(mirror)) {
			try(DataOutputStream stream = new DataOutputStream(connection.getOutputStream())) {
				if(request.isMultiPartFormData()) {
					//
					// multipart/form-encoded format is:
					//
					// ========================
					// POST /path/to/script.php HTTP/1.0
					// Host: example.com
					// Content-type: multipart/form-data, boundary=<RANDOM BOUNDARY>
					// Content-Length: <REQUEST_LENGTH>
					//
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="field1"
					//
					// value1
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="field2"
					//
					// value2
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="file1"; filename="<NAME OF FILE 1>"
					// Content-Type: <FILE 1 MIME TYPE>
					// Content-Transfer-Encoding: binary
					// 
					// <FILE 1 BINARY DATA>
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="file2"; filename="<NAME OF FILE 2>"
					// Content-Type: <FILE 2 MIME TYPE>
					// Content-Transfer-Encoding: binary
					// 
					// <FILE 2 BINARY DATA>
					// --<RANDOM BOUNDARY>--
					// ==========================						
					for(HttpParameter parameter : request.getParameters()) {
						stream.writeBytes("--" + request.getBoundary());
						stream.writeBytes(NEWLINE);
						switch(parameter.getType()) {
						case TEXT:
							stream.writeBytes("Content-Disposition: form-data; name=\"" + parameter.getName() + "\"" + NEWLINE);
							stream.writeBytes(NEWLINE);
							stream.writeBytes(((HttpTextParameter)parameter).getValue().toString() + NEWLINE);
							break;
						case FILE:
							stream.writeBytes("Content-Disposition: form-data; name=\"" + parameter.getName() + "\"; filename=\"" + ((HttpFileParameter)parameter).getFileName() + "\"" + NEWLINE);
							stream.writeBytes("Content-Type: " + ((HttpFileParameter)parameter).getContentType() + NEWLINE);
							stream.writeBytes("Content-Transfer-Encoding: binary" + NEWLINE);
							stream.writeBytes(NEWLINE);
							Streams.copy(((HttpFileParameter)parameter).getInputStream(), stream);
							stream.writeBytes(NEWLINE);
							break;						
						}
					}					
					stream.writeBytes("--" + request.getBoundary() + "--");
				} else {
					//
					// plain old form format is:
					//
					// ========================
					// POST /path/to/script.php HTTP/1.0
					// Host: example.com
					// Content-type: application/x-www-form-urlencoded
					// Content-Length: <CONTENT LENGTH>
					//
					// logfile=blabla&configfile=more+blabla&usercomment=hello&useremail=
					// ==========================						
					//
					String values = HttpParameter.concatenate(request.getParameters());
					stream.writeBytes(values);
				}
			
				stream.flush();
				stream.close();
			}
		} else if(request.getMethod() == HttpMethod.GET) {
			// do nothing
		}
		
		return new HttpResponse(connection);
	}