Sends an HTTP request to the task of the specified {@code taskId} and returns a response if it succeeded.
178285
private FullResponseHolder submitRequest(
      String taskId,
      @Nullable String mediaType, // nullable if content is empty
      HttpMethod method,
      String encodedPathSuffix,
      @Nullable String encodedQueryString,
      byte[] content,
      boolean retry
  ) throws IOException, ChannelException, NoTaskLocationException
  {
    final RetryPolicy retryPolicy = retryPolicyFactory.makeRetryPolicy();

    while (true) {
      String path = StringUtils.format("%s/%s/%s", BASE_PATH, StringUtils.urlEncode(taskId), encodedPathSuffix);

      Optional<TaskStatus> status = taskInfoProvider.getTaskStatus(taskId);
      if (!status.isPresent() || !status.get().isRunnable()) {
        throw new TaskNotRunnableException(
            StringUtils.format(
                "Aborting request because task [%s] is not runnable",
                taskId
            )
        );
      }

      final TaskLocation location = taskInfoProvider.getTaskLocation(taskId);
      if (location.equals(TaskLocation.unknown())) {
        throw new NoTaskLocationException(StringUtils.format("No TaskLocation available for task [%s]", taskId));
      }

      final Request request = createRequest(
          taskId,
          location,
          path,
          encodedQueryString,
          method,
          mediaType,
          content
      );

      FullResponseHolder response = null;
      try {
        // Netty throws some annoying exceptions if a connection can't be opened, which happens relatively frequently
        // for tasks that happen to still be starting up, so test the connection first to keep the logs clean.
        checkConnection(request.getUrl().getHost(), request.getUrl().getPort());

        response = submitRequest(request);

        int responseCode = response.getStatus().getCode();
        if (responseCode / 100 == 2) {
          return response;
        } else if (responseCode == 400) { // don't bother retrying if it's a bad request
          throw new IAE("Received 400 Bad Request with body: %s", response.getContent());
        } else {
          throw new IOE("Received status [%d] and content [%s]", responseCode, response.getContent());
        }
      }
      catch (IOException | ChannelException e) {

        // Since workers are free to move tasks around to different ports, there is a chance that a task may have been
        // moved but our view of its location has not been updated yet from ZK. To detect this case, we send a header
        // identifying our expected recipient in the request; if this doesn't correspond to the worker we messaged, the
        // worker will return an HTTP 404 with its ID in the response header. If we get a mismatching task ID, then
        // we will wait for a short period then retry the request indefinitely, expecting the task's location to
        // eventually be updated.

        final Duration delay;
        if (response != null && response.getStatus().equals(HttpResponseStatus.NOT_FOUND)) {
          String headerId = StringUtils.urlDecode(
              response.getResponse().headers().get(ChatHandlerResource.TASK_ID_HEADER)
          );
          if (headerId != null && !headerId.equals(taskId)) {
            log.warn(
                "Expected worker to have taskId [%s] but has taskId [%s], will retry in [%d]s",
                taskId, headerId, TASK_MISMATCH_RETRY_DELAY_SECONDS
            );
            delay = Duration.standardSeconds(TASK_MISMATCH_RETRY_DELAY_SECONDS);
          } else {
            delay = retryPolicy.getAndIncrementRetryDelay();
          }
        } else {
          delay = retryPolicy.getAndIncrementRetryDelay();
        }
        final String urlForLog = request.getUrl().toString();
        if (!retry) {
          // if retry=false, we probably aren't too concerned if the operation doesn't succeed (i.e. the request was
          // for informational purposes only) so don't log a scary stack trace
          log.info("submitRequest failed for [%s], with message [%s]", urlForLog, e.getMessage());
          throw e;
        } else if (delay == null) {
          log.warn(e, "Retries exhausted for [%s], last exception:", urlForLog);
          throw e;
        } else {
          try {
            final long sleepTime = delay.getMillis();
            log.debug(
                "Bad response HTTP [%s] from [%s]; will try again in [%s] (body/exception: [%s])",
                (response != null ? response.getStatus().getCode() : "no response"),
                urlForLog,
                new Duration(sleepTime).toString(),
                (response != null ? response.getContent() : e.getMessage())
            );
            Thread.sleep(sleepTime);
          }
          catch (InterruptedException e2) {
            Thread.currentThread().interrupt();
            e.addSuppressed(e2);
            throw new RuntimeException(e);
          }
        }
      }
      catch (NoTaskLocationException e) {
        log.info("No TaskLocation available for task [%s], this task may not have been assigned to a worker yet or "
                 + "may have already completed", taskId);
        throw e;
      }
      catch (Exception e) {
        log.warn(e, "Exception while sending request");
        throw e;
      }
    }
  }
703553
public void waitTask(String taskID, long timeToWait) throws AlgoliaException {
    this.waitTask(taskID, timeToWait, RequestOptions.empty);
  }
1039185
public static final void assertTaskUncompleted(final String taskId) {
        Validate.notNull(taskId);

        apiCallback.debug(LogMessage.TASK_2, taskId);
        try {
            getTaskInstanceAssertable().taskIsUncompleted(taskId);
        } catch (final AssertionError ae) {
            apiCallback.fail(ae, LogMessage.ERROR_TASK_2, taskId);
        }
    }
1088566
def send_task(self, request, response):
        """"""

        # TODO is this too messy?
        from bettercache.tasks import GeneratePage
        try:
            GeneratePage.apply_async((strip_wsgi(request),))
        except:
            logger.error("failed to send celery task")
        self.set_cache(request, response)
640388
public net.minidev.ovh.api.sms.OvhTask serviceName_task_taskId_GET(String serviceName, Long taskId) throws IOException {
		String qPath = "/sms/{serviceName}/task/{taskId}";
		StringBuilder sb = path(qPath, serviceName, taskId);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, net.minidev.ovh.api.sms.OvhTask.class);
	}
76592
public Task getTaskDetails(String taskId) {
        Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank");
        return protoMapper.fromProto(
                stub.getTask(TaskServicePb.GetTaskRequest.newBuilder()
                        .setTaskId(taskId)
                        .build()
                ).getTask()
        );
    }
942035
protected <T> Future<T> invokeSubmit(ExecutorService executor, Callable<T> task) {
    return executor.submit(wrapTask(task));
  }
770172
protected FullResponseHolder submitJsonRequest(
      String taskId,
      HttpMethod method,
      String encodedPathSuffix,
      @Nullable String encodedQueryString,
      byte[] content,
      boolean retry
  ) throws IOException, ChannelException, NoTaskLocationException
  {
    return submitRequest(
        taskId,
        MediaType.APPLICATION_JSON,
        method,
        encodedPathSuffix,
        encodedQueryString,
        content,
        retry
    );
  }
1005708
public void startTask(int id, String taskName) {
        if (isActivated) {
            durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));
        }
    }
636330
public Task startTask(String taskId, boolean beginConversation) {
    if(beginConversation) {
      Conversation conversation = conversationInstance.get();
      if(conversation.isTransient()) {
       conversation.begin();
      }
    }
    return startTask(taskId);
  }
381589
public Task pollTask(String taskType, String workerId, String domain) {
        Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(domain), "Domain cannot be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(workerId), "Worker id cannot be blank");

        TaskServicePb.PollResponse response = stub.poll(
                TaskServicePb.PollRequest.newBuilder()
                .setTaskType(taskType)
                .setWorkerId(workerId)
                .setDomain(domain)
                .build()
        );
        return protoMapper.fromProto(response.getTask());
    }
356715
public synchronized void notifyTaskCompletion(long jobId, int taskId, Object result) {
    Pair<Long, Integer> id = new Pair<>(jobId, taskId);
    TaskInfo.Builder taskInfo = mUnfinishedTasks.get(id);
    taskInfo.setStatus(Status.COMPLETED);
    try {
      taskInfo.setResult(ByteString.copyFrom(SerializationUtils.serialize(result)));
    } catch (IOException e) {
      // TODO(yupeng) better error handling
      LOG.warn("Failed to serialize {} : {}", result, e.getMessage());
      LOG.debug("Exception: ", e);
    } finally {
      finishTask(id);
      LOG.info("Task {} for job {} completed.", taskId, jobId);
    }
  }
1249784
def approve_task(self, task_id):
        
        uri = 'tasks/%s' % task_id

        data = {"approved": True}

        resp, body = self.post(uri, json.dumps(data))
        self.expected_success(200, resp.status)
        body = json.loads(body)
        return rest_client.ResponseBody(resp, body)
387866
protected void executeSendCommandWithNoResponse(SendCommandTask task)
        throws PDUException, IOException {

        int seqNum = sequence.nextValue();
        try {
            task.executeTask(connection().getOutputStream(), seqNum);
        } catch (IOException e) {
            logger.error("Failed sending " + task.getCommandName() + " command", e);
            close();
            throw e;
        }
    }
196482
public Task getTaskDetails(String taskId) {
        Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank");
        return getForEntity("tasks/{taskId}", null, Task.class, taskId);
    }
121490
public synchronized void done(TaskAttemptID taskid)
  throws IOException {
    TaskInProgress tip = tasks.get(taskid);
    commitResponses.remove(taskid);
    if (tip != null) {
      tip.reportDone();
    } else {
      LOG.warn("Unknown child task done: "+taskid+". Ignored.");
    }
  }
1170462
public OvhIpTask ip_task_taskId_GET(String ip, Long taskId) throws IOException {
		String qPath = "/ip/{ip}/task/{taskId}";
		StringBuilder sb = path(qPath, ip, taskId);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhIpTask.class);
	}