Executes the given {@link HttpRequest}.

@param request the request to execute.
@return a task containing the response to executing the request.
768532
public Task<HttpResponse> execute(@NonNull final HttpRequest request) {
    return dispatcher.dispatchTask(new Callable<HttpResponse>() {
      @Override
      public HttpResponse call() {
        return proxy.execute(request);
      }
    });
  }
487457
public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {
        try {
            return execute(listener, task.getServerIdentity(), task.getOperation());
        } catch (OperationFailedException e) {
            // Handle failures operation transformation failures
            final ServerIdentity identity = task.getServerIdentity();
            final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);
            final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);
            listener.operationPrepared(result);
            recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));
            return 1; // 1 ms timeout since there is no reason to wait for the locally stored result
        }

    }
974830
public QueryResponse<DatastoreKey> executeKeyQueryRequest(KeyQueryRequest request) {
    try {
      GqlQuery.Builder<Key> queryBuilder = Query.newGqlQueryBuilder(ResultType.KEY,
          request.getQuery());
      queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
      queryBuilder.setAllowLiteral(request.isAllowLiterals());
      QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
      QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
      GqlQuery<Key> gqlQuery = queryBuilder.build();
      QueryResults<Key> results = nativeReader.run(gqlQuery);
      List<DatastoreKey> entities = new ArrayList<>();
      DefaultQueryResponse<DatastoreKey> response = new DefaultQueryResponse<>();
      response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
      while (results.hasNext()) {
        Key result = results.next();
        DatastoreKey datastoreKey = new DefaultDatastoreKey(result);
        entities.add(datastoreKey);
      }
      response.setResults(entities);
      response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
      response.setQueryResponseMetadata(
          new DefaultQueryResponseMetadata(
              QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
      return response;
    } catch (DatastoreException exp) {
      throw new EntityManagerException(exp);
    }
  }
944329
@Override
    public HttpResponse execute(HttpRequest request) throws BaasException {
        try {
            HttpURLConnection connection = openConnection(request.url);

            for (String name : request.headers.keySet()) {
                connection.addRequestProperty(name, request.headers.get(name));
            }
            setupConnectionForRequest(connection, request);
            connection.connect();

            int responseCode = -1;
            try {
                responseCode = connection.getResponseCode();
            } catch (IOException e) {
                responseCode = connection.getResponseCode();
            }
            Logger.info("Connection response received");
            if (responseCode == -1) {
                throw new IOException("Connection failed");
            }


            HttpResponse response = new HttpResponse(HttpResponse.HttpVersion.HTTP_1_1,responseCode,connection.getResponseMessage());

            response.setEntity(asEntity(connection));
            for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
                if (header.getKey() != null) {
//                    Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                    response.addHeader(header.getKey(),header.getValue().get(0));
                }
            }
            return response;
        } catch (IOException e) {
            throw new BaasIOException(e);
        }
    }
849327
public void execute(Task task) {
    LOG.info(String.format("Executing task %s", task.getTaskId()));
    this.taskExecutor.execute(new TrackingTask(task));
  }
359833
public Response api(Request request) throws IOException {
    Request req = new Request();
    req.setMethod(request.getMethod());
    req.setBaseUri(this.host);
    req.setEndpoint("/" + version + "/" + request.getEndpoint());
    req.setBody(request.getBody());
    for (Map.Entry<String, String> header : this.requestHeaders.entrySet()) {
      req.addHeader(header.getKey(), header.getValue());
    }
    for (Map.Entry<String, String> queryParam : request.getQueryParams().entrySet()) {
      req.addQueryParam(queryParam.getKey(), queryParam.getValue());
    }

    return makeCall(req);
  }
1146413
public CreateSessionResponse createSession(CreateSessionRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        if (request.getPreset() == null && request.getPresets() == null) {
            throw new IllegalArgumentException("The parameter preset and presets should NOT both be null or empty.");
        }

        InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, LIVE_SESSION);
        return invokeHttpClient(internalRequest, CreateSessionResponse.class);
    }
