Java Code Examples for com.google.api.client.json.GenericJson#setFactory()

The following examples show how to use com.google.api.client.json.GenericJson#setFactory() . 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: GoogleCredentialTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
static String createUserJson(String clientId, String clientSecret, String refreshToken)
    throws IOException {
  GenericJson userCredentialContents = new GenericJson();
  userCredentialContents.setFactory(JSON_FACTORY);
  if (clientId != null) {
    userCredentialContents.put("client_id", clientId);
  }
  if (clientSecret != null) {
    userCredentialContents.put("client_secret", clientSecret);
  }
  if (refreshToken != null) {
    userCredentialContents.put("refresh_token", refreshToken);
  }
  userCredentialContents.put("type", GoogleCredential.USER_FILE_TYPE);
  String json = userCredentialContents.toPrettyString();
  return json;
}
 
Example 2
Source File: GoogleCredentialTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testFromStreamServiceAccountMissingPrivateKeyIdThrows() throws IOException {
  final String serviceAccountId =
      "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com";
  final String serviceAccountEmail =
      "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com";

  MockHttpTransport transport = new MockTokenServerTransport();

  // Write out user file
  GenericJson serviceAccountContents = new GenericJson();
  serviceAccountContents.setFactory(JSON_FACTORY);
  serviceAccountContents.put("client_id", serviceAccountId);
  serviceAccountContents.put("client_email", serviceAccountEmail);
  serviceAccountContents.put("private_key", SA_KEY_TEXT);
  serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE);
  String json = serviceAccountContents.toPrettyString();
  InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes());

  try {
    GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY);
    fail();
  } catch (IOException expected) {
    assertTrue(expected.getMessage().contains("private_key_id"));
  }
}
 
Example 3
Source File: GoogleCredentialTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testFromStreamServiceAccountMissingPrivateKeyThrows() throws IOException {
  final String serviceAccountId =
      "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com";
  final String serviceAccountEmail =
      "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com";

  MockHttpTransport transport = new MockTokenServerTransport();

  // Write out user file
  GenericJson serviceAccountContents = new GenericJson();
  serviceAccountContents.setFactory(JSON_FACTORY);
  serviceAccountContents.put("client_id", serviceAccountId);
  serviceAccountContents.put("client_email", serviceAccountEmail);
  serviceAccountContents.put("private_key_id", SA_KEY_ID);
  serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE);
  String json = serviceAccountContents.toPrettyString();
  InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes());

  try {
    GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY);
    fail();
  } catch (IOException expected) {
    assertTrue(expected.getMessage().contains("private_key"));
  }
}
 
Example 4
Source File: GoogleCredentialTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testFromStreamServiceAccountMissingClientEmailThrows() throws IOException {
  final String serviceAccountId =
      "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com";

  MockHttpTransport transport = new MockTokenServerTransport();

  // Write out user file
  GenericJson serviceAccountContents = new GenericJson();
  serviceAccountContents.setFactory(JSON_FACTORY);
  serviceAccountContents.put("client_id", serviceAccountId);
  serviceAccountContents.put("private_key", SA_KEY_TEXT);
  serviceAccountContents.put("private_key_id", SA_KEY_ID);
  serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE);
  String json = serviceAccountContents.toPrettyString();
  InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes());

  try {
    GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY);
    fail();
  } catch (IOException expected) {
    assertTrue(expected.getMessage().contains("client_email"));
  }
}
 
Example 5
Source File: GoogleCredentialTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testFromStreamServiceAccountMissingClientIdThrows() throws IOException {
  final String serviceAccountEmail =
      "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com";

  MockHttpTransport transport = new MockTokenServerTransport();

  // Write out user file
  GenericJson serviceAccountContents = new GenericJson();
  serviceAccountContents.setFactory(JSON_FACTORY);
  serviceAccountContents.put("client_email", serviceAccountEmail);
  serviceAccountContents.put("private_key", SA_KEY_TEXT);
  serviceAccountContents.put("private_key_id", SA_KEY_ID);
  serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE);
  String json = serviceAccountContents.toPrettyString();
  InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes());

  try {
    GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY);
    fail();
  } catch (IOException expected) {
    assertTrue(expected.getMessage().contains("client_id"));
  }
}
 
Example 6
Source File: MockHttpTransportHelper.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
public static MockLowLevelHttpResponse jsonErrorResponse(ErrorResponses errorResponse)
    throws IOException {
  GoogleJsonError.ErrorInfo errorInfo = new GoogleJsonError.ErrorInfo();
  errorInfo.setReason(errorResponse.getErrorReason());
  errorInfo.setDomain(errorResponse.getErrorDomain());
  errorInfo.setFactory(JSON_FACTORY);

  GoogleJsonError jsonError = new GoogleJsonError();
  jsonError.setCode(errorResponse.getErrorCode());
  jsonError.setErrors(ImmutableList.of(errorInfo));
  jsonError.setMessage(errorResponse.getErrorMessage());
  jsonError.setFactory(JSON_FACTORY);

  GenericJson errorResponseJson = new GenericJson();
  errorResponseJson.set("error", jsonError);
  errorResponseJson.setFactory(JSON_FACTORY);

  return new MockLowLevelHttpResponse()
      .setContent(errorResponseJson.toPrettyString())
      .setContentType(Json.MEDIA_TYPE)
      .setStatusCode(errorResponse.getResponseCode());
}
 
Example 7
Source File: ApiErrorExtractorTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
private static GoogleJsonResponseException googleJsonResponseException(
    int status, ErrorInfo errorInfo, String httpStatusString) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          errorInfo.setFactory(jsonFactory);
          GoogleJsonError jsonError = new GoogleJsonError();
          jsonError.setCode(status);
          jsonError.setErrors(Collections.singletonList(errorInfo));
          jsonError.setMessage(httpStatusString);
          jsonError.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", jsonError);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example 8
Source File: GoogleCredentialTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFromStreamServiceAccountAlternateTokenUri() throws IOException {
  final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
  final String serviceAccountId =
      "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com";
  final String serviceAccountEmail =
      "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com";

  final String tokenServerUrl = "http://another.auth.com/token";
  MockTokenServerTransport transport = new MockTokenServerTransport(tokenServerUrl);
  transport.addServiceAccount(serviceAccountEmail, accessToken);

  // Write out user file
  GenericJson serviceAccountContents = new GenericJson();
  serviceAccountContents.setFactory(JSON_FACTORY);
  serviceAccountContents.put("client_id", serviceAccountId);
  serviceAccountContents.put("client_email", serviceAccountEmail);
  serviceAccountContents.put("private_key", SA_KEY_TEXT);
  serviceAccountContents.put("private_key_id", SA_KEY_ID);
  serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE);
  serviceAccountContents.put("token_uri", tokenServerUrl);
  String json = serviceAccountContents.toPrettyString();
  InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes());

  GoogleCredential defaultCredential = GoogleCredential
      .fromStream(serviceAccountStream, transport, JSON_FACTORY);
  assertNotNull(defaultCredential);
  assertEquals(tokenServerUrl, defaultCredential.getTokenServerEncodedUrl());
  defaultCredential = defaultCredential.createScoped(SCOPES);
  assertEquals(tokenServerUrl, defaultCredential.getTokenServerEncodedUrl());

  assertTrue(defaultCredential.refreshToken());
  assertEquals(accessToken, defaultCredential.getAccessToken());
}
 
Example 9
Source File: GoogleCredentialTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFromStreamServiceAccount() throws IOException {
  final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
  final String serviceAccountId =
      "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com";
  final String serviceAccountEmail =
      "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com";

  MockTokenServerTransport transport = new MockTokenServerTransport();
  transport.addServiceAccount(serviceAccountEmail, accessToken);

  // Write out user file
  GenericJson serviceAccountContents = new GenericJson();
  serviceAccountContents.setFactory(JSON_FACTORY);
  serviceAccountContents.put("client_id", serviceAccountId);
  serviceAccountContents.put("client_email", serviceAccountEmail);
  serviceAccountContents.put("private_key", SA_KEY_TEXT);
  serviceAccountContents.put("private_key_id", SA_KEY_ID);
  serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE);
  String json = serviceAccountContents.toPrettyString();
  InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes());

  GoogleCredential defaultCredential = GoogleCredential
      .fromStream(serviceAccountStream, transport, JSON_FACTORY);
  assertNotNull(defaultCredential);
  defaultCredential = defaultCredential.createScoped(SCOPES);

  assertTrue(defaultCredential.refreshToken());
  assertEquals(accessToken, defaultCredential.getAccessToken());
}
 
Example 10
Source File: CoreSocketFactoryTest.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 5 votes vote down vote up
private static GoogleJsonResponseException fakeGoogleJsonResponseException(
    int status, ErrorInfo errorInfo, String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          errorInfo.setFactory(jsonFactory);
          GoogleJsonError jsonError = new GoogleJsonError();
          jsonError.setCode(status);
          jsonError.setErrors(Collections.singletonList(errorInfo));
          jsonError.setMessage(message);
          jsonError.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", jsonError);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example 11
Source File: PackageUtilTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/** Builds a fake GoogleJsonResponseException for testing API error handling. */
private static GoogleJsonResponseException googleJsonResponseException(
    final int status, final String reason, final String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          ErrorInfo errorInfo = new ErrorInfo();
          errorInfo.setReason(reason);
          errorInfo.setMessage(message);
          errorInfo.setFactory(jsonFactory);
          GenericJson error = new GenericJson();
          error.set("code", status);
          error.set("errors", Arrays.asList(errorInfo));
          error.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", error);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example 12
Source File: GcsUtilTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/** Builds a fake GoogleJsonResponseException for testing API error handling. */
private static GoogleJsonResponseException googleJsonResponseException(
    final int status, final String reason, final String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          ErrorInfo errorInfo = new ErrorInfo();
          errorInfo.setReason(reason);
          errorInfo.setMessage(message);
          errorInfo.setFactory(jsonFactory);
          GenericJson error = new GenericJson();
          error.set("code", status);
          error.set("errors", Arrays.asList(errorInfo));
          error.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", error);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example 13
Source File: GcsUtilTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSizeBytesWhenFileNotFoundBatch() throws Exception {
  JsonFactory jsonFactory = new JacksonFactory();

  String contentBoundary = "batch_foobarbaz";
  String contentBoundaryLine = "--" + contentBoundary;
  String endOfContentBoundaryLine = "--" + contentBoundary + "--";

  GenericJson error = new GenericJson().set("error", new GenericJson().set("code", 404));
  error.setFactory(jsonFactory);

  String content =
      contentBoundaryLine
          + "\n"
          + "Content-Type: application/http\n"
          + "\n"
          + "HTTP/1.1 404 Not Found\n"
          + "Content-Length: -1\n"
          + "\n"
          + error.toString()
          + "\n"
          + "\n"
          + endOfContentBoundaryLine
          + "\n";
  thrown.expect(FileNotFoundException.class);
  MockLowLevelHttpResponse notFoundResponse =
      new MockLowLevelHttpResponse()
          .setContentType("multipart/mixed; boundary=" + contentBoundary)
          .setContent(content)
          .setStatusCode(HttpStatusCodes.STATUS_CODE_OK);

  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder().setLowLevelHttpResponse(notFoundResponse).build();

  GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil();

  gcsUtil.setStorageClient(new Storage(mockTransport, Transport.getJsonFactory(), null));
  gcsUtil.fileSizes(ImmutableList.of(GcsPath.fromComponents("testbucket", "testobject")));
}
 
Example 14
Source File: MockTokenServerTransport.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
private MockLowLevelHttpRequest buildTokenRequest(String url) {
  return new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      String content = this.getContentAsString();
      Map<String, String> query = TestUtils.parseQuery(content);
      String accessToken = null;

      String foundId = query.get("client_id");
      if (foundId != null) {
        if (!clients.containsKey(foundId)) {
          throw new IOException("Client ID not found.");
        }
        String foundSecret = query.get("client_secret");
        String expectedSecret = clients.get(foundId);
        if (foundSecret == null || !foundSecret.equals(expectedSecret)) {
          throw new IOException("Client secret not found.");
        }
        String foundRefresh = query.get("refresh_token");
        if (!refreshTokens.containsKey(foundRefresh)) {
          throw new IOException("Refresh Token not found.");
        }
        accessToken = refreshTokens.get(foundRefresh);
      } else if (query.containsKey("grant_type")) {
        String grantType = query.get("grant_type");
        if (!EXPECTED_GRANT_TYPE.equals(grantType)) {
          throw new IOException("Unexpected Grant Type.");
        }
        String assertion = query.get("assertion");
        JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion);
        String foundEmail = signature.getPayload().getIssuer();
        if (!serviceAccounts.containsKey(foundEmail)) {
          throw new IOException("Service Account Email not found as issuer.");
        }
        accessToken = serviceAccounts.get(foundEmail);
        String foundScopes = (String) signature.getPayload().get("scope");
        if (foundScopes == null || foundScopes.length() == 0) {
          throw new IOException("Scopes not found.");
        }
      } else {
        throw new IOException("Unknown token type.");
      }

      // Create the JSon response
      GenericJson refreshContents = new GenericJson();
      refreshContents.setFactory(JSON_FACTORY);
      refreshContents.put("access_token", accessToken);
      refreshContents.put("expires_in", 3600);
      refreshContents.put("token_type", "Bearer");
      String refreshText  = refreshContents.toPrettyString();

      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
          .setContentType(Json.MEDIA_TYPE)
          .setContent(refreshText);
      return response;
    }
  };
}
 
Example 15
Source File: DefaultCredentialProviderTest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
public void testDefaultCredentialServiceAccount() throws IOException {
  File serviceAccountFile = new java.io.File(getTempDirectory(),
      "DefaultCredentialServiceAccount.json");
  if (serviceAccountFile.exists()) {
    serviceAccountFile.delete();
  }
  final String serviceAccountId =
      "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com";
  final String serviceAccountEmail =
      "36680232662-vrd7ji19qe3nelgchdcsanun6bnr@developer.gserviceaccount.com";

  MockTokenServerTransport transport = new MockTokenServerTransport();
  transport.addServiceAccount(serviceAccountEmail, ACCESS_TOKEN);

  TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider();
  try {
    // Write out service account file
    GenericJson serviceAccountContents = new GenericJson();
    serviceAccountContents.setFactory(JSON_FACTORY);
    serviceAccountContents.put("client_id", serviceAccountId);
    serviceAccountContents.put("client_email", serviceAccountEmail);
    serviceAccountContents.put("private_key", SA_KEY_TEXT);
    serviceAccountContents.put("private_key_id", SA_KEY_ID);
    serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE);
    PrintWriter writer = new PrintWriter(serviceAccountFile);
    String json = serviceAccountContents.toPrettyString();
    writer.println(json);
    writer.close();

    // Point the default credential to the file
    testProvider.setEnv(DefaultCredentialProvider.CREDENTIAL_ENV_VAR,
        serviceAccountFile.getAbsolutePath());

    GoogleCredential credential = testProvider.getDefaultCredential(transport, JSON_FACTORY);
    assertNotNull(credential);
    credential = credential.createScoped(SCOPES);

    assertTrue(credential.refreshToken());
    assertEquals(ACCESS_TOKEN, credential.getAccessToken());
  } finally {
    if (serviceAccountFile.exists()) {
      serviceAccountFile.delete();
    }
  }
}
 
Example 16
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
public void testFactory() {
  JsonFactory factory = newFactory();
  GenericJson data = new GenericJson();
  data.setFactory(factory);
  assertEquals(factory, data.getFactory());
}
 
Example 17
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
public void testToString_withFactory() {
  GenericJson data = new GenericJson();
  data.put("a", "b");
  data.setFactory(newFactory());
  assertEquals("{\"a\":\"b\"}", data.toString());
}
 
Example 18
Source File: GcsUtilTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoveWhenFileNotFound() throws Exception {
  JsonFactory jsonFactory = new JacksonFactory();

  String contentBoundary = "batch_foobarbaz";
  String contentBoundaryLine = "--" + contentBoundary;
  String endOfContentBoundaryLine = "--" + contentBoundary + "--";

  GenericJson error = new GenericJson().set("error", new GenericJson().set("code", 404));
  error.setFactory(jsonFactory);

  String content =
      contentBoundaryLine
          + "\n"
          + "Content-Type: application/http\n"
          + "\n"
          + "HTTP/1.1 404 Not Found\n"
          + "Content-Length: -1\n"
          + "\n"
          + error.toString()
          + "\n"
          + "\n"
          + endOfContentBoundaryLine
          + "\n";

  final LowLevelHttpResponse mockResponse = Mockito.mock(LowLevelHttpResponse.class);
  when(mockResponse.getContentType()).thenReturn("multipart/mixed; boundary=" + contentBoundary);
  when(mockResponse.getStatusCode()).thenReturn(200);
  when(mockResponse.getContent()).thenReturn(toStream(content));

  // A mock transport that lets us mock the API responses.
  MockLowLevelHttpRequest request =
      new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          return mockResponse;
        }
      };
  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder().setLowLevelHttpRequest(request).build();

  GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil();
  gcsUtil.setStorageClient(
      new Storage(mockTransport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()));
  gcsUtil.remove(Arrays.asList("gs://some-bucket/already-deleted"));
}
 
Example 19
Source File: GcsUtilTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetSizeBytesWhenFileNotFoundBatchRetry() throws Exception {
  JsonFactory jsonFactory = new JacksonFactory();

  String contentBoundary = "batch_foobarbaz";
  String contentBoundaryLine = "--" + contentBoundary;
  String endOfContentBoundaryLine = "--" + contentBoundary + "--";

  GenericJson error = new GenericJson().set("error", new GenericJson().set("code", 404));
  error.setFactory(jsonFactory);

  String content =
      contentBoundaryLine
          + "\n"
          + "Content-Type: application/http\n"
          + "\n"
          + "HTTP/1.1 404 Not Found\n"
          + "Content-Length: -1\n"
          + "\n"
          + error.toString()
          + "\n"
          + "\n"
          + endOfContentBoundaryLine
          + "\n";
  thrown.expect(FileNotFoundException.class);

  final LowLevelHttpResponse mockResponse = Mockito.mock(LowLevelHttpResponse.class);
  when(mockResponse.getContentType()).thenReturn("multipart/mixed; boundary=" + contentBoundary);

  // 429: Too many requests, then 200: OK.
  when(mockResponse.getStatusCode()).thenReturn(429, 200);
  when(mockResponse.getContent()).thenReturn(toStream("error"), toStream(content));

  // A mock transport that lets us mock the API responses.
  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder()
          .setLowLevelHttpRequest(
              new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  return mockResponse;
                }
              })
          .build();

  GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil();

  gcsUtil.setStorageClient(
      new Storage(mockTransport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()));
  gcsUtil.fileSizes(ImmutableList.of(GcsPath.fromComponents("testbucket", "testobject")));
}