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

The following examples show how to use com.google.api.client.http.InputStreamContent. 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: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testDirectMediaUploadWithMetadata() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.directUploadEnabled = true;
  fakeTransport.directUploadWithMetadata = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.setProgressListener(new DirectProgressListener());
  // Enable direct media upload.
  uploader.setDirectUploadEnabled(true);
  // Set Metadata
  uploader.setMetadata(new MockHttpContent());

  HttpResponse response = uploader.upload(new GenericUrl(TEST_MULTIPART_REQUEST_URL));
  assertEquals(200, response.getStatusCode());

  // There should be only 1 call made for direct media upload.
  assertEquals(1, fakeTransport.lowLevelExecCalls);
}
 
Example #2
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testResumable_BadResponse() throws IOException {
  int contentLength = 3;
  ResumableErrorMediaTransport fakeTransport = new ResumableErrorMediaTransport();
  byte[] testedData = new byte[contentLength];
  new Random().nextBytes(testedData);
  TestingInputStream is = new TestingInputStream(testedData);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader =
      new MediaHttpUploader(mediaContent, fakeTransport, new ZeroBackOffRequestInitializer());

  // disable GZip - so we would be able to test byte received by server.
  uploader.setDisableGZipContent(true);
  HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
  assertEquals(500, response.getStatusCode());

  assertTrue("input stream should be closed", is.isClosed);
}
 
Example #3
Source File: UserApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public HttpResponse updateUserForHttpResponse(String username, java.io.InputStream body, String mediaType) throws IOException {
    // verify the required parameter 'username' is set
        if (username == null) {
        throw new IllegalArgumentException("Missing the required parameter 'username' when calling updateUser");
        }// verify the required parameter 'body' is set
        if (body == null) {
        throw new IllegalArgumentException("Missing the required parameter 'body' when calling updateUser");
        }
            // create a map of path variables
            final Map<String, Object> uriVariables = new HashMap<String, Object>();
                uriVariables.put("username", username);
        UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}");

        String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
        GenericUrl genericUrl = new GenericUrl(localVarUrl);

        HttpContent content = body == null ?
          apiClient.new JacksonJsonHttpContent(null) :
          new InputStreamContent(mediaType == null ? Json.MEDIA_TYPE : mediaType, body);
        return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PUT, genericUrl, content).execute();
}
 
Example #4
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void indexItemAndContent_emptyInputStreamContentIsUploaded() throws Exception {
  this.transport.addUploadItemsReqResp(
      SOURCE_ID, GOOD_ID, new UploadItemRef().setName(testName.getMethodName()));
  Item item = new Item().setName(GOOD_ID);
  InputStreamContent content =
      new InputStreamContent("text/html", new ByteArrayInputStream(new byte[0]));
  when(contentUploadService.uploadContent(testName.getMethodName(), content))
      .thenReturn(Futures.immediateFuture(null));

  this.indexingService.indexItemAndContent(
      item, content, null, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS);

  assertEquals(
      new ItemContent()
          .setContentDataRef(new UploadItemRef().setName(testName.getMethodName()))
          .setContentFormat("TEXT"),
      item.getContent());
  verify(quotaServer, times(2)).acquire(Operations.DEFAULT);
}
 
Example #5
Source File: GoogleBloggerImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String uploadImage(ASObject imageObject, Drive driveService, String parentFolderId)
    throws IOException {
  String url;
  String description = null;
  // The image property can either be an object, or just a URL, handle both cases.
  if ("Image".equalsIgnoreCase(imageObject.objectTypeString())) {
    url = imageObject.firstUrl().toString();
    if (imageObject.displayName() != null) {
      description = imageObject.displayNameString();
    }
  } else {
    url = imageObject.toString();
  }
  if (description == null) {
    description = "Imported photo from: " + url;
  }
  HttpURLConnection conn = imageStreamProvider.getConnection(url);
  InputStream inputStream = conn.getInputStream();
  File driveFile = new File().setName(description).setParents(ImmutableList.of(parentFolderId));
  InputStreamContent content = new InputStreamContent(null, inputStream);
  File newFile = driveService.files().create(driveFile, content).setFields("id").execute();

  return "https://drive.google.com/thumbnail?id=" + newFile.getId();
}
 