439701
public CompletableFuture<BackupResponse> backup(BackupRequest request) {
    ComposableFuture<BackupResponse> future = new ComposableFuture<>();
    threadContext.execute(() -> {
      role.backup(request).whenComplete(future);
    });
    return future;
  }
933554
public static <T> T executeXmlResult(HttpUriRequest request,Class<T> clazz){
		return execute(request,XmlResponseHandler.createResponseHandler(clazz));
	}
1217323
public <T> T execute(WebDriverLikeRequest request) {
    Response response = null;
    long total = 0;
    try {
      HttpClient client = newHttpClientWithTimeout();
      String url = remoteURL + request.getPath();
      BasicHttpEntityEnclosingRequest
          r =
          new BasicHttpEntityEnclosingRequest(request.getMethod(), url);
      if (request.hasPayload()) {
        r.setEntity(new StringEntity(request.getPayload().toString(), "UTF-8"));
      }

      HttpHost h = new HttpHost(remoteURL.getHost(), remoteURL.getPort());
      long start = System.currentTimeMillis();
      HttpResponse res = client.execute(h, r);
      total = System.currentTimeMillis() - start;

      response = Helper.exctractResponse(res);
    } catch (Exception e) {
      throw new WebDriverException(e);
    }
    response = errorHandler.throwIfResponseFailed(response, total);
    try{
    return cast(response.getValue());
    }catch (ClassCastException e){
      log.warning(e.getMessage()+" for "+response.getValue());
      throw e;
    }
  }
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);
	}
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;
    }
588430
protected JsonRpcResponse execute(JsonRpcRequest request) {
        if (request == null) {
            return new JsonRpcResponse(null, JsonRpcError.parseError(null));
        }

        String serviceName = null;
        String methodName = request.getMethod();
        int lastIndex = methodName.lastIndexOf('.');
        if (lastIndex >= 0) {
            serviceName = methodName.substring(0, lastIndex);
            methodName = methodName.substring(lastIndex + 1);
        }

        ServiceEntry<?> serviceEntry = serviceRegistry.getService(serviceName);
        if (serviceEntry == null) {
            return new JsonRpcResponse(null, JsonRpcError.methodNotFoundError(null));
        }
        Set<Method> methods = serviceEntry.getMethods(methodName);
        if (methods == null || methods.isEmpty()) {
            return new JsonRpcResponse(null, JsonRpcError.methodNotFoundError(null));
        }

        String id = request.getId();
        Node[] params = request.getParams();
        Method method = findExecutableMethod(methods, params);
        if (method == null) {
            return new JsonRpcResponse(null, JsonRpcError.invalidParamsError(null));
        }

        Object service = serviceEntry.getService();
        Object[] args = getParameters(method, params);
        try {
            Object invokeValue = method.invoke(service, args);

            if (id == null) {
                return null;
            }

            Node result = jsonImpl.convert(invokeValue);
            return new JsonRpcResponse(id, result);
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException) {
                t = ((InvocationTargetException) t).getTargetException();
            }
            LOG.debug("executing error : " + method, t);
            return new JsonRpcResponse(id, JsonRpcError.serverError(2, "Server error", t));
        }
    }
264526
public CommandResponse execute(GwtCommand request) {
		if (request != null) {
			return commandDispatcher.execute(request.getCommandName(), request.getCommandRequest(),
					request.getUserToken(), request.getLocale());
		}
		return null;
	}
284878
protected Response executeRequest(Request request)
    {
        try
        {
            com.squareup.okhttp.Request httpRequest = buildHttpRequest(request);

            if(logger.isInfoEnabled())
                logger.info("Sending request: {} {}",httpRequest.method(),httpRequest.urlString());

            if(logger.isDebugEnabled() && request.getRequestMethod().isBodyRequest())
            {
                Buffer buffer = new Buffer();
                httpRequest.body().writeTo(buffer);
                if(maxLoggedBodySize == -1 || buffer.size() <= maxLoggedBodySize )
                    logger.debug("Request body: {}", buffer.readUtf8());
                else
                    logger.debug("Request body not captured: too large. ");
            }

            if(logger.isTraceEnabled())
                logger.trace("Request headers: {}",httpRequest.headers().toString());

            Response response = client.newCall(httpRequest).execute();

            if(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && authorizationFactory != null
                    && authorizationFactory.retryOnAuthenticationError())
            {
                if(authorizationFactory instanceof ResettableAuthorizationFactory)
                    ((ResettableAuthorizationFactory) authorizationFactory).reset();

                response = client.newCall(httpRequest).execute();
            }

            logger.info("Response code: {}",response.code());

            if(logger.isTraceEnabled())
                logger.trace("Response headers: {}",response.headers().toString());

            if(logger.isDebugEnabled())
            {
                ByteArrayOutputStream copy = new ByteArrayOutputStream();
                copy(response.body().byteStream(),copy);
                response = response.newBuilder().body(ResponseBody.create(response.body().contentType(),copy.toByteArray())).build();

                if(maxLoggedBodySize == -1 || copy.size() <= maxLoggedBodySize)
                    logger.debug("Response body: {}",copy.toString());
                else
                    logger.debug("Response body not captured: too large.");
            }
            if (response.code() >= HttpURLConnection.HTTP_BAD_REQUEST)
            {
                throw readException(response);
            }

            return response;
        }
        catch (IOException e)
        {
            throw new ClientConnectionException("Error calling service.",e);
        }

    }
703571
public boolean execute (PathFinderRequest<N> request) {

		request.executionFrames++;

		while (true) {
			if (DEBUG) GdxAI.getLogger().debug(TAG, "------");
			// Should perform search begin?
			if (request.status == PathFinderRequest.SEARCH_NEW) {
				long currentTime = TimeUtils.nanoTime();
				timeToRun -= currentTime - lastTime;
				if (timeToRun <= timeTolerance) return false;
				if (DEBUG) GdxAI.getLogger().debug(TAG, "search begin");
				if (!request.initializeSearch(timeToRun)) return false;
				request.changeStatus(PathFinderRequest.SEARCH_INITIALIZED);
				lastTime = currentTime;
			}

			// Should perform search path?
			if (request.status == PathFinderRequest.SEARCH_INITIALIZED) {
				long currentTime = TimeUtils.nanoTime();
				timeToRun -= currentTime - lastTime;
				if (timeToRun <= timeTolerance) return false;
				if (DEBUG) GdxAI.getLogger().debug(TAG, "search path");
				if (!request.search(pathFinder, timeToRun)) return false;
				request.changeStatus(PathFinderRequest.SEARCH_DONE);
				lastTime = currentTime;
			}

			// Should perform search end?
			if (request.status == PathFinderRequest.SEARCH_DONE) {
				long currentTime = TimeUtils.nanoTime();
				timeToRun -= currentTime - lastTime;
				if (timeToRun <= timeTolerance) return false;
				if (DEBUG) GdxAI.getLogger().debug(TAG, "search end");
				if (!request.finalizeSearch(timeToRun)) return false;
				request.changeStatus(PathFinderRequest.SEARCH_FINALIZED);

				// Search finished, send result to the client
				if (server != null) {
					MessageDispatcher dispatcher = request.dispatcher != null ? request.dispatcher : MessageManager.getInstance();
					dispatcher.dispatchMessage(server, request.client, request.responseMessageCode, request);
				}

				lastTime = currentTime;

				if (request.statusChanged && request.status == PathFinderRequest.SEARCH_NEW) {
					if (DEBUG) GdxAI.getLogger().debug(TAG, "search renew");
					continue;
				}
			}

			return true;
		}
	}
26500
void invoke(HttpRequest request) throws Exception {
    bodyConsumer = null;
    Object invokeResult;
    try {
      args[0] = this.request = request;
      invokeResult = method.invoke(handler, args);
    } catch (InvocationTargetException e) {
      exceptionHandler.handle(e.getTargetException(), request, responder);
      return;
    } catch (Throwable t) {
      exceptionHandler.handle(t, request, responder);
      return;
    }

    if (isStreaming) {
      // Casting guarantee to be succeeded.
      bodyConsumer = (BodyConsumer) invokeResult;
    }
  }