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

The following examples show how to use com.google.api.client.http.LowLevelHttpRequest. 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: OAuth2CredentialsTest.java    From rides-java-sdk with MIT License 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException {
    return new MockLowLevelHttpRequest() {

        @Override
        public String getUrl() {
            return url;
        }

        @Override
        public LowLevelHttpResponse execute() throws IOException {
            lastRequestUrl = getUrl();
            lastRequestContent = getContentAsString();

            MockLowLevelHttpResponse mock = new MockLowLevelHttpResponse();
            mock.setStatusCode(httpStatusCode);
            mock.setContent(httpResponseContent);

            return mock;
        }
    };
}
 
Example #2
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testReturnRawInputStream_defaultFalse() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH,
      JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  InputStream inputStream = request.executeAsInputStream();
  // The response will be wrapped because of gzip encoding
  assertFalse(inputStream instanceof ByteArrayInputStream);
}
 
Example #3
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testExecute_void() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContent("{\"a\":\"ignored\"}")
              .setContentType(Json.MEDIA_TYPE);
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<Void> request =
      new MockGoogleClientRequest<Void>(client, HttpMethods.GET, URI_TEMPLATE, null, Void.class);
  Void v = request.execute();
  assertNull(v);
}
 
Example #4
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testExecuteUsingHead() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          assertEquals("HEAD", method);
          assertEquals("https://www.googleapis.com/test/path/v1/tests/foo", url);
          return new MockLowLevelHttpResponse();
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  request.put("testId", "foo");
  request.executeUsingHead();
}
 
Example #5
Source File: FakeWebServer.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      if (responses.isEmpty()) {
        throw new IOException(
            "Unexpected call to execute(), no injected responses left to return.");
      }
      return responses.remove();
    }
  };
  requests.add(new Request(method, request));
  return request;
}
 
Example #6
Source File: GitTestUtil.java    From copybara with Apache License 2.0 6 votes vote down vote up
public static LowLevelHttpRequest mockResponseWithStatus(
    String responseContent, int status, MockRequestAssertion requestValidator) {
  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      assertWithMessage(
              String.format(
                  "Request <%s> did not match predicate: '%s'",
                  this.getContentAsString(), requestValidator))
          .that(requestValidator.test(this.getContentAsString()))
          .isTrue();
      // Responses contain a IntputStream for content. Cannot be reused between for two
      // consecutive calls. We create new ones per call here.
      return new MockLowLevelHttpResponse()
          .setContentType(Json.MEDIA_TYPE)
          .setContent(responseContent)
          .setStatusCode(status);
    }
  };
}
 
Example #7
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testReturnRawInputStream_True() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH,
      JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  request.setReturnRawInputStream(true);
  InputStream inputStream = request.executeAsInputStream();
  // The response will not be wrapped due to setReturnRawInputStream(true)
  assertTrue(inputStream instanceof ByteArrayInputStream);
}
 
Example #8
Source File: FirebaseChannelTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void firebaseGet() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("GET", FIREBASE_DB_URL + "/my/path");
}
 
Example #9
Source File: GoogleAuthTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setContentType("application/json");
          result.setContent(content);
          result.setStatusCode(statusCode);
          return result;
        }
      };
    }
  };
  HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory()));
  GoogleAuth.configureErrorHandling(httpRequest);
  return httpRequest;
}
 
Example #10
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(final String method, String url) {
  // First request should be to the resumable request url
  if (method.equals("POST")) {
    assertEquals(TEST_RESUMABLE_REQUEST_URL, url);

    return new MockLowLevelHttpRequest() {
      @Override
      public LowLevelHttpResponse execute() {
        assertEquals(TEST_CONTENT_TYPE, getFirstHeaderValue("x-upload-content-type"));

        // This is the initiation call.
        MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
        // Return 200 with the upload URI.
        response.setStatusCode(200);
        response.addHeader("Location", TEST_UPLOAD_URL);
        return response;
      }
    };
  }

  // Fake an error when uploading chunks
  return new MockLowLevelHttpRequest() {
 
Example #11
Source File: CustomTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
  return new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setContentType(Json.MEDIA_TYPE);
      IdTokenResponse json = new IdTokenResponse();
      json.setAccessToken("abc");
      json.setRefreshToken("def");
      json.setExpiresInSeconds(3600L);
      json.setIdToken(JWT_ENCODED_CONTENT);
      response.setContent(JSON_FACTORY.toString(json));
      return response;
    }
  };
}
 
Example #12
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoServiceAccount() throws Exception {
  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId("test-project-id")
      .setHttpTransport(new HttpTransport() {
        @Override
        protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          throw new IOException("transport error");
        }
      })
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  try {
    FirebaseAuth.getInstance(app).createCustomTokenAsync("foo").get();
    fail("Expected exception.");
  } catch (IllegalStateException expected) {
    Assert.assertEquals(
        "Failed to initialize FirebaseTokenFactory. Make sure to initialize the SDK with "
            + "service account credentials or specify a service account ID with "
            + "iam.serviceAccounts.signBlob permission. Please refer to "
            + "https://firebase.google.com/docs/auth/admin/create-custom-tokens for more details "
            + "on creating custom tokens.",
        expected.getMessage());
  }
}
 
Example #13
Source File: FirebaseTokenVerifierImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyTokenCertificateError() {
  MockHttpTransport failingTransport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      throw new IOException("Expected error");
    }
  };
  GooglePublicKeysManager publicKeysManager = newPublicKeysManager(failingTransport);
  FirebaseTokenVerifier idTokenVerifier = newTestTokenVerifier(publicKeysManager);
  String token = tokenFactory.createToken();

  try {
    idTokenVerifier.verifyToken(token);
    Assert.fail("No exception thrown");
  } catch (FirebaseAuthException expected) {
    assertTrue(expected.getCause() instanceof IOException);
    assertEquals("Expected error", expected.getCause().getMessage());
  }
}
 
Example #14
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      String firstHeader = getFirstHeaderValue(expectedHeader);
      assertTrue(
          String.format(
              "Expected header value to match %s, instead got %s.",
              expectedHeaderValue,
              firstHeader
          ),
          firstHeader.matches(expectedHeaderValue)
      );
      return new MockLowLevelHttpResponse();
    }
  };
}
 
Example #15
Source File: GooglePublicKeysManagerTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String name, String url) {
  return new MockLowLevelHttpRequest() {
      @Override
    public LowLevelHttpResponse execute() {
      MockLowLevelHttpResponse r = new MockLowLevelHttpResponse();
      r.setStatusCode(200);
      r.addHeader("Cache-Control", "max-age=" + MAX_AGE);
      if (useAgeHeader) {
        r.addHeader("Age", String.valueOf(AGE));
      }
      r.setContentType(Json.MEDIA_TYPE);
      r.setContent(TEST_CERTIFICATES);
      return r;
    }
  };
}
 
Example #16
Source File: FirebaseChannelTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void firebaseDelete() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("DELETE", FIREBASE_DB_URL + "/my/path");
}
 
Example #17
Source File: GerritDestinationTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
private void mockChangeFound(GitRevision currentRev, int changeNum) throws IOException {
  when(gitUtil
          .httpTransport()
          .buildRequest(eq("GET"), startsWith("https://localhost:33333/changes/")))
      .then(
          (Answer<LowLevelHttpRequest>)
              invocation -> {
                String change = changeIdFromRequest((String) invocation.getArguments()[1]);
                return mockResponse(
                    String.format(
                        "[{"
                            + "change_id : '%s',"
                            + "status : 'NEW',"
                            + "_number : '" + changeNum + "',"
                            + "current_revision = '%s'}]",
                        change, currentRev.getSha1()));
              });
}
 
Example #18
Source File: DirectoryGroupsConnectionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Returns a valid GoogleJsonResponseException for the given status code and error message.  */
private GoogleJsonResponseException makeResponseException(
    final int statusCode,
    final String message) throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(statusCode);
          response.setContentType(Json.MEDIA_TYPE);
          response.setContent(String.format(
              "{\"error\":{\"code\":%d,\"message\":\"%s\",\"domain\":\"global\","
              + "\"reason\":\"duplicate\"}}",
              statusCode,
              message));
          return response;
        }};
    }};
  HttpRequest request = transport.createRequestFactory()
      .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
      .setThrowExceptionOnExecuteError(false);
  return GoogleJsonResponseException.from(new JacksonFactory(), request.execute());
}
 
Example #19
Source File: MockHttpTransportHelper.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
public static MockHttpTransport mockTransport(LowLevelHttpResponse... responsesIn) {
  return new MockHttpTransport() {
    int responsesIndex = 0;
    final LowLevelHttpResponse[] responses = responsesIn;

    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return responses[responsesIndex++];
        }
      };
    }
  };
}
 
Example #20
Source File: MockHttpTransportHelper.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
public static HttpResponse fakeResponse(Map<String, Object> headers, InputStream content)
    throws IOException {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() {
              MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
              headers.forEach((h, hv) -> response.addHeader(h, String.valueOf(hv)));
              return response.setContent(content);
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  return request.execute();
}
 
Example #21
Source File: IcannHttpReporterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) {
  return new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      mockRequest = new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          response.setContentType(PLAIN_TEXT_UTF_8.toString());
          response.setContent(iirdeaResponse.read());
          return response;
        }
      };
      mockRequest.setUrl(url);
      return mockRequest;
    }
  };
}
 
Example #22
Source File: GithubArchiveTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void repoExceptionOnDownloadFailure() throws Exception {
  httpTransport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
           MockLowLevelHttpRequest request = new MockLowLevelHttpRequest() {
              public LowLevelHttpResponse execute() throws IOException {
                throw new IOException("OH NOES!");
              }
           };
          return request;
        }
      };
  RemoteFileOptions options = new RemoteFileOptions();
  options.transport = () -> new GclientHttpStreamFactory(httpTransport, Duration.ofSeconds(20));
  Console console = new TestingConsole();
  OptionsBuilder optionsBuilder = new OptionsBuilder().setConsole(console);
  optionsBuilder.remoteFile = options;
  skylark = new SkylarkTestExecutor(optionsBuilder);
  ValidationException e = assertThrows(ValidationException.class, () -> skylark.eval("sha256",
      "sha256 = remotefiles.github_archive("
          + "project = 'google/copybara',"
          + "revision='674ac754f91e64a0efb8087e59a176484bd534d1').sha256()"));
  assertThat(e).hasCauseThat().hasCauseThat().hasCauseThat().isInstanceOf(RepoException.class);
}
 
Example #23
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void normal() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(200);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  this.task.put(sinkRecords);
}
 
Example #24
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void connectionRefused() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  when(httpRequest.execute()).thenThrow(ConnectException.class);
  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(RetriableException.class, () -> this.task.put(sinkRecords));
}
 
Example #25
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void contentLengthTooLarge() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(417);
  when(httpResponse.getContentType()).thenReturn("text/html");
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
Example #26
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidToken() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(403);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
Example #27
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidIndex() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(400);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
Example #28
Source File: RetryHttpRequestInitializerTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  HttpTransport lowLevelTransport =
      new HttpTransport() {
        @Override
        protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          return mockLowLevelRequest;
        }
      };

  // Retry initializer will pass through to credential, since we can have
  // only a single HttpRequestInitializer, and we use multiple Credential
  // types in the SDK, not all of which allow for retry configuration.
  RetryHttpRequestInitializer initializer =
      new RetryHttpRequestInitializer(
          new MockNanoClock(),
          millis -> {},
          Arrays.asList(418 /* I'm a teapot */),
          mockHttpResponseInterceptor);
  storage =
      new Storage.Builder(lowLevelTransport, jsonFactory, initializer)
          .setApplicationName("test")
          .build();
}
 
Example #29
Source File: GitHubApiTransportImplTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testPasswordHeaderSet() throws Exception {
  Map<String, List<String>> headers = new HashMap<>();
  httpTransport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          headers.putAll(this.getHeaders());
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setContent("foo");
          return response;
        }
      };
    }
  };
  transport = new GitHubApiTransportImpl(repo, httpTransport, "store", new TestingConsole());
  transport.get("foo/bar", String.class);
  assertThat(headers).containsEntry("authorization", ImmutableList.of("Basic dXNlcjpTRUNSRVQ="));
}
 
Example #30
Source File: TicTacToeServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void doGet_noGameKey() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  servletUnderTest.doGet(mockRequest, mockResponse);

  // Make sure the game object was created for a new game
  Objectify ofy = ObjectifyService.ofy();
  Game game = ofy.load().type(Game.class).first().safe();
  assertThat(game.userX).isEqualTo(USER_ID);

  verify(mockHttpTransport, times(1))
      .buildRequest(eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$"));
  verify(requestDispatcher).forward(mockRequest, mockResponse);
  verify(mockRequest).setAttribute(eq("token"), anyString());
  verify(mockRequest).setAttribute("game_key", game.id);
  verify(mockRequest).setAttribute("me", USER_ID);
  verify(mockRequest).setAttribute("channel_id", USER_ID + game.id);
  verify(mockRequest).setAttribute(eq("initial_message"), anyString());
  verify(mockRequest).setAttribute(eq("game_link"), anyString());
}