Example #6
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testDirectMediaUploadWithMetadata_WithNoContentSizeProvided() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.directUploadEnabled = true;
  fakeTransport.contentLengthNotSpecified = true;
  fakeTransport.directUploadWithMetadata = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  DirectProgressListener listener = new DirectProgressListener();
  listener.contentLengthNotSpecified = true;
  uploader.setProgressListener(listener);
  // Enable direct media upload.
  uploader.setDirectUploadEnabled(true);
  // Set Metadata
  uploader.setMetadata(new MockHttpContent());

  HttpResponse response = uploader.upload(new GenericUrl(TEST_MULTIPART_REQUEST_URL));
  assertEquals(200, response.getStatusCode());

  // There should be only 1 call made for direct media upload.
  assertEquals(1, fakeTransport.lowLevelExecCalls);
}
 
Example #7
Source File: DriveImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String importSingleFile(
    UUID jobId, Drive driveInterface, DigitalDocumentWrapper file, String parentId)
    throws IOException {
  InputStreamContent content =
      new InputStreamContent(
          null, jobStore.getStream(jobId, file.getCachedContentId()).getStream());
  DtpDigitalDocument dtpDigitalDocument = file.getDtpDigitalDocument();
  File driveFile = new File().setName(dtpDigitalDocument.getName());
  if (!Strings.isNullOrEmpty(parentId)) {
    driveFile.setParents(ImmutableList.of(parentId));
  }
  if (!Strings.isNullOrEmpty(dtpDigitalDocument.getDateModified())) {
    driveFile.setModifiedTime(DateTime.parseRfc3339(dtpDigitalDocument.getDateModified()));
  }
  if (!Strings.isNullOrEmpty(file.getOriginalEncodingFormat())
      && file.getOriginalEncodingFormat().startsWith("application/vnd.google-apps.")) {
    driveFile.setMimeType(file.getOriginalEncodingFormat());
  }
  return driveInterface.files().create(driveFile, content).execute().getId();
}
 
Example #8
Source File: GitGCSSyncApp.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
private void recursiveGCSSync(File repo, String prefix, Storage gcs) throws IOException {
  for (String name : repo.list()) {
    if (!name.equals(".git")) {
      File file = new File(repo.getPath(), name);
      if (file.isDirectory()) {
        recursiveGCSSync(file, prefix + file.getName() + "/", gcs);
      } else {
        InputStream inputStream = new FileInputStream(repo.getPath() + "/" + file.getName());
        InputStreamContent mediaContent = new InputStreamContent("text/plain", inputStream);
        mediaContent.setLength(file.length());
        StorageObject objectMetadata = new StorageObject()
            .setName(prefix + file.getName());
        gcs.objects().insert(bucket, objectMetadata, mediaContent).execute();
      }
    }
  }
}
 
Example #9
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 #10
Source File: StorageHandler.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
/**
 * Method to insert a image into the bucket of the cloud storage.
 *
 * @author <a href="mailto:[email protected]"> João Felipe de Medeiros Moreira </a>
 * @since 15/10/2015
 *
 * @param name of the image.
 * @param contentStream to be converted.
 *
 * @return the media link of the image.
 *
 * @throws IOException in case a IO problem.
 * @throws GeneralSecurityException in case a security problem.
 */
public static String saveImage(String name, InputStreamContent contentStream)
    throws IOException, GeneralSecurityException {
  logger.finest("###### Saving a image");
  StorageObject objectMetadata = new StorageObject()
      // Set the destination object name
      .setName(name)
      // Set the access control list to publicly read-only
      .setAcl(Arrays.asList(new ObjectAccessControl().setEntity(ALL_USERS).setRole(READER)));

  Storage client = getService();
  String bucketName = getBucket().getName();
  Storage.Objects.Insert insertRequest =
      client.objects().insert(bucketName, objectMetadata, contentStream);

  return insertRequest.execute().getMediaLink();
}
 
Example #11
Source File: StorageSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Uploads data to an object in a bucket.
 *
 * @param name the name of the destination object.
 * @param contentType the MIME type of the data.
 * @param file the file to upload.
 * @param bucketName the name of the bucket to create the object in.
 */
public static void uploadFile(String name, String contentType, File file, String bucketName)
    throws IOException, GeneralSecurityException {
  InputStreamContent contentStream =
      new InputStreamContent(contentType, new FileInputStream(file));
  // Setting the length improves upload performance
  contentStream.setLength(file.length());
  StorageObject objectMetadata =
      new StorageObject()
          // Set the destination object name
          .setName(name)
          // Set the access control list to publicly read-only
          .setAcl(
              Arrays.asList(new ObjectAccessControl().setEntity("allUsers").setRole("READER")));

  // Do the insert
  Storage client = StorageFactory.getService();
  Storage.Objects.Insert insertRequest =
      client.objects().insert(bucketName, objectMetadata, contentStream);

  insertRequest.execute();
}
 
Example #12
Source File: GoogleStorageCacheManager.java    From simpleci with MIT License 6 votes vote down vote up
@Override
public void uploadCache(JobOutputProcessor outputProcessor, String cachePath) {
    try {
            outputProcessor.output("Uploading cache file " + cacheFileName + " to google storage\n");

            Storage client = createClient();
            File uploadFile = new File(cachePath);
            InputStreamContent contentStream = new InputStreamContent(
                    null, new FileInputStream(uploadFile));
            contentStream.setLength(uploadFile.length());
            StorageObject objectMetadata = new StorageObject()
                    .setName(cacheFileName);

            Storage.Objects.Insert insertRequest = client.objects().insert(
                    settings.bucketName, objectMetadata, contentStream);

            insertRequest.execute();

            outputProcessor.output("Cache uploaded\n");
    } catch (GeneralSecurityException | IOException e) {
        outputProcessor.output("Error upload cache: " + e.getMessage() + "\n");
    }
}
 
Example #13
Source File: AbstractGoogleAsyncWriteChannel.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
@Override
public void startUpload(InputStream pipeSource) throws IOException {
  // Connect pipe-source to the stream used by uploader.
  InputStreamContent objectContentStream = new InputStreamContent(contentType, pipeSource);
  // Indicate that we do not know length of file in advance.
  objectContentStream.setLength(-1);
  objectContentStream.setCloseInputStream(false);

  T request = createRequest(objectContentStream);
  request.setDisableGZipContent(true);

  // Change chunk size from default value (10MB) to one that yields higher performance.
  clientRequestHelper.setChunkSize(request, options.getUploadChunkSize());

  // Given that the two ends of the pipe must operate asynchronous relative
  // to each other, we need to start the upload operation on a separate thread.
  uploadOperation = threadPool.submit(new UploadOperation(request, pipeSource));
}
 
Example #14
Source File: GoogleCloudStorageWriteChannel.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
@Override
public Insert createRequest(InputStreamContent inputStream) throws IOException {
  // Create object with the given name and metadata.
  StorageObject object =
      new StorageObject()
          .setContentEncoding(contentEncoding)
          .setMetadata(metadata)
          .setName(objectName);

  Insert insert = gcs.objects().insert(bucketName, object, inputStream);
  writeConditions.apply(insert);
  if (insert.getMediaHttpUploader() != null) {
    insert.getMediaHttpUploader().setDirectUploadEnabled(isDirectUploadEnabled());
    insert.getMediaHttpUploader().setProgressListener(
      new LoggingMediaHttpUploaderProgressListener(this.objectName, MIN_LOGGING_INTERVAL_MS));
  }
  insert.setName(objectName);
  if (kmsKeyName != null) {
    insert.setKmsKeyName(kmsKeyName);
  }
  return insert;
}
 
Example #15
Source File: GoogleCloudStorageWriteChannelTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void createRequest_shouldSetKmsKeyName() throws IOException {
  String kmsKeyName = "testKmsKey";

  GoogleCloudStorageWriteChannel writeChannel =
      new GoogleCloudStorageWriteChannel(
          MoreExecutors.newDirectExecutorService(),
          new Storage(HTTP_TRANSPORT, JSON_FACTORY, r -> {}),
          new ClientRequestHelper<>(),
          BUCKET_NAME,
          OBJECT_NAME,
          "content-type",
          /* contentEncoding= */ null,
          kmsKeyName,
          AsyncWriteChannelOptions.DEFAULT,
          new ObjectWriteConditions(),
          /* objectMetadata= */ null);

  Storage.Objects.Insert request =
      writeChannel.createRequest(
          new InputStreamContent("plain/text", new ByteArrayInputStream(new byte[0])));

  assertThat(request.getKmsKeyName()).isEqualTo(kmsKeyName);
}
 
Example #16
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testUploadMultipleCalls_WithNoContentSizeProvidedChunkedInput() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 5;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.contentLengthNotSpecified = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]) {
      @Override
    public synchronized int read(byte[] b, int off, int len) {
      return super.read(b, off, Math.min(len, MediaHttpUploader.DEFAULT_CHUNK_SIZE / 10));
    }
  };
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));

  // There should be 6 calls made. 1 initiation request and 5 upload requests.
  assertEquals(6, fakeTransport.lowLevelExecCalls);
}
 
Example #17
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testUploadServerError_WithoutUnsuccessfulHandler() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.testServerError = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);

  HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
  assertEquals(500, response.getStatusCode());

  // There should be 3 calls made. 1 initiation request, 1 successful upload request and 1 upload
  // request with server error
  assertEquals(3, fakeTransport.lowLevelExecCalls);
}
 
Example #18
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testUploadIOException_WithoutIOExceptionHandler() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.testIOException = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);

  try {
    uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
    fail("expected " + IOException.class);
  } catch (IOException e) {
    // There should be 3 calls made. 1 initiation request, 1 successful upload request,
    // and 1 upload request with server error
    assertEquals(3, fakeTransport.lowLevelExecCalls);
  }
}
 
Example #19
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testUploadServerErrorWithBackOffDisabled_WithNoContentSizeProvided()
    throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.testServerError = true;
  fakeTransport.contentLengthNotSpecified = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);

  HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
  assertEquals(500, response.getStatusCode());

  // There should be 3 calls made. 1 initiation request, 1 successful upload request and 1 upload
  // request with server error
  assertEquals(3, fakeTransport.lowLevelExecCalls);
}
 
Example #20
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testDirectMediaUpload() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.directUploadEnabled = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.setProgressListener(new DirectProgressListener());
  // Enable direct media upload.
  uploader.setDirectUploadEnabled(true);

  HttpResponse response = uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));
  assertEquals(200, response.getStatusCode());

  // There should be only 1 call made for direct media upload.
  assertEquals(1, fakeTransport.lowLevelExecCalls);
}
 
Example #21
Source File: NetHttpRequestTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterruptedWriteWithResponse() throws Exception {
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)) {
        @Override
        public OutputStream getOutputStream() throws IOException {
          return new OutputStream() {
            @Override
            public void write(int b) throws IOException {
              throw new IOException("Error writing request body to server");
            }
          };
        }
      };
  connection.setResponseCode(401);
  connection.setRequestMethod("POST");
  NetHttpRequest request = new NetHttpRequest(connection);
  InputStream is = NetHttpRequestTest.class.getClassLoader().getResourceAsStream("file.txt");
  HttpContent content = new InputStreamContent("text/plain", is);
  request.setStreamingContent(content);

  LowLevelHttpResponse response = request.execute();
  assertEquals(401, response.getStatusCode());
}
 
Example #22
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testDirectMediaUpload_WithSpecifiedHeader() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.directUploadEnabled = true;
  fakeTransport.assertTestHeaders = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.getInitiationHeaders().set("test-header-name", "test-header-value");
  uploader.setProgressListener(new DirectProgressListener());
  // Enable direct media upload.
  uploader.setDirectUploadEnabled(true);

  HttpResponse response = uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));
  assertEquals(200, response.getStatusCode());

  // There should be only 1 call made for direct media upload.
  assertEquals(1, fakeTransport.lowLevelExecCalls);
}
 
Example #23
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testDirectMediaUpload_WithNoContentSizeProvided() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.directUploadEnabled = true;
  fakeTransport.contentLengthNotSpecified = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  DirectProgressListener listener = new DirectProgressListener();
  listener.contentLengthNotSpecified = true;
  uploader.setProgressListener(listener);
  // Enable direct media upload.
  uploader.setDirectUploadEnabled(true);

  HttpResponse response = uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));
  assertEquals(200, response.getStatusCode());

  // There should be only 1 call made for direct media upload.
  assertEquals(1, fakeTransport.lowLevelExecCalls);
}
 
Example #24
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void indexItemAndContent_largeContentIsUploaded() throws Exception {
  this.transport.addUploadItemsReqResp(
      SOURCE_ID, GOOD_ID, new UploadItemRef().setName(testName.getMethodName()));
  Item item = new Item().setName(GOOD_ID);
  InputStreamContent content =
      new InputStreamContent(
          "text/html", new ByteArrayInputStream("Hello World.".getBytes(UTF_8)));
  when(contentUploadService.uploadContent(testName.getMethodName(), content))
      .thenReturn(Futures.immediateFuture(null));

  this.indexingService.indexItemAndContent(
      item, content, null, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS);

  assertEquals(
      new ItemContent()
          .setContentDataRef(new UploadItemRef().setName(testName.getMethodName()))
          .setContentFormat("TEXT"),
      item.getContent());
  verify(quotaServer, times(2)).acquire(Operations.DEFAULT);
}
 
Example #25
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testUploadOneCall_WithContentSizeProvided() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader =
      new MediaHttpUploader(mediaContent, fakeTransport, new GZipCheckerInitializer(true));
  uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));

  // There should be 2 calls made. 1 initiation request and 1 upload request.
  assertEquals(2, fakeTransport.lowLevelExecCalls);
}
 
Example #26
Source File: AbstractGoogleClientTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testMediaUpload_disableGZip() throws Exception {
  MediaTransport transport = new MediaTransport();
  transport.contentLengthNotSpecified = true;
  AbstractGoogleClient client = new MockGoogleClient.Builder(
      transport, TEST_RESUMABLE_REQUEST_URL, "", JSON_OBJECT_PARSER,
      new GZipCheckerInitializer(true)).setApplicationName("Test Application").build();
  InputStream is = new ByteArrayInputStream(new byte[MediaHttpUploader.DEFAULT_CHUNK_SIZE]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  MockGoogleClientRequest<A> rq =
      new MockGoogleClientRequest<A>(client, "POST", "", null, A.class);
  rq.initializeMediaUpload(mediaContent);
  rq.setDisableGZipContent(true);
  A result = rq.execute();
  assertEquals("somevalue", result.foo);
}
 
Example #27
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testUploadMultipleCalls_WithPatch() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 5;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.testMethodOverride = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.setInitiationRequestMethod(HttpMethods.PATCH);
  uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));

  // There should be 6 calls made. 1 initiation request and 5 upload requests.
  assertEquals(6, fakeTransport.lowLevelExecCalls);
}
 
Example #28
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testUploadOneCall_WithNoContentSizeProvided() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.contentLengthNotSpecified = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));

  // There should be 2 calls made. 1 initiation request and 1 upload request.
  assertEquals(2, fakeTransport.lowLevelExecCalls);
}
 
Example #29
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testUploadMultipleCalls_WithSpecifiedHeader() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 5;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.assertTestHeaders = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
  uploader.getInitiationHeaders().set("test-header-name", "test-header-value");
  uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));

  // There should be 6 calls made. 1 initiation request and 5 upload requests.
  assertEquals(6, fakeTransport.lowLevelExecCalls);
}
 
Example #30
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testUploadOneCall_WithDefaultGzip() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  fakeTransport.contentLengthNotSpecified = true;

  // GZip content must be disabled by default.
  MediaHttpUploader uploader =
      new MediaHttpUploader(mediaContent, fakeTransport, new GZipCheckerInitializer(false));
  uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
  // There should be 2 calls made. 1 initiation request and 1 upload request.
  assertEquals(2, fakeTransport.lowLevelExecCalls);
}