com.google.api.client.http.MultipartContent Java Examples

The following examples show how to use com.google.api.client.http.MultipartContent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Attachments.java    From java-asana with MIT License 6 votes vote down vote up
/**
 * Upload a file and attach it to a task
 *
 * @param task        Globally unique identifier for the task.
 * @param fileContent Content of the file to be uploaded
 * @param fileName    Name of the file to be uploaded
 * @param fileType    MIME type of the file to be uploaded
 * @return Request object
 */
public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {
    MultipartContent.Part part = new MultipartContent.Part()
            .setContent(new InputStreamContent(fileType, fileContent))
            .setHeaders(new HttpHeaders().set(
                    "Content-Disposition",
                    String.format("form-data; name=\"file\"; filename=\"%s\"", fileName) // TODO: escape fileName?
            ));
    MultipartContent content = new MultipartContent()
            .setMediaType(new HttpMediaType("multipart/form-data").setParameter("boundary", UUID.randomUUID().toString()))
            .addPart(part);

    String path = String.format("/tasks/%s/attachments", task);
    return new ItemRequest<Attachment>(this, Attachment.class, path, "POST")
            .data(content);
}
 
Example #2
Source File: GoogleCloudStorageIntegrationHelper.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/** Convert request to string representation that could be used for assertions in tests */
public static String requestToString(HttpRequest request) {
  String method = request.getRequestMethod();
  String url = request.getUrl().toString();
  String requestString = method + ":" + url;
  if ("POST".equals(method) && url.contains("uploadType=multipart")) {
    MultipartContent content = (MultipartContent) request.getContent();
    JsonHttpContent jsonRequest =
        (JsonHttpContent) Iterables.get(content.getParts(), 0).getContent();
    String objectName = ((StorageObject) jsonRequest.getData()).getName();
    requestString += ":" + objectName;
  }
  return requestString;
}
 
Example #3
Source File: MediaHttpUploader.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Direct Uploads the media.
 *
 * @param initiationRequestUrl The request URL where the initiation request will be sent
 * @return HTTP response
 */
private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException {
  updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS);

  HttpContent content = mediaContent;
  if (metadata != null) {
    content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent));
    initiationRequestUrl.put("uploadType", "multipart");
  } else {
    initiationRequestUrl.put("uploadType", "media");
  }
  HttpRequest request =
      requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
  request.getHeaders().putAll(initiationHeaders);
  // We do not have to do anything special here if media content length is unspecified because
  // direct media upload works even when the media content length == -1.
  HttpResponse response = executeCurrentRequest(request);
  boolean responseProcessed = false;
  try {
    if (isMediaLengthKnown()) {
      totalBytesServerReceived = getMediaContentLength();
    }
    updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE);
    responseProcessed = true;
  } finally {
    if (!responseProcessed) {
      response.disconnect();
    }
  }
  return response;
}
 
Example #4
Source File: BatchRequest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks.
 *
 * <p>
 * Calling {@link #execute()} executes and clears the queued requests. This means that the
 * {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests
 * again.
 * </p>
 */
public void execute() throws IOException {
  boolean retryAllowed;
  Preconditions.checkState(!requestInfos.isEmpty());

  // Log a warning if the user is using the global batch endpoint. In the future, we can turn this
  // into a preconditions check.
  if (GLOBAL_BATCH_ENDPOINT.equals(this.batchUrl.toString())) {
    LOGGER.log(Level.WARNING, GLOBAL_BATCH_ENDPOINT_WARNING);
  }

  HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null);
  // NOTE: batch does not support gzip encoding
  HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor();
  batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor));
  int retriesRemaining = batchRequest.getNumberOfRetries();

  do {
    retryAllowed = retriesRemaining > 0;
    MultipartContent batchContent = new MultipartContent();
    batchContent.getMediaType().setSubType("mixed");
    int contentId = 1;
    for (RequestInfo<?, ?> requestInfo : requestInfos) {
      batchContent.addPart(new MultipartContent.Part(
          new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++),
          new HttpRequestContent(requestInfo.request)));
    }
    batchRequest.setContent(batchContent);
    HttpResponse response = batchRequest.execute();
    BatchUnparsedResponse batchResponse;
    try {
      // Find the boundary from the Content-Type header.
      String boundary = "--" + response.getMediaType().getParameter("boundary");

      // Parse the content stream.
      InputStream contentStream = response.getContent();
      batchResponse =
          new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed);

      while (batchResponse.hasNext) {
        batchResponse.parseNextResponse();
      }
    } finally {
      response.disconnect();
    }

    List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos;
    if (!unsuccessfulRequestInfos.isEmpty()) {
      requestInfos = unsuccessfulRequestInfos;
    } else {
      break;
    }
    retriesRemaining--;
  } while (retryAllowed);
  requestInfos.clear();
}