org.apache.http.HttpResponse

Here are the examples of the java api class org.apache.http.HttpResponse taken from open source projects.

1. TestDefaultConnectionReuseStrategy#testConnectionTokens5()

View license
public void testConnectionTokens5() throws Exception {
    // Use HTTP 1.1
    HttpResponse response = createResponse(HttpVersion.HTTP_1_1, 200, "OK", true, -1);
    response.addHeader("Connection", "yadda, dumdy");
    response.addHeader("Proxy-Connection", "close");
    // Connection takes precedence over Proxy-Connection,
    // even if it doesn't contain a recognized token.
    // Default for HTTP/1.1 is to keep alive.
    assertTrue(reuseStrategy.keepAlive(response, context));
}

2. AwsMvcConfig#hostName()

Project: genie
Source File: AwsMvcConfig.java
View license
/**
     * Get the host name for this application by calling the AWS metadata endpoints. Overrides default implementation
     * which defaults to using InetAddress class. Only active when profile enabled.
     *
     * @param httpClient The http client to use to call the Amazon endpoints
     * @return The hostname
     * @throws IOException When the host can't be calculated
     */
@Bean
public String hostName(final HttpClient httpClient) throws IOException {
    final HttpResponse publicHostnameResponse = httpClient.execute(this.publicHostNameGet);
    if (publicHostnameResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        final String hostname = EntityUtils.toString(publicHostnameResponse.getEntity(), UTF_8);
        log.debug("AWS Public Hostname: {}", hostname);
        return hostname;
    }
    final HttpResponse ipv4Response = httpClient.execute(this.localIPV4HostNameGet);
    if (ipv4Response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        final String hostname = EntityUtils.toString(ipv4Response.getEntity(), UTF_8);
        log.debug("AWS IPV4 Hostname: {}", hostname);
        return hostname;
    }
    throw new IOException("Unable to get instance metadata from AWS");
}

3. AwsMvcConfigUnitTests#cantGetHostname()

Project: genie
Source File: AwsMvcConfigUnitTests.java
View license
/**
     * Make sure if both fails we throw an exception.
     *
     * @throws IOException on any problem
     */
@Test(expected = IOException.class)
public void cantGetHostname() throws IOException {
    final HttpClient client = Mockito.mock(HttpClient.class);
    final HttpResponse response = Mockito.mock(HttpResponse.class);
    Mockito.when(client.execute(this.awsMvcConfig.publicHostNameGet)).thenReturn(response);
    final StatusLine statusLine = Mockito.mock(StatusLine.class);
    Mockito.when(response.getStatusLine()).thenReturn(statusLine);
    Mockito.when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NOT_FOUND);
    final HttpResponse ip4Response = Mockito.mock(HttpResponse.class);
    Mockito.when(client.execute(this.awsMvcConfig.localIPV4HostNameGet)).thenReturn(ip4Response);
    final StatusLine ip4StatusLine = Mockito.mock(StatusLine.class);
    Mockito.when(ip4Response.getStatusLine()).thenReturn(ip4StatusLine);
    Mockito.when(ip4StatusLine.getStatusCode()).thenReturn(HttpStatus.SC_BAD_REQUEST);
    this.awsMvcConfig.hostName(client);
}

4. TestDefaultConnectionReuseStrategy#createResponse()

View license
// createResponse/empty
/**
     * Creates a response with an entity.
     *
     * @param version   the HTTP version
     * @param status    the status code
     * @param message   the status message
     * @param chunked   whether the entity should indicate chunked encoding
     * @param length    the content length to be indicated by the entity
     *
     * @return  a response with the argument attributes, but no headers
     */
private static final HttpResponse createResponse(HttpVersion version, int status, String message, boolean chunked, int length) {
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setChunked(chunked);
    entity.setContentLength(length);
    HttpResponse response = createResponse(version, status, message);
    response.setEntity(entity);
    return response;
}

5. TestHttpClient#execute()

Project: httpcore
Source File: TestHttpClient.java
View license
public HttpResponse execute(final HttpRequest request, final HttpHost targetHost, final HttpClientConnection conn) throws HttpException, IOException {
    this.context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
    this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
    this.httpexecutor.preProcess(request, this.httpproc, this.context);
    HttpResponse response = this.httpexecutor.execute(request, conn, this.context);
    response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
    this.httpexecutor.postProcess(response, this.httpproc, this.context);
    return response;
}

6. TestStandardInterceptors#testResponseConnControlEntityUnknownContentLength()

View license
public void testResponseConnControlEntityUnknownContentLength() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    BasicHttpRequest request = new BasicHttpRequest("GET", "/");
    request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE));
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    response.setEntity(entity);
    ResponseConnControl interceptor = new ResponseConnControl();
    interceptor.process(response, context);
    Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
    assertNotNull(header);
    assertEquals(HTTP.CONN_CLOSE, header.getValue());
}

7. TestStandardInterceptors#testResponseConnControlClientRequest()

View license
public void testResponseConnControlClientRequest() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    BasicHttpRequest request = new BasicHttpRequest("GET", "/");
    request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE));
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    StringEntity entity = new StringEntity("whatever");
    response.setEntity(entity);
    ResponseConnControl interceptor = new ResponseConnControl();
    interceptor.process(response, context);
    Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
    assertNotNull(header);
    assertEquals(HTTP.CONN_KEEP_ALIVE, header.getValue());
}

8. TestStandardInterceptors#testResponseConnControlClientRequest2()

View license
public void testResponseConnControlClientRequest2() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    BasicHttpRequest request = new BasicHttpRequest("GET", "/");
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    StringEntity entity = new StringEntity("whatever");
    response.setEntity(entity);
    ResponseConnControl interceptor = new ResponseConnControl();
    interceptor.process(response, context);
    Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
    assertNull(header);
}

9. TestStandardInterceptors#testResponseContentEntityChunked()

View license
public void testResponseContentEntityChunked() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setChunked(true);
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
    assertNotNull(h1);
    assertEquals(HTTP.CHUNK_CODING, h1.getValue());
    Header h2 = response.getFirstHeader(HTTP.CONTENT_LEN);
    assertNull(h2);
}

10. TestStandardInterceptors#testResponseContentEntityContentLenghtDelimited()

View license
public void testResponseContentEntityContentLenghtDelimited() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContentLength(10);
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.CONTENT_LEN);
    assertNotNull(h1);
    assertEquals("10", h1.getValue());
    Header h2 = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
    assertNull(h2);
}

11. TestStandardInterceptors#testResponseContentEntityUnknownContentLength()

View license
public void testResponseContentEntityUnknownContentLength() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
    assertNull(h1);
    Header h2 = response.getFirstHeader(HTTP.CONTENT_LEN);
    assertNull(h2);
}

12. TestStandardInterceptors#testResponseContentEntityNoContentTypeAndEncoding()

View license
public void testResponseContentEntityNoContentTypeAndEncoding() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.CONTENT_TYPE);
    assertNull(h1);
    Header h2 = response.getFirstHeader(HTTP.CONTENT_ENCODING);
    assertNull(h2);
}

13. TestStandardInterceptors#testResponseContentEntityContentTypeAndEncoding()

View license
public void testResponseContentEntityContentTypeAndEncoding() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContentEncoding("whatever");
    entity.setContentType("whatever");
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.CONTENT_TYPE);
    assertNotNull(h1);
    assertEquals("whatever", h1.getValue());
    Header h2 = response.getFirstHeader(HTTP.CONTENT_ENCODING);
    assertNotNull(h2);
    assertEquals("whatever", h2.getValue());
}

14. TestPerHostServiceWrappedHttpClient#reusesWrapperForRequestsFromSameHost()

View license
@Test
public void reusesWrapperForRequestsFromSameHost() throws Exception {
    ServiceWrapper wrapper = new NullWrapper();
    HttpUriRequest req1 = new HttpGet("http://foo.example.com/bar");
    HttpUriRequest req2 = new HttpGet("http://foo.example.com/baz");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName(isA(String.class))).andReturn(wrapper);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    impl.execute(req2, ctx);
    verifyMocks();
}

15. TestPerHostServiceWrappedHttpClient#reusesWrapperForRequestsFromEquivalentHostsDefaultHttpPort()

View license
@Test
public void reusesWrapperForRequestsFromEquivalentHostsDefaultHttpPort() throws Exception {
    ServiceWrapper wrapper = new NullWrapper();
    HttpUriRequest req1 = new HttpGet("http://foo.example.com/bar");
    HttpUriRequest req2 = new HttpGet("http://foo.example.com:80/baz");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName(isA(String.class))).andReturn(wrapper);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    impl.execute(req2, ctx);
    verifyMocks();
}

16. TestPerHostServiceWrappedHttpClient#reusesWrapperForRequestsFromEquivalentHostsDefaultHttpsPort()

View license
@Test
public void reusesWrapperForRequestsFromEquivalentHostsDefaultHttpsPort() throws Exception {
    ServiceWrapper wrapper = new NullWrapper();
    HttpUriRequest req1 = new HttpGet("https://foo.example.com/bar");
    HttpUriRequest req2 = new HttpGet("https://foo.example.com:443/baz");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName(isA(String.class))).andReturn(wrapper);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    impl.execute(req2, ctx);
    verifyMocks();
}

17. TestPerHostServiceWrappedHttpClient#reusesWrapperForRequestsFromEquivalentHostsCaseInsensitiveHostName()

View license
@Test
public void reusesWrapperForRequestsFromEquivalentHostsCaseInsensitiveHostName() throws Exception {
    ServiceWrapper wrapper = new NullWrapper();
    HttpUriRequest req1 = new HttpGet("http://foo.example.com/bar");
    HttpUriRequest req2 = new HttpGet("http://FOO.Example.cOM/baz");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName(isA(String.class))).andReturn(wrapper);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    impl.execute(req2, ctx);
    verifyMocks();
}

18. TestPerHostServiceWrappedHttpClient#usesDifferentWrappersForDifferentHosts()

View license
@Test
public void usesDifferentWrappersForDifferentHosts() throws Exception {
    Flag f1 = new Flag();
    ServiceWrapper wrapper1 = new NullWrapper(f1);
    Flag f2 = new Flag();
    ServiceWrapper wrapper2 = new NullWrapper(f2);
    HttpUriRequest req1 = new HttpGet("http://foo.example.com/");
    HttpUriRequest req2 = new HttpGet("http://bar.example.com/");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName("foo.example.com:80")).andReturn(wrapper1);
    expect(mockFactory.getWrapperWithName("bar.example.com:80")).andReturn(wrapper2);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    assertTrue(f1.set && !f2.set);
    impl.execute(req2, ctx);
    assertTrue(f1.set && f2.set);
    verifyMocks();
}

19. OkApacheClientTest#headers()

Project: okhttp
Source File: OkApacheClientTest.java
View license
@Test
public void headers() throws Exception {
    server.enqueue(new MockResponse().addHeader("Foo", "Bar"));
    server.enqueue(new MockResponse().addHeader("Foo", "Bar").addHeader("Foo", "Baz"));
    HttpGet request1 = new HttpGet(server.url("/").url().toURI());
    HttpResponse response1 = client.execute(request1);
    Header[] headers1 = response1.getHeaders("Foo");
    assertEquals(1, headers1.length);
    assertEquals("Bar", headers1[0].getValue());
    HttpGet request2 = new HttpGet(server.url("/").url().toURI());
    HttpResponse response2 = client.execute(request2);
    Header[] headers2 = response2.getHeaders("Foo");
    assertEquals(2, headers2.length);
    assertEquals("Bar", headers2[0].getValue());
    assertEquals("Baz", headers2[1].getValue());
}

20. CxfCacheUriInfoIssue2Test#testServletContextPath()

View license
@Test
public void testServletContextPath() throws Exception {
    URI uri1 = URI.create(server1.getEndpoint().toASCIIString() + "$metadata");
    final HttpGet get1 = new HttpGet(uri1);
    HttpResponse r1 = new DefaultHttpClient().execute(get1);
    assertNotNull(r1);
    assertEquals(uri1, CxfCacheUriInfoIssueService1Factory.service.getProcessor().getContext().getPathInfo().getRequestUri());
    assertEquals(server1.getEndpoint(), CxfCacheUriInfoIssueService1Factory.service.getProcessor().getContext().getPathInfo().getServiceRoot());
    URI uri2 = URI.create(server2.getEndpoint().toASCIIString() + "$metadata");
    final HttpGet get2 = new HttpGet(uri2);
    HttpResponse r2 = new DefaultHttpClient().execute(get2);
    assertNotNull(r2);
    assertEquals(uri2, CxfCacheUriInfoIssueService2Factory.service.getProcessor().getContext().getPathInfo().getRequestUri());
    assertEquals(server2.getEndpoint(), CxfCacheUriInfoIssueService2Factory.service.getProcessor().getContext().getPathInfo().getServiceRoot());
}

21. CxfCacheUriInfoIssueTest#checkContextForDifferentHostNamesRequests()

View license
@Test
public void checkContextForDifferentHostNamesRequests() throws ClientProtocolException, IOException, ODataException, URISyntaxException {
    URI uri1 = URI.create(getEndpoint().toString() + "$metadata");
    HttpGet get1 = new HttpGet(uri1);
    HttpResponse response1 = getHttpClient().execute(get1);
    assertNotNull(response1);
    URI serviceRoot1 = getService().getProcessor().getContext().getPathInfo().getServiceRoot();
    assertEquals(uri1.getHost(), serviceRoot1.getHost());
    get1.reset();
    URI uri2 = new URI(uri1.getScheme(), uri1.getUserInfo(), "127.0.0.1", uri1.getPort(), uri1.getPath(), uri1.getQuery(), uri1.getFragment());
    HttpGet get2 = new HttpGet(uri2);
    HttpResponse response2 = getHttpClient().execute(get2);
    assertNotNull(response2);
    URI serviceRoot2 = getService().getProcessor().getContext().getPathInfo().getServiceRoot();
    assertEquals(uri2.getHost(), serviceRoot2.getHost());
}

22. DefaultRequestDirectorTest#shouldReturnRequestsByRule_AnyMethod()

View license
@Test
public void shouldReturnRequestsByRule_AnyMethod() throws Exception {
    Robolectric.addHttpResponseRule("http://some.uri", new TestHttpResponse(200, "a cheery response body"));
    HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
    assertNotNull(getResponse);
    assertThat(getResponse.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(Strings.fromStream(getResponse.getEntity().getContent()), equalTo("a cheery response body"));
    HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null);
    assertNotNull(postResponse);
    assertThat(postResponse.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(Strings.fromStream(postResponse.getEntity().getContent()), equalTo("a cheery response body"));
}

23. DefaultRequestDirectorTest#shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams()

View license
@Test
public void shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams() throws Exception {
    TestHttpResponse testHttpResponse = new TestHttpResponse(200, "a cheery response body");
    Robolectric.addHttpResponseRule("http://some.uri", testHttpResponse);
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(true));
    HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
    InputStream getResponseStream = getResponse.getEntity().getContent();
    assertThat(Strings.fromStream(getResponseStream), equalTo("a cheery response body"));
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null);
    InputStream postResponseStream = postResponse.getEntity().getContent();
    assertThat(Strings.fromStream(postResponseStream), equalTo("a cheery response body"));
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    getResponseStream.close();
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    postResponseStream.close();
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(true));
}

24. DefaultRequestDirectorTest#shouldHandleMultipleInvocations()

View license
@Test
public void shouldHandleMultipleInvocations() throws Exception {
    Robolectric.addPendingHttpResponse(200, "a happy response body");
    Robolectric.addPendingHttpResponse(201, "another happy response body");
    HttpResponse response1 = requestDirector.execute(null, new HttpGet("http://example.com"), null);
    HttpResponse response2 = requestDirector.execute(null, new HttpGet("www.example.com"), null);
    assertThat(response1.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(Strings.fromStream(response1.getEntity().getContent()), equalTo("a happy response body"));
    assertThat(response2.getStatusLine().getStatusCode(), equalTo(201));
    assertThat(Strings.fromStream(response2.getEntity().getContent()), equalTo("another happy response body"));
}

25. CreateSessionHandlerTest#assertNewTestSessionCreationAndGetCapabilties()

View license
@Test
public void assertNewTestSessionCreationAndGetCapabilties() throws Exception {
    HttpResponse sessionResponse = executeCreateSessionRequest();
    JSONObject json = parseJsonResponse(sessionResponse);
    String sessionId = json.getString("sessionId");
    // Get capabilities of session
    HttpResponse getCapaResp = executeRequest("http://" + host + ":" + port + "/wd/hub/session/" + sessionId, HttpMethod.GET);
    SelendroidAssert.assertResponseIsOk(getCapaResp);
    JSONObject capa = parseJsonResponse(getCapaResp);
    Assert.assertEquals(sessionId, capa.getString("sessionId"));
    Assert.assertEquals(0, capa.getInt("status"));
    Assert.assertEquals("selendroid", capa.getJSONObject("value").getString(Capabilities.NAME));
}

26. FindElementHandlerTest#assertThatFindElementResponseHasCorrectFormat()

View license
// @Test()
public void assertThatFindElementResponseHasCorrectFormat() throws Exception {
    HttpResponse response = executeCreateSessionRequest();
    SelendroidAssert.assertResponseIsRedirect(response);
    JSONObject session = parseJsonResponse(response);
    String sessionId = session.getString("sessionId");
    Assert.assertFalse(sessionId.isEmpty());
    JSONObject payload = new JSONObject();
    payload.put("using", "id");
    payload.put("value", "my_button_bar");
    String url = "http://" + host + ":" + port + "/wd/hub/session/" + sessionId + "/element";
    HttpResponse element = executeRequestWithPayload(url, HttpMethod.POST, payload.toString());
    SelendroidAssert.assertResponseIsOk(element);
}

27. PinningSSLSocketFactoryTest#testGoodPin()

View license
public void testGoodPin() throws IOException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    String[] pins = new String[] { "40c5401d6f8cbaf08b00edefb1ee87d005b3b9cd" };
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new PinningSSLSocketFactory(getContext(), pins, 0), 443));
    HttpParams httpParams = new BasicHttpParams();
    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
    HttpResponse response = httpClient.execute(new HttpGet("https://www.google.com/"));
}

28. RemoteServer#_run()

Project: Anki-Android
Source File: RemoteServer.java
View license
private JSONObject _run(String cmd, JSONObject data) throws UnknownHttpResponseException {
    HttpResponse ret = super.req(cmd, super.getInputStream(Utils.jsonToString(data)));
    try {
        String s = super.stream2String(ret.getEntity().getContent());
        if (!s.equalsIgnoreCase("null") && s.length() != 0) {
            return new JSONObject(s);
        } else {
            return new JSONObject();
        }
    } catch (IllegalStateExceptionJSONException | IOException |  e) {
        throw new RuntimeException(e);
    }
}

29. ClientCredentialGrantTestIT#performClientCredentialTokenPost()

View license
private InputStream performClientCredentialTokenPost(String username, String password) throws IOException {
    String tokenUrl = String.format("%s/oauth2/token", baseUrl());
    final HttpPost tokenRequest = new HttpPost(tokenUrl);
    String postBody = String.format("grant_type=%s", OAuth2Validator.GRANT_TYPE_CLIENT_CREDENTIALS);
    tokenRequest.setEntity(new ByteArrayEntity(postBody.getBytes()));
    tokenRequest.addHeader("Authorization", authorizationBasic(username, password));
    tokenRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse tokenHttpResponse = new DefaultHttpClient().execute(tokenRequest);
    return tokenHttpResponse.getEntity().getContent();
}

30. AuthorizationCodeRequestHandler#handle()

View license
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    final String uri = request.getRequestLine().getUri();
    Map<String, String> params = getParamsFromUri(uri);
    String authorizationCode = params.get("code");
    authorizationResponseState = params.get("state");
    LOG.debug("URL: {}, state: {}", uri, authorizationResponseState);
    final HttpPost tokenRequest = new HttpPost(oauthServerBaseUrl + "/oauth2/token");
    String postBody = getPostBody(authorizationCode, grantType);
    tokenRequest.setEntity(new ByteArrayEntity(postBody.getBytes()));
    tokenRequest.addHeader("Authorization", AuthorizationCodeTestIT.authorizationBasic(clientId, secret));
    tokenRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse tokenHttpResponse = new DefaultHttpClient().execute(tokenRequest);
    final InputStream responseContent = tokenHttpResponse.getEntity().getContent();
    String responseAsString = new Scanner(responseContent).useDelimiter("\\A").next();
    responseContent.close();
    tokenResponse = responseAsString;
}

31. HttpJobClient#getStatus()

Project: asakusafw
Source File: HttpJobClient.java
View license
@Override
public JobStatus getStatus(JobId id) throws IOException, InterruptedException {
    if (id == null) {
        //$NON-NLS-1$
        throw new IllegalArgumentException("id must not be null");
    }
    HttpGet request = new HttpGet();
    URI uri = createUri(String.format("jobs/%s", id.getToken()));
    request.setURI(uri);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Obtaining information about job: method=get, uri={}", uri);
    }
    HttpResponse response = http.execute(request);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        JobStatus status = extractJobStatus(request, response);
        return status;
    } else {
        throw toException(request, response, MessageFormat.format("Failed to obtain the job status: {0} ({1})", id.getToken(), request.getURI()));
    }
}

32. RegionUtils#fetchFile()

View license
/**
     * Fetches a file from the URL given and writes it to the destination given.
     */
private static void fetchFile(String url, File destinationFile) throws IOException, ClientProtocolException, FileNotFoundException {
    HttpClient httpclient = HttpClientFactory.create(AwsToolkitCore.getDefault(), url);
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        FileOutputStream output = new FileOutputStream(destinationFile);
        try {
            int l;
            byte[] tmp = new byte[2048];
            while ((l = instream.read(tmp)) != -1) {
                output.write(tmp, 0, l);
            }
        } finally {
            output.close();
            instream.close();
        }
    }
}

33. HTTPSenderImpl#cleanup()

Project: axis2-java
Source File: HTTPSenderImpl.java
View license
@Override
protected void cleanup(MessageContext msgContext, Object httpResponse) {
    HttpResponse response;
    if (httpResponse instanceof HttpResponse) {
        response = (HttpResponse) httpResponse;
    } else {
        log.trace("HttpResponse expected, but found - " + httpResponse);
        return;
    }
    if (msgContext.isPropertyTrue(HTTPConstants.CLEANUP_RESPONSE)) {
        log.trace("Cleaning response : " + response);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                log.error("Error while cleaning response : " + response, e);
            }
        }
    }
}

34. HTTPSenderImpl#sendViaDelete()

Project: axis2-java
Source File: HTTPSenderImpl.java
View license
/**
     * Used to send a request via HTTP Delete Method
     *
     * @param msgContext        - The MessageContext of the message
     * @param url               - The target URL
     * @param soapActionString - The soapAction string of the request
     * @throws org.apache.axis2.AxisFault - Thrown in case an exception occurs
     */
protected void sendViaDelete(MessageContext msgContext, URL url, String soapActionString) throws AxisFault {
    HttpDelete deleteMethod = new HttpDelete();
    AbstractHttpClient httpClient = getHttpClient(msgContext);
    populateCommonProperties(msgContext, url, deleteMethod, httpClient, soapActionString);
    /*
         * main execution takes place..
         */
    HttpResponse response = null;
    try {
        response = executeMethod(httpClient, msgContext, url, deleteMethod);
        handleResponse(msgContext, response);
    } catch (IOException e) {
        log.info("Unable to sendViaDelete to url[" + url + "]", e);
        throw AxisFault.makeFault(e);
    } finally {
        cleanup(msgContext, response);
    }
}

35. HttpEnumIntegrationTest#testHttpEnumIngestionInvalidPastCollectionTime()

View license
@Test
public void testHttpEnumIngestionInvalidPastCollectionTime() throws IOException, URISyntaxException {
    long timestamp = System.currentTimeMillis() - TIME_DIFF_MS - Configuration.getInstance().getLongProperty(CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS);
    // ingest and rollup metrics with enum values and verify CF points and elastic search indexes
    final String tenant_id = "333333";
    String postfix = getPostfix();
    final String metric_name = postfix + "enum_metric_test";
    Set<Locator> locators = new HashSet<Locator>();
    locators.add(Locator.createLocatorFromPathComponents(tenant_id, metric_name));
    // post enum metric for ingestion and verify
    HttpResponse response = postMetric(tenant_id, postAggregatedPath, "sample_enums_payload.json", timestamp, postfix);
    String[] errors = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(ERROR_TITLE, errors[0]);
    assertTrue(Pattern.matches(PAST_COLLECTION_TIME_REGEX, errors[1]));
}

36. HttpEnumIntegrationTest#testHttpEnumIngestionInvalidFutureCollectionTime()

View license
@Test
public void testHttpEnumIngestionInvalidFutureCollectionTime() throws IOException, URISyntaxException {
    long timestamp = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty(CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS);
    // ingest and rollup metrics with enum values and verify CF points and elastic search indexes
    final String tenant_id = "333333";
    String postfix = getPostfix();
    // post enum metric for ingestion and verify
    HttpResponse response = postMetric(tenant_id, postAggregatedPath, "sample_enums_payload.json", timestamp, postfix);
    String[] errors = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(ERROR_TITLE, errors[0]);
    assertTrue(Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, errors[1]));
}

37. HttpAnnotationsEndToEndTest#testAnnotationsEndToEndHappyCase()

View license
@Test
public void testAnnotationsEndToEndHappyCase() throws Exception {
    final int batchSize = 1;
    String event = createTestEvent(batchSize);
    HttpResponse response = postEvent(event, tenant_id);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    Thread.sleep(1000);
    parameterMap = new HashMap<String, String>();
    parameterMap.put(Event.fromParameterName, String.valueOf(baseMillis - 86400000));
    parameterMap.put(Event.untilParameterName, String.valueOf(baseMillis + (86400000 * 3)));
    HttpGet get = new HttpGet(getAnnotationsQueryURI());
    response = client.execute(get);
    String responseString = EntityUtils.toString(response.getEntity());
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    Assert.assertFalse(responseString.equals("[]"));
    Assert.assertTrue(responseString.contains("deployment 0"));
}

38. HttpHandlerAnnotationIntegrationTest#testHttpAnnotationIngestionInvalidPastCollectionTime()

View license
@Test
public void testHttpAnnotationIngestionInvalidPastCollectionTime() throws Exception {
    long timestamp = System.currentTimeMillis() - TIME_DIFF_MS - Configuration.getInstance().getLongProperty(CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS);
    final int batchSize = 1;
    final String tenant_id = "333333";
    String event = createTestEvent(batchSize, timestamp);
    HttpResponse response = postEvent(tenant_id, event);
    String[] errors = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(2, errors.length);
    assertEquals(INVALID_DATA, errors[0]);
    assertTrue(Pattern.matches(PAST_COLLECTION_TIME_REGEX, errors[1]));
}

39. HttpHandlerAnnotationIntegrationTest#testHttpAnnotationIngestionInvalidFutureCollectionTime()

View license
@Test
public void testHttpAnnotationIngestionInvalidFutureCollectionTime() throws Exception {
    long timestamp = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty(CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS);
    final int batchSize = 1;
    final String tenant_id = "333333";
    String event = createTestEvent(batchSize, timestamp);
    HttpResponse response = postEvent(tenant_id, event);
    String[] errors = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(2, errors.length);
    assertEquals(INVALID_DATA, errors[0]);
    assertTrue(Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, errors[1]));
}

40. HttpHandlerAnnotationIntegrationTest#testHttpAnnotationIngestionMultiEventsInvalidPastCollectionTime()

View license
@Test
public void testHttpAnnotationIngestionMultiEventsInvalidPastCollectionTime() throws Exception {
    long timestamp = System.currentTimeMillis() - TIME_DIFF_MS - Configuration.getInstance().getLongProperty(CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS);
    final int batchSize = 5;
    final String tenant_id = "333444";
    String event = createTestEvent(batchSize, timestamp);
    HttpResponse response = postEvent(tenant_id, event);
    String[] errors = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(2, errors.length);
    assertEquals(INVALID_DATA, errors[0]);
    assertTrue(Pattern.matches(PAST_COLLECTION_TIME_REGEX, errors[1]));
}

41. HttpHandlerAnnotationIntegrationTest#testIngestingInvalidJAnnotationsJSON()

View license
@Test
public void testIngestingInvalidJAnnotationsJSON() throws Exception {
    String //Invalid JSON with single inverted commas instead of double.
    requestBody = "{'when':346550008," + "'what':'Dummy Event'," + "'data':'Dummy Data'," + "'tags':'deployment'}";
    HttpResponse response = postEvent("456854", requestBody);
    String responseString = EntityUtils.toString(response.getEntity());
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertTrue(responseString.contains("Invalid Data:"));
}

42. HttpHandlerAnnotationIntegrationTest#testIngestingInvalidAnnotationsData()

View license
@Test
public void testIngestingInvalidAnnotationsData() throws Exception {
    String //Invalid Data.
    requestBody = "{\"how\":346550008," + "\"why\":\"Dummy Event\"," + "\"info\":\"Dummy Data\"," + "\"tickets\":\"deployment\"}";
    HttpResponse response = postEvent("456854", requestBody);
    String responseString = EntityUtils.toString(response.getEntity());
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertTrue(responseString.contains("Invalid Data:"));
}

43. HttpHandlerAnnotationIntegrationTest#testHttpAnnotationIngestionMultiEventsInvalidFutureCollectionTime()

View license
@Test
public void testHttpAnnotationIngestionMultiEventsInvalidFutureCollectionTime() throws Exception {
    long timestamp = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty(CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS);
    final int batchSize = 5;
    final String tenant_id = "333444";
    String event = createTestEvent(batchSize, timestamp);
    HttpResponse response = postEvent(tenant_id, event);
    String[] errors = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(2, errors.length);
    assertEquals(INVALID_DATA, errors[0]);
    assertTrue(Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, errors[1]));
}

44. HttpHandlerIntegrationTest#testHttpIngestionInvalidPastCollectionTime()

View license
@Test
public void testHttpIngestionInvalidPastCollectionTime() throws Exception {
    String postfix = getPostfix();
    long time = System.currentTimeMillis() - TIME_DIFF_MS - Configuration.getInstance().getLongProperty(CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS);
    HttpResponse response = postGenMetric(TID, postfix, postPath, time);
    assertEquals(400, response.getStatusLine().getStatusCode());
    String[] output = getBodyArray(response);
    assertTrue(output[1] + " did not match past pattern " + PAST_COLLECTION_TIME_REGEX, Pattern.matches(PAST_COLLECTION_TIME_REGEX, output[1]));
    assertTrue(output[2] + " did not match past pattern " + PAST_COLLECTION_TIME_REGEX, Pattern.matches(PAST_COLLECTION_TIME_REGEX, output[2]));
    assertTrue(output[3] + " did not match past pattern " + PAST_COLLECTION_TIME_REGEX, Pattern.matches(PAST_COLLECTION_TIME_REGEX, output[3]));
}

45. HttpHandlerIntegrationTest#testHttpIngestionInvalidFutureCollectionTime()

View license
@Test
public void testHttpIngestionInvalidFutureCollectionTime() throws Exception {
    String postfix = getPostfix();
    long time = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty(CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS);
    HttpResponse response = postGenMetric(TID, postfix, postPath, time);
    assertEquals(400, response.getStatusLine().getStatusCode());
    String[] output = getBodyArray(response);
    assertEquals(4, output.length);
    assertTrue(output[1] + " did not match future pattern " + FUTURE_COLLECTION_TIME_REGEX, Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, output[1]));
    assertTrue(output[2] + " did not match future pattern " + FUTURE_COLLECTION_TIME_REGEX, Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, output[2]));
    assertTrue(output[3] + " did not match future pattern " + FUTURE_COLLECTION_TIME_REGEX, Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, output[3]));
}

46. HttpHandlerIntegrationTest#testHttpIngestionPartialInvalidCollectionTime()

View license
@Test
public void testHttpIngestionPartialInvalidCollectionTime() throws Exception {
    String postfix = getPostfix();
    long validTime = System.currentTimeMillis();
    long pastTime = System.currentTimeMillis() - TIME_DIFF_MS - Configuration.getInstance().getLongProperty(CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS);
    long futureTime = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty(CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS);
    String jsonBody = getJsonFromFile("sample_multi_payload_with_different_time.json", postfix);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_1%\"", validTime);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_2%\"", pastTime);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_3%\"", futureTime);
    jsonBody = jsonBody.replaceAll("%TENANT_ID_.%", TID);
    HttpResponse response = httpPost(TID, postMultiPath, jsonBody);
    String[] output = getBodyArray(response);
    try {
        assertEquals("Should get status 207 from " + String.format(postMultiPath, TID), 207, response.getStatusLine().getStatusCode());
        assertEquals("", output[0]);
    } finally {
        // Releases connection apparently
        EntityUtils.consume(response.getEntity());
    }
}

47. HttpHandlerIntegrationTest#testHttpAggregatedIngestionInvalidPastCollectionTime()

View license
@Test
public void testHttpAggregatedIngestionInvalidPastCollectionTime() throws IOException, URISyntaxException {
    long timestamp = System.currentTimeMillis() - TIME_DIFF_MS - Configuration.getInstance().getLongProperty(CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS);
    HttpResponse response = postMetric("333333", postAggregatedPath, "sample_payload.json", timestamp, getPostfix());
    String[] errors = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(2, errors.length);
    assertEquals(ERROR_TITLE, errors[0]);
    assertTrue(errors[1] + " did not match past pattern " + PAST_COLLECTION_TIME_REGEX, Pattern.matches(PAST_COLLECTION_TIME_REGEX, errors[1]));
}

48. HttpHandlerIntegrationTest#testHttpAggregatedIngestionInvalidFutureCollectionTime()

View license
@Test
public void testHttpAggregatedIngestionInvalidFutureCollectionTime() throws IOException, URISyntaxException {
    long timestamp = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty(CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS);
    HttpResponse response = postMetric("333333", postAggregatedPath, "sample_payload.json", timestamp, getPostfix());
    String[] errors = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(2, errors.length);
    assertEquals(ERROR_TITLE, errors[0]);
    assertTrue(errors[1] + " did not match future pattern " + FUTURE_COLLECTION_TIME_REGEX, Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, errors[1]));
}

49. HttpHandlerIntegrationTest#testHttpAggregatedIngestionHappyCase()

View license
@Test
public void testHttpAggregatedIngestionHappyCase() throws Exception {
    long start = System.currentTimeMillis() - TIME_DIFF_MS;
    long end = System.currentTimeMillis() + TIME_DIFF_MS;
    String postfix = getPostfix();
    HttpResponse response = postMetric("333333", postAggregatedPath, "sample_payload.json", postfix);
    MetricsRW metricsRW = IOContainer.fromConfig().getPreAggregatedMetricsRW();
    try {
        assertEquals(200, response.getStatusLine().getStatusCode());
        verify(context, atLeastOnce()).update(anyLong(), anyInt());
        final Locator locator = Locator.createLocatorFromPathComponents("333333", "internal", "packets_received" + postfix);
        Points<BluefloodCounterRollup> points = metricsRW.getDataToRollup(locator, RollupType.COUNTER, new Range(start, end), CassandraModel.getPreaggregatedColumnFamilyName(Granularity.FULL));
        assertEquals(1, points.getPoints().size());
    } finally {
        // Releases connection apparently
        EntityUtils.consume(response.getEntity());
    }
}

50. HttpHandlerIntegrationTest#testHttpAggregatedMultiIngestionInvalidPastCollectionTime()

View license
@Test
public void testHttpAggregatedMultiIngestionInvalidPastCollectionTime() throws IOException, URISyntaxException {
    long timestamp = System.currentTimeMillis() - TIME_DIFF_MS - Configuration.getInstance().getLongProperty(CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS);
    String postfix = getPostfix();
    HttpResponse response = postMetric("333333", postAggregatedMultiPath, "sample_multi_aggregated_payload.json", timestamp, postfix);
    String errors[] = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(4, errors.length);
    assertEquals(ERROR_TITLE, errors[0]);
    assertTrue(errors[1] + " did not match past pattern " + PAST_COLLECTION_TIME_REGEX, Pattern.matches(PAST_COLLECTION_TIME_REGEX, errors[1]));
    assertTrue(errors[2] + " did not match past pattern " + PAST_COLLECTION_TIME_REGEX, Pattern.matches(PAST_COLLECTION_TIME_REGEX, errors[2]));
    assertTrue(errors[3] + " did not match past pattern " + PAST_COLLECTION_TIME_REGEX, Pattern.matches(PAST_COLLECTION_TIME_REGEX, errors[3]));
}

51. HttpHandlerIntegrationTest#testHttpAggregatedMultiIngestionInvalidFutureCollectionTime()

View license
@Test
public void testHttpAggregatedMultiIngestionInvalidFutureCollectionTime() throws IOException, URISyntaxException {
    long timestamp = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty(CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS);
    String postfix = getPostfix();
    HttpResponse response = postMetric("333333", postAggregatedMultiPath, "sample_multi_aggregated_payload.json", timestamp, postfix);
    String errors[] = getBodyArray(response);
    assertEquals(400, response.getStatusLine().getStatusCode());
    assertEquals(4, errors.length);
    assertEquals(ERROR_TITLE, errors[0]);
    assertTrue(errors[1] + " did not match future pattern " + FUTURE_COLLECTION_TIME_REGEX, Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, errors[1]));
    assertTrue(errors[2] + " did not match future pattern " + FUTURE_COLLECTION_TIME_REGEX, Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, errors[2]));
    assertTrue(errors[3] + " did not match future pattern " + FUTURE_COLLECTION_TIME_REGEX, Pattern.matches(FUTURE_COLLECTION_TIME_REGEX, errors[3]));
}

52. HttpHandlerIntegrationTest#testHttpAggregatedMultiPartialInvalidCollectionTime()

View license
@Test
public void testHttpAggregatedMultiPartialInvalidCollectionTime() throws Exception {
    String postfix = getPostfix();
    long validTime = System.currentTimeMillis();
    long pastTime = System.currentTimeMillis() - TIME_DIFF_MS - Configuration.getInstance().getLongProperty(CoreConfig.BEFORE_CURRENT_COLLECTIONTIME_MS);
    long futureTime = System.currentTimeMillis() + TIME_DIFF_MS + Configuration.getInstance().getLongProperty(CoreConfig.AFTER_CURRENT_COLLECTIONTIME_MS);
    String jsonBody = getJsonFromFile("sample_multi_aggregated_payload_with_different_time.json", postfix);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_1%\"", validTime);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_2%\"", pastTime);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_3%\"", futureTime);
    jsonBody = jsonBody.replaceAll("%TENANT_ID_.%", TID);
    HttpResponse response = httpPost(TID, postAggregatedMultiPath, jsonBody);
    String[] output = getBodyArray(response);
    try {
        assertEquals("Should get status 207 from " + String.format(postAggregatedMultiPath, TID), 207, response.getStatusLine().getStatusCode());
        assertEquals("", output[0]);
    } finally {
        // Releases connection apparently
        EntityUtils.consume(response.getEntity());
    }
}

53. HttpHandlerIntegrationTest#testBadRequests()

View license
@Test
public void testBadRequests() throws Exception {
    HttpResponse response = httpPost(TID, postPath, "");
    try {
        assertEquals(400, response.getStatusLine().getStatusCode());
    } finally {
        // Releases connection apparently
        EntityUtils.consume(response.getEntity());
    }
    response = httpPost(TID, postPath, "Some incompatible json body");
    try {
        assertEquals(400, response.getStatusLine().getStatusCode());
    } finally {
        // Releases connection apparently
        EntityUtils.consume(response.getEntity());
    }
}

54. HttpHandlerIntegrationTest#testMultiTenantFailureWithoutTenant()

View license
@Test
public void testMultiTenantFailureWithoutTenant() throws Exception {
    HttpResponse response = postGenMetric(TID, "", postMultiPath);
    String[] output = getBodyArray(response);
    try {
        assertEquals(400, response.getStatusLine().getStatusCode());
        assertTrue(output[1] + " did not match no tenant id pattern " + NO_TENANT_ID_REGEX, Pattern.matches(NO_TENANT_ID_REGEX, output[1]));
        assertTrue(output[2] + " did not match no tenant id pattern " + NO_TENANT_ID_REGEX, Pattern.matches(NO_TENANT_ID_REGEX, output[2]));
        assertTrue(output[3] + " did not match no tenant id pattern " + NO_TENANT_ID_REGEX, Pattern.matches(NO_TENANT_ID_REGEX, output[3]));
    } finally {
        // Releases connection apparently
        EntityUtils.consume(response.getEntity());
    }
}

55. HttpHandlerIntegrationTest#testMultiTenantPartialFailureWithoutTenant()

View license
@Test
public void testMultiTenantPartialFailureWithoutTenant() throws Exception {
    String postfix = getPostfix();
    long validTime = System.currentTimeMillis();
    String jsonBody = getJsonFromFile("sample_multi_payload_with_different_time.json", postfix);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_1%\"", validTime);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_2%\"", validTime);
    jsonBody = updateTimeStampJson(jsonBody, "\"%TIMESTAMP_3%\"", validTime);
    jsonBody = jsonBody.replaceAll("%TENANT_ID_1%", TID);
    jsonBody = jsonBody.replaceAll("%TENANT_ID_2%", "");
    jsonBody = jsonBody.replaceAll("%TENANT_ID_3%", TID);
    HttpResponse response = httpPost(TID, postMultiPath, jsonBody);
    String[] output = getBodyArray(response);
    try {
        assertEquals("Should get status 207 from " + String.format(postMultiPath, TID), 207, response.getStatusLine().getStatusCode());
        assertEquals("", output[0]);
    } finally {
        // Releases connection apparently
        EntityUtils.consume(response.getEntity());
    }
}

56. HttpAnnotationsIntegrationTest#testHttpQueryAnnotationsHappyCase()

View license
@Test
public void testHttpQueryAnnotationsHappyCase() throws Exception {
    parameterMap = new HashMap<String, String>();
    parameterMap.put(Event.fromParameterName, String.valueOf(baseMillis - 86400000));
    parameterMap.put(Event.untilParameterName, String.valueOf(baseMillis + (86400000 * 3)));
    HttpGet get = new HttpGet(getAnnotationsQueryURI());
    HttpResponse response = client.execute(get);
    String responseString = EntityUtils.toString(response.getEntity());
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    Assert.assertFalse(responseString.equals("[]"));
}

57. HttpAnnotationsIntegrationTest#testQueryHttpAnnotationsStaleTimeStamps()

View license
@Test
public void testQueryHttpAnnotationsStaleTimeStamps() throws Exception {
    parameterMap = new HashMap<String, String>();
    parameterMap.put(Event.fromParameterName, String.valueOf(baseMillis - 86400000));
    parameterMap.put(Event.untilParameterName, String.valueOf(baseMillis));
    HttpGet get = new HttpGet(getAnnotationsQueryURI());
    HttpResponse response = client.execute(get);
    String responseString = EntityUtils.toString(response.getEntity());
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(responseString);
    Assert.assertTrue(responseString.equals("[]"));
}

58. HttpAnnotationsIntegrationTest#testQueryAnnotationsByTagName()

View license
@Test
public void testQueryAnnotationsByTagName() throws Exception {
    parameterMap = new HashMap<String, String>();
    parameterMap.put(Event.tagsParameterName, "1");
    HttpGet get = new HttpGet(getAnnotationsQueryURI());
    HttpResponse response = client.execute(get);
    String responseString = EntityUtils.toString(response.getEntity());
    Assert.assertNotNull(responseString);
    Assert.assertFalse(responseString.equals("[]"));
    //Test Using non-existing tag name
    parameterMap.put(Event.tagsParameterName, "NoSuchTag");
    get = new HttpGet(getAnnotationsQueryURI());
    response = client.execute(get);
    responseString = EntityUtils.toString(response.getEntity());
    Assert.assertNotNull(responseString);
    Assert.assertTrue(responseString.equals("[]"));
}

59. HttpAnnotationsIntegrationTest#testQueriesByMultipleTagsReturnNothing()

View license
@Test
public void testQueriesByMultipleTagsReturnNothing() throws Exception {
    parameterMap = new HashMap<String, String>();
    parameterMap.put(Event.tagsParameterName, "0,1");
    HttpGet get = new HttpGet(getAnnotationsQueryURI());
    HttpResponse response = client.execute(get);
    String responseString = EntityUtils.toString(response.getEntity());
    Assert.assertNotNull(responseString);
    Assert.assertTrue(responseString.equals("[]"));
    parameterMap.put(Event.tagsParameterName, "[0,1]");
    get = new HttpGet(getAnnotationsQueryURI());
    response = client.execute(get);
    responseString = EntityUtils.toString(response.getEntity());
    Assert.assertNotNull(responseString);
    Assert.assertTrue(responseString.equals("[]"));
    parameterMap.put(Event.tagsParameterName, "{0,1}");
    get = new HttpGet(getAnnotationsQueryURI());
    response = client.execute(get);
    responseString = EntityUtils.toString(response.getEntity());
    Assert.assertNotNull(responseString);
    Assert.assertTrue(responseString.equals("[]"));
}

60. CxfRsConsumerSimpleBindingTest#testListVipCustomers()

View license
@Test
public void testListVipCustomers() throws Exception {
    HttpGet get = new HttpGet("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/vip/gold");
    get.addHeader("Content-Type", "text/xml");
    get.addHeader("Accept", "text/xml");
    HttpResponse response = httpclient.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
    CustomerList cl = (CustomerList) jaxb.createUnmarshaller().unmarshal(new StringReader(EntityUtils.toString(response.getEntity())));
    List<Customer> vips = cl.getCustomers();
    assertEquals(2, vips.size());
    assertEquals(123, vips.get(0).getId());
    assertEquals(456, vips.get(1).getId());
}

61. CxfRsConsumerSimpleBindingTest#testMultipartPostWithParametersAndPayload()

View license
@Test
public void testMultipartPostWithParametersAndPayload() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/123?query=abcd");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);
    builder.addBinaryBody("part1", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg");
    builder.addBinaryBody("part2", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg");
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    builder.addTextBody("body", sw.toString(), ContentType.create("text/xml", Consts.UTF_8));
    post.setEntity(builder.build());
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

62. CxfRsConsumerSimpleBindingTest#testMultipartPostWithoutParameters()

View license
@Test
public void testMultipartPostWithoutParameters() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/withoutParameters");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);
    builder.addBinaryBody("part1", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg");
    builder.addBinaryBody("part2", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg");
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    builder.addTextBody("body", sw.toString(), ContentType.create("text/xml", Consts.UTF_8));
    post.setEntity(builder.build());
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

63. RestletHttpsWithSSLContextParametersTest#postRequestMessage()

View license
private void postRequestMessage(String message) throws Exception {
    // ensure jsse clients can validate the self signed dummy localhost cert, 
    // use the server keystore as the trust store for these tests
    URL trustStoreUrl = this.getClass().getClassLoader().getResource("jsse/localhost.ks");
    System.setProperty("javax.net.ssl.trustStore", trustStoreUrl.toURI().getPath());
    HttpPost post = new HttpPost("https://localhost:" + portNum + "/users/");
    post.addHeader(Exchange.CONTENT_TYPE, "application/xml");
    post.setEntity(new StringEntity(message));
    HttpResponse response = doExecute(post);
    assertHttpResponse(response, 200, "application/xml");
    String s = context.getTypeConverter().convertTo(String.class, response.getEntity().getContent());
    assertEquals("<status>OK</status>", s);
}

64. RestletMultiMethodsEndpointTest#testDeleteMethod()

View license
@Test
public void testDeleteMethod() throws Exception {
    HttpResponse response = doExecute(new HttpDelete("http://localhost:" + portNum + "/users/homer"));
    // delete is not allowed so we return 405
    assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED.getCode(), response.getStatusLine().getStatusCode());
    Header header = response.getFirstHeader("Allow");
    assertNotNull(header);
    String value = header.getValue().toUpperCase(Locale.US);
    assertTrue("POST should be allowed", value.contains("POST"));
    assertTrue("GET should be allowed", value.contains("GET"));
    assertTrue("PUT should be allowed", value.contains("PUT"));
}

65. RestletPostFormTest#testPostBody()

Project: camel
Source File: RestletPostFormTest.java
View license
@Test
public void testPostBody() throws Exception {
    HttpUriRequest method = new HttpPost("http://localhost:" + portNum + "/users");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("foo", "bar"));
    ((HttpEntityEnclosingRequestBase) method).setEntity(new UrlEncodedFormEntity(urlParameters));
    HttpResponse response = doExecute(method);
    assertHttpResponse(response, 200, "text/plain");
}

66. GithubClient#paginateGithub()

Project: cattle
Source File: GithubClient.java
View license
private List<HttpResponse> paginateGithub(String githubAccessToken, String url) throws IOException {
    List<HttpResponse> responses = new ArrayList<>();
    HttpResponse response = getFromGithub(githubAccessToken, url);
    responses.add(response);
    String nextUrl = nextGithubPage(response);
    while (StringUtils.isNotBlank(nextUrl)) {
        response = getFromGithub(githubAccessToken, nextUrl);
        responses.add(response);
        nextUrl = nextGithubPage(response);
    }
    return responses;
}

67. AppFabricTestBase#stopProgram()

Project: cdap
Source File: AppFabricTestBase.java
View license
protected void stopProgram(Id.Program program, String runId, int expectedStatusCode, String expectedMessage) throws Exception {
    String path;
    if (runId == null) {
        path = String.format("apps/%s/%s/%s/stop", program.getApplicationId(), program.getType().getCategoryName(), program.getId());
    } else {
        path = String.format("apps/%s/%s/%s/runs/%s/stop", program.getApplicationId(), program.getType().getCategoryName(), program.getId(), runId);
    }
    HttpResponse response = doPost(getVersionedAPIPath(path, program.getNamespaceId()));
    Assert.assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode());
    if (expectedMessage != null) {
        Assert.assertEquals(expectedMessage, EntityUtils.toString(response.getEntity()));
    }
}

68. AppLifecycleHttpHandlerTest#testAppWithConfig()

View license
@Test
public void testAppWithConfig() throws Exception {
    Id.Application appId = Id.Application.from(Id.Namespace.DEFAULT, "ConfigApp");
    Id.Artifact artifactId = Id.Artifact.from(Id.Namespace.DEFAULT, "appWithConfig", "1.0.0-SNAPSHOT");
    HttpResponse response = addAppArtifact(artifactId, ConfigTestApp.class);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    ConfigTestApp.ConfigClass config = new ConfigTestApp.ConfigClass("abc", "def");
    response = deploy(appId, new AppRequest<>(ArtifactSummary.from(artifactId), config));
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    JsonObject appDetails = getAppDetails(Id.Namespace.DEFAULT.getId(), "ConfigApp");
    Assert.assertEquals(GSON.toJson(config), appDetails.get("configuration").getAsString());
    deleteApp(appId, 200);
    deleteArtifact(artifactId, 200);
}

69. DashboardHttpHandlerTest#createDashboard()

Project: cdap
Source File: DashboardHttpHandlerTest.java
View license
private String createDashboard(String namespace, String contents, int expectedStatus) throws Exception {
    HttpResponse response = doPost(String.format("/v3/namespaces/%s/configuration/dashboards", namespace), contents);
    Assert.assertEquals(expectedStatus, response.getStatusLine().getStatusCode());
    if (expectedStatus == HttpResponseStatus.OK.getCode()) {
        String jsonData = EntityUtils.toString(response.getEntity());
        Map<String, String> idMap = GSON.fromJson(jsonData, MAP_STRING_STRING_TYPE);
        Assert.assertEquals(1, idMap.size());
        Assert.assertEquals(true, idMap.containsKey("id"));
        return idMap.get("id");
    }
    return null;
}

70. MonitorHandlerTest#testRestartInstances()

Project: cdap
Source File: MonitorHandlerTest.java
View license
@Test
public void testRestartInstances() throws Exception {
    String path = String.format("%s/system/services/%s/restart", Constants.Gateway.API_VERSION_3, Constants.Service.APP_FABRIC_HTTP);
    HttpResponse response = doPost(path);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
    path = String.format("%s/system/services/%s/latest-restart", Constants.Gateway.API_VERSION_3, Constants.Service.APP_FABRIC_HTTP);
    response = doGet(path);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
    RestartServiceInstancesStatus result = GSON.fromJson(new String(ByteStreams.toByteArray(response.getEntity().getContent()), Charsets.UTF_8), RestartServiceInstancesStatus.class);
    Assert.assertNotNull(result);
    Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result.getServiceName());
    Assert.assertEquals(RestartServiceInstancesStatus.RestartStatus.SUCCESS, result.getStatus());
}

71. MonitorHandlerTest#testSingleIdRestartInstances()

Project: cdap
Source File: MonitorHandlerTest.java
View license
@Test
public void testSingleIdRestartInstances() throws Exception {
    String path = String.format("%s/system/services/%s/instances/0/restart", Constants.Gateway.API_VERSION_3, Constants.Service.APP_FABRIC_HTTP);
    HttpResponse response = doPost(path);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
    path = String.format("%s/system/services/%s/latest-restart", Constants.Gateway.API_VERSION_3, Constants.Service.APP_FABRIC_HTTP);
    response = doGet(path);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
    RestartServiceInstancesStatus result = GSON.fromJson(new String(ByteStreams.toByteArray(response.getEntity().getContent()), Charsets.UTF_8), RestartServiceInstancesStatus.class);
    Assert.assertNotNull(result);
    Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result.getServiceName());
    Assert.assertEquals(RestartServiceInstancesStatus.RestartStatus.SUCCESS, result.getStatus());
}

72. MonitorHandlerTest#testInvalidIdRestartInstances()

Project: cdap
Source File: MonitorHandlerTest.java
View license
@Test
public void testInvalidIdRestartInstances() throws Exception {
    String path = String.format("%s/system/services/%s/instances/1000/restart", Constants.Gateway.API_VERSION_3, Constants.Service.APP_FABRIC_HTTP);
    HttpResponse response = doPost(path);
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), response.getStatusLine().getStatusCode());
    path = String.format("%s/system/services/%s/latest-restart", Constants.Gateway.API_VERSION_3, Constants.Service.APP_FABRIC_HTTP);
    response = doGet(path);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
    RestartServiceInstancesStatus result = GSON.fromJson(new String(ByteStreams.toByteArray(response.getEntity().getContent()), Charsets.UTF_8), RestartServiceInstancesStatus.class);
    Assert.assertNotNull(result);
    Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result.getServiceName());
    Assert.assertEquals(RestartServiceInstancesStatus.RestartStatus.FAILURE, result.getStatus());
}

73. NamespaceHttpHandlerTest#testNamespacesValidFlows()

Project: cdap
Source File: NamespaceHttpHandlerTest.java
View license
@Test
public void testNamespacesValidFlows() throws Exception {
    // get initial namespace list
    HttpResponse response = listAllNamespaces();
    assertResponseCode(200, response);
    List<JsonObject> namespaces = readListResponse(response);
    int initialSize = namespaces.size();
    // create and verify
    response = createNamespace(METADATA_VALID, NAME);
    assertResponseCode(200, response);
    response = listAllNamespaces();
    namespaces = readListResponse(response);
    Assert.assertEquals(initialSize + 1, namespaces.size());
    Assert.assertEquals(NAME, namespaces.get(0).get(NAME_FIELD).getAsString());
    Assert.assertEquals(DESCRIPTION, namespaces.get(0).get(DESCRIPTION_FIELD).getAsString());
    // cleanup
    response = deleteNamespace(NAME);
    assertResponseCode(200, response);
    response = listAllNamespaces();
    namespaces = readListResponse(response);
    Assert.assertEquals(initialSize, namespaces.size());
}

74. NamespaceHttpHandlerTest#testCreateDuplicate()

Project: cdap
Source File: NamespaceHttpHandlerTest.java
View license
@Test
public void testCreateDuplicate() throws Exception {
    // prepare - create namespace
    HttpResponse response = createNamespace(METADATA_VALID, NAME);
    assertResponseCode(200, response);
    response = getNamespace(NAME);
    JsonObject namespace = readGetResponse(response);
    Assert.assertNotNull(namespace);
    Assert.assertEquals(NAME, namespace.get(NAME_FIELD).getAsString());
    Assert.assertEquals(DESCRIPTION, namespace.get(DESCRIPTION_FIELD).getAsString());
    // create again with the same name
    response = createNamespace(METADATA_EMPTY_FIELDS, NAME);
    // create is idempotent, so response code is 200, but no updates should happen
    assertResponseCode(200, response);
    // check that no updates happened
    response = getNamespace(NAME);
    namespace = readGetResponse(response);
    Assert.assertNotNull(namespace);
    Assert.assertEquals(NAME, namespace.get(NAME_FIELD).getAsString());
    Assert.assertEquals(DESCRIPTION, namespace.get(DESCRIPTION_FIELD).getAsString());
    // cleanup
    response = deleteNamespace(NAME);
    assertResponseCode(200, response);
}

75. NamespaceHttpHandlerTest#testCreateWithConfig()

Project: cdap
Source File: NamespaceHttpHandlerTest.java
View license
@Test
public void testCreateWithConfig() throws Exception {
    // prepare - create namespace with config in its properties
    String propertiesString = String.format("{\"%s\":\"%s\", \"%s\":\"%s\", \"%s\":%s}", NAME_FIELD, NAME, DESCRIPTION_FIELD, DESCRIPTION, CONFIG_FIELD, "{\"scheduler.queue.name\":\"testSchedulerQueueName\"}");
    HttpResponse response = createNamespace(propertiesString, NAME);
    assertResponseCode(200, response);
    response = getNamespace(NAME);
    JsonObject namespace = readGetResponse(response);
    Assert.assertNotNull(namespace);
    Assert.assertEquals(NAME, namespace.get(NAME_FIELD).getAsString());
    Assert.assertEquals(DESCRIPTION, namespace.get(DESCRIPTION_FIELD).getAsString());
    Assert.assertEquals("testSchedulerQueueName", namespace.get(CONFIG_FIELD).getAsJsonObject().get("scheduler.queue.name").getAsString());
    response = deleteNamespace(NAME);
    assertResponseCode(200, response);
}

76. NamespaceHttpHandlerTest#testInvalidReservedId()

Project: cdap
Source File: NamespaceHttpHandlerTest.java
View license
@Test
public void testInvalidReservedId() throws Exception {
    HttpResponse response = createNamespace(METADATA_VALID, INVALID_NAME);
    assertResponseCode(400, response);
    // '-' is not allowed anymore
    response = createNamespace(METADATA_VALID, "my-namespace");
    assertResponseCode(400, response);
    // 'default' and 'system' are reserved namespaces
    response = createNamespace(METADATA_VALID, Id.Namespace.DEFAULT.getId());
    assertResponseCode(400, response);
    response = createNamespace(METADATA_VALID, Id.Namespace.SYSTEM.getId());
    assertResponseCode(400, response);
    // we allow deleting the contents in default namespace. However, the namespace itself should never be deleted
    deploy(AppWithDataset.class);
    response = deleteNamespace(Id.Namespace.DEFAULT.getId());
    assertResponseCode(200, response);
    response = getNamespace(Id.Namespace.DEFAULT.getId());
    Assert.assertEquals(0, getAppList(Id.Namespace.DEFAULT.getId()).size());
    assertResponseCode(200, response);
    // there is no system namespace
    response = deleteNamespace(Id.Namespace.SYSTEM.getId());
    assertResponseCode(404, response);
}

77. NotificationFeedHttpHandlerTest#testCreateMissingEmptyOrInvalidName()

View license
@Test
public void testCreateMissingEmptyOrInvalidName() throws Exception {
    // name must be non-null, non-empty
    JsonObject object = new JsonObject();
    object.add(DESCRIPTION_FIELD, GSON.toJsonTree(DESCRIPTION));
    String metadata = GSON.toJson(object);
    HttpResponse response = createFeed(NAMESPACE, CATEGORY, "", metadata);
    assertResponseCode(404, response);
    response = createFeed(NAMESPACE, CATEGORY, "$.a", metadata);
    assertResponseCode(400, response);
}

78. NotificationFeedHttpHandlerTest#testCreateMissingEmptyOrInvalidNamespace()

View license
@Test
public void testCreateMissingEmptyOrInvalidNamespace() throws Exception {
    // namespace must be non-null, non-empty
    JsonObject object = new JsonObject();
    object.add(DESCRIPTION_FIELD, GSON.toJsonTree(DESCRIPTION));
    String metadata = GSON.toJson(object);
    HttpResponse response = createFeed("", CATEGORY, NAME, metadata);
    assertResponseCode(404, response);
    response = createFeed("$.a", CATEGORY, NAME, metadata);
    assertResponseCode(400, response);
}

79. NotificationFeedHttpHandlerTest#testCreateMissingEmptyOrInvalidCategory()

View license
@Test
public void testCreateMissingEmptyOrInvalidCategory() throws Exception {
    // category must be non-null, non-empty
    JsonObject object = new JsonObject();
    object.add(DESCRIPTION_FIELD, GSON.toJsonTree(DESCRIPTION));
    String metadata = GSON.toJson(object);
    HttpResponse response = createFeed(NAMESPACE, "", NAME, metadata);
    assertResponseCode(404, response);
    response = createFeed(NAMESPACE, "$.a", NAME, metadata);
    assertResponseCode(400, response);
}

80. PreferencesHttpHandlerTest#getProperty()

View license
private Map<String, String> getProperty(String uri, boolean resolved, int expectedStatus) throws Exception {
    String request = String.format("/v3/%s/preferences", uri);
    if (resolved) {
        request += "?resolved=true";
    }
    HttpResponse response = doGet(request);
    Assert.assertEquals(expectedStatus, response.getStatusLine().getStatusCode());
    if (expectedStatus == 200) {
        String s = EntityUtils.toString(response.getEntity());
        return GSON.fromJson(s, MAP_STRING_STRING_TYPE);
    }
    return null;
}

81. ProgramLifecycleHttpHandlerTest#testWorkerSpecification()

View license
/**
   * Worker Specification tests
   */
@Test
public void testWorkerSpecification() throws Exception {
    // deploy AppWithWorker in namespace1 and verify
    HttpResponse response = deploy(AppWithWorker.class, Constants.Gateway.API_VERSION_3_TOKEN, TEST_NAMESPACE1);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    verifyProgramSpecification(TEST_NAMESPACE1, AppWithWorker.NAME, ProgramType.WORKER.getCategoryName(), AppWithWorker.WORKER);
    Assert.assertEquals(404, getProgramSpecificationResponseCode(TEST_NAMESPACE2, AppWithWorker.NAME, ProgramType.WORKER.getCategoryName(), AppWithWorker.WORKER));
}

82. ProgramLifecycleHttpHandlerTest#testServiceSpecification()

View license
@Test
public void testServiceSpecification() throws Exception {
    deploy(AppWithServices.class);
    HttpResponse response = doGet("/v3/namespaces/default/apps/AppWithServices/services/NoOpService");
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    Set<ServiceHttpEndpoint> expectedEndpoints = ImmutableSet.of(new ServiceHttpEndpoint("GET", "/ping"), new ServiceHttpEndpoint("POST", "/multi"), new ServiceHttpEndpoint("GET", "/multi"), new ServiceHttpEndpoint("GET", "/multi/ping"));
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ServiceSpecification.class, new ServiceSpecificationCodec());
    Gson gson = gsonBuilder.create();
    ServiceSpecification specification = readResponse(response, ServiceSpecification.class, gson);
    Set<ServiceHttpEndpoint> returnedEndpoints = new HashSet<>();
    for (HttpServiceHandlerSpecification httpServiceHandlerSpecification : specification.getHandlers().values()) {
        returnedEndpoints.addAll(httpServiceHandlerSpecification.getEndpoints());
    }
    Assert.assertEquals("NoOpService", specification.getName());
    Assert.assertTrue(returnedEndpoints.equals(expectedEndpoints));
}

83. ProgramLifecycleHttpHandlerTest#testMultipleWorkflowSchedules()

View license
@Test
public void testMultipleWorkflowSchedules() throws Exception {
    // Deploy the app
    HttpResponse response = deploy(AppWithMultipleScheduledWorkflows.class, Constants.Gateway.API_VERSION_3_TOKEN, TEST_NAMESPACE2);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    List<ScheduleSpecification> someSchedules = getSchedules(TEST_NAMESPACE2, APP_WITH_MULTIPLE_WORKFLOWS_APP_NAME, APP_WITH_MULTIPLE_WORKFLOWS_SOMEWORKFLOW);
    Assert.assertEquals(2, someSchedules.size());
    Assert.assertEquals(APP_WITH_MULTIPLE_WORKFLOWS_SOMEWORKFLOW, someSchedules.get(0).getProgram().getProgramName());
    Assert.assertEquals(APP_WITH_MULTIPLE_WORKFLOWS_SOMEWORKFLOW, someSchedules.get(1).getProgram().getProgramName());
    List<ScheduleSpecification> anotherSchedules = getSchedules(TEST_NAMESPACE2, APP_WITH_MULTIPLE_WORKFLOWS_APP_NAME, APP_WITH_MULTIPLE_WORKFLOWS_ANOTHERWORKFLOW);
    Assert.assertEquals(3, anotherSchedules.size());
    Assert.assertEquals(APP_WITH_MULTIPLE_WORKFLOWS_ANOTHERWORKFLOW, anotherSchedules.get(0).getProgram().getProgramName());
    Assert.assertEquals(APP_WITH_MULTIPLE_WORKFLOWS_ANOTHERWORKFLOW, anotherSchedules.get(1).getProgram().getProgramName());
    Assert.assertEquals(APP_WITH_MULTIPLE_WORKFLOWS_ANOTHERWORKFLOW, anotherSchedules.get(2).getProgram().getProgramName());
}

84. ProgramLifecycleHttpHandlerTest#verifyProgramList()

View license
private void verifyProgramList(String namespace, String appName, final ProgramType programType, int expected) throws Exception {
    HttpResponse response = requestAppDetail(namespace, appName);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    String json = EntityUtils.toString(response.getEntity());
    ApplicationDetail appDetail = GSON.fromJson(json, ApplicationDetail.class);
    Collection<ProgramRecord> programs = Collections2.filter(appDetail.getPrograms(), new Predicate<ProgramRecord>() {

        @Override
        public boolean apply(@Nullable ProgramRecord record) {
            return programType.getCategoryName().equals(record.getType().getCategoryName());
        }
    });
    Assert.assertEquals(expected, programs.size());
}

85. TransactionHttpHandlerTest#testInvalidateTx()

View license
/**
   * Tests invalidating a transaction.
   * @throws Exception
   */
@Test
public void testInvalidateTx() throws Exception {
    TransactionSystemClient txClient = getTxClient();
    Transaction tx1 = txClient.startShort();
    HttpResponse response = doPost("/v3/transactions/" + tx1.getWritePointer() + "/invalidate");
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    Transaction tx2 = txClient.startShort();
    txClient.commit(tx2);
    response = doPost("/v3/transactions/" + tx2.getWritePointer() + "/invalidate");
    Assert.assertEquals(409, response.getStatusLine().getStatusCode());
    Assert.assertEquals(400, doPost("/v3/transactions/foobar/invalidate").getStatusLine().getStatusCode());
}

86. TransactionHttpHandlerTest#testGetInvalidSize()

View license
@Test
public void testGetInvalidSize() throws Exception {
    TransactionSystemClient txClient = getTxClient();
    // Reset state, and assert no invalid transactions are present
    txClient.resetState();
    Assert.assertEquals(0, txClient.getInvalidSize());
    // Start few transactions and invalidate them
    Transaction tx1 = txClient.startShort();
    Transaction tx2 = txClient.startLong();
    Transaction tx3 = txClient.startLong();
    Assert.assertTrue(txClient.invalidate(tx1.getWritePointer()));
    Assert.assertTrue(txClient.invalidate(tx2.getWritePointer()));
    Assert.assertTrue(txClient.invalidate(tx3.getWritePointer()));
    Assert.assertEquals(3, txClient.getInvalidSize());
    // Assert through REST API
    HttpResponse response = doGet("/v3/transactions/invalid/size");
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    Map<String, Integer> resultMap = GSON.fromJson(EntityUtils.toString(response.getEntity()), STRING_INT_TYPE);
    Assert.assertNotNull(resultMap);
    Assert.assertEquals(3, (int) resultMap.get("size"));
}

87. WorkflowHttpHandlerTest#setAndTestRuntimeArgs()

Project: cdap
Source File: WorkflowHttpHandlerTest.java
View license
private void setAndTestRuntimeArgs(Id.Program programId, Map<String, String> args) throws Exception {
    HttpResponse response;
    String argString = GSON.toJson(args, new TypeToken<Map<String, String>>() {
    }.getType());
    String path = String.format("apps/%s/workflows/%s/runtimeargs", programId.getApplicationId(), programId.getId());
    String versionedRuntimeArgsUrl = getVersionedAPIPath(path, Constants.Gateway.API_VERSION_3_TOKEN, programId.getNamespaceId());
    response = doPut(versionedRuntimeArgsUrl, argString);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    response = doGet(versionedRuntimeArgsUrl);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    String responseEntity = EntityUtils.toString(response.getEntity());
    Map<String, String> argsRead = GSON.fromJson(responseEntity, new TypeToken<Map<String, String>>() {
    }.getType());
    Assert.assertEquals(args.size(), argsRead.size());
}

88. WorkflowHttpHandlerTest#verifyMultipleConcurrentRuns()

Project: cdap
Source File: WorkflowHttpHandlerTest.java
View license
private void verifyMultipleConcurrentRuns(Id.Program workflowId) throws Exception {
    verifyProgramRuns(workflowId, ProgramRunStatus.RUNNING.name(), 1);
    List<RunRecord> historyRuns = getProgramRuns(workflowId, "running");
    Assert.assertEquals(2, historyRuns.size());
    HttpResponse response = getWorkflowCurrentStatus(workflowId, historyRuns.get(0).getPid());
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    String json = EntityUtils.toString(response.getEntity());
    List<WorkflowActionNode> nodes = GSON.fromJson(json, LIST_WORKFLOWACTIONNODE_TYPE);
    Assert.assertEquals(1, nodes.size());
    Assert.assertEquals(ConcurrentWorkflowApp.SimpleAction.class.getSimpleName(), nodes.get(0).getProgram().getProgramName());
    response = getWorkflowCurrentStatus(workflowId, historyRuns.get(1).getPid());
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    json = EntityUtils.toString(response.getEntity());
    nodes = GSON.fromJson(json, LIST_WORKFLOWACTIONNODE_TYPE);
    Assert.assertEquals(1, nodes.size());
    Assert.assertEquals(ConcurrentWorkflowApp.SimpleAction.class.getSimpleName(), nodes.get(0).getProgram().getProgramName());
}

89. MetricsReporterHookTestRun#testMetricsSuccess()

View license
@Test
public void testMetricsSuccess() throws Exception {
    String context = "tag=namespace:system&tag=component:appfabric&tag=handler:PingHandler&tag=method:ping";
    // todo: better fix needed: CDAP-2174
    TimeUnit.SECONDS.sleep(1);
    long received = getMetricValue(context, "system.request.received");
    long successful = getMetricValue(context, "system.response.successful");
    long clientError = getMetricValue(context, "system.response.client-error");
    // Make a successful call
    HttpResponse response = GatewayFastTestsSuite.doGet("/ping");
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
    // received and successful should have increased by one, clientError should be the same
    verifyMetrics(received + 1, context, "system.request.received");
    verifyMetrics(successful + 1, context, "system.response.successful");
    verifyMetrics(clientError, context, "system.response.client-error");
}

90. MetricsReporterHookTestRun#testMetricsNotFound()

View license
@Test
public void testMetricsNotFound() throws Exception {
    String context = "&tag=namespace:system&tag=component:appfabric&tag=handler:StreamHandler&tag=method:getInfo";
    long received = getMetricValue(context, "system.request.received");
    long successful = getMetricValue(context, "system.response.successful");
    long clientError = getMetricValue(context, "system.response.client-error");
    // Get info of non-existent stream
    HttpResponse response = GatewayFastTestsSuite.doGet("/v3/namespaces/default/streams/metrics-hook-test-non-existent-stream");
    Assert.assertEquals(HttpResponseStatus.NOT_FOUND.getCode(), response.getStatusLine().getStatusCode());
    // received and clientError should have increased by one, successful should be the same
    verifyMetrics(received + 1, context, "system.request.received");
    verifyMetrics(successful, context, "system.response.successful");
    verifyMetrics(clientError + 1, context, "system.response.client-error");
}

91. MetricsReporterHookTestRun#getMetricValue()

View license
private static long getMetricValue(String context, String metricName) throws Exception {
    HttpResponse response = doPost("/v3/metrics/query?" + context + "&metric=" + metricName);
    Assert.assertEquals("POST " + context + " did not return 200 status.", HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    String content = new String(ByteStreams.toByteArray(response.getEntity().getContent()), Charsets.UTF_8);
    // response has the form:
    // {"startTime":0,"endTime":...,"series":[{"metricName":"...","grouping":{},"data":[{"time":0,"value":<value>}]}]}
    JsonObject json = new Gson().fromJson(content, JsonObject.class);
    JsonArray array = json.getAsJsonArray("series");
    if (array.size() > 0) {
        array = array.get(0).getAsJsonObject().getAsJsonArray("data");
        if (array.size() > 0) {
            return array.get(0).getAsJsonObject().get("value").getAsLong();
        }
    }
    return 0L;
}

92. LogHandlerTestRun#testNextRunId()

Project: cdap
Source File: LogHandlerTestRun.java
View license
private void testNextRunId(String appId, String entityType, String entityId, String namespace, String format) throws Exception {
    Id.Program id = Id.Program.from(namespace, appId, ProgramType.valueOfCategoryName(entityType), entityId);
    RunRecord runRecord = mockLogReader.getRunRecord(id);
    int expectedEvents = 20;
    if (runRecord.getStatus() == ProgramRunStatus.RUNNING || runRecord.getStatus() == ProgramRunStatus.SUSPENDED) {
        expectedEvents = 30;
    }
    String nextNoFromUrl = String.format("apps/%s/%s/%s/runs/%s/logs/next?format=%s&max=100", appId, entityType, entityId, runRecord.getPid(), format);
    HttpResponse response = doGet(getVersionedAPIPath(nextNoFromUrl, namespace));
    verifyLogs(response, entityId, format, true, false, true, expectedEvents, 20);
}

93. LogHandlerTestRun#testPrevRunId()

Project: cdap
Source File: LogHandlerTestRun.java
View license
private void testPrevRunId(String appId, String entityType, String entityId, String namespace, String format) throws Exception {
    Id.Program id = Id.Program.from(namespace, appId, ProgramType.valueOfCategoryName(entityType), entityId);
    RunRecord runRecord = mockLogReader.getRunRecord(id);
    int expectedEvents = 20;
    if (runRecord.getStatus() == ProgramRunStatus.RUNNING || runRecord.getStatus() == ProgramRunStatus.SUSPENDED) {
        expectedEvents = 30;
    }
    String prevRunIdUrl = String.format("apps/%s/%s/%s/runs/%s/logs/prev?format=%s&max=100", appId, entityType, entityId, runRecord.getPid(), format);
    HttpResponse response = doGet(getVersionedAPIPath(prevRunIdUrl, namespace));
    verifyLogs(response, entityId, format, true, false, true, expectedEvents, 20);
}

94. LogHandlerTestRun#testLogsRunId()

Project: cdap
Source File: LogHandlerTestRun.java
View license
private void testLogsRunId(String appId, String entityType, String entityId, String namespace, String format) throws Exception {
    Id.Program id = Id.Program.from(namespace, appId, ProgramType.valueOfCategoryName(entityType), entityId);
    RunRecord runRecord = mockLogReader.getRunRecord(id);
    int expectedEvents = 20;
    if (runRecord.getStatus() == ProgramRunStatus.RUNNING || runRecord.getStatus() == ProgramRunStatus.SUSPENDED) {
        expectedEvents = 30;
    }
    long startTime = MockLogReader.getMockTimeSecs(0);
    long stopTime = MockLogReader.getMockTimeSecs(100);
    String nextNoFromUrl = String.format("apps/%s/%s/%s/runs/%s/logs?format=%s&start=%s&stop=%s", appId, entityType, entityId, runRecord.getPid(), format, startTime, stopTime);
    HttpResponse response = doGet(getVersionedAPIPath(nextNoFromUrl, namespace));
    verifyLogs(response, entityId, format, true, true, true, expectedEvents, 20);
}

95. LogHandlerTestRun#testLogs()

Project: cdap
Source File: LogHandlerTestRun.java
View license
private void testLogs(String appId, String entityType, String entityId, String namespace) throws Exception {
    long startTime = MockLogReader.getMockTimeSecs(20);
    long stopTime = MockLogReader.getMockTimeSecs(35);
    String logsUrl = String.format("apps/%s/%s/%s/logs?start=%s&stop=%s", appId, entityType, entityId, startTime, stopTime);
    HttpResponse response = doGet(getVersionedAPIPath(logsUrl, namespace));
    verifyLogs(response, entityId, "text", false, true, true, 15, 20);
    // Try with invalid time range -> start > stop
    logsUrl = String.format("apps/%s/%s/%s/logs?start=%s&stop=%s", appId, entityType, entityId, 350, 300);
    response = doGet(getVersionedAPIPath(logsUrl, namespace));
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), response.getStatusLine().getStatusCode());
}

96. MetricsHandlerTestRun#testInvalidRequest()

Project: cdap
Source File: MetricsHandlerTestRun.java
View license
@Test
public void testInvalidRequest() throws Exception {
    // test invalid request - query without any query Params and body content
    HttpResponse response = doPost("/v3/metrics/query", null);
    Assert.assertEquals(400, response.getStatusLine().getStatusCode());
    // batch query with empty metrics list
    QueryRequestFormat invalidQuery = new QueryRequestFormat(ImmutableMap.of("namespace", "myspace", "app", "WordCount1", "flow", "WordCounter", "flowlet", "splitter"), ImmutableList.<String>of(), ImmutableList.<String>of(), ImmutableMap.of("aggregate", "true"));
    response = doPost("/v3/metrics/query", GSON.toJson(ImmutableMap.of("invalid", invalidQuery)));
    Assert.assertEquals(400, response.getStatusLine().getStatusCode());
    // test invalid request - query without any metric Params
    response = doPost("/v3/metrics/query?context=namespace.default", null);
    Assert.assertEquals(400, response.getStatusLine().getStatusCode());
    response = doPost("/v3/metrics/query?tag=namespace.default", null);
    Assert.assertEquals(400, response.getStatusLine().getStatusCode());
}

97. ExternalAuthenticationServerTestBase#testInvalidAuthentication()

View license
/**
   * Test an unauthorized request to server.
   * @throws Exception
   */
@Test
public void testInvalidAuthentication() throws Exception {
    HttpClient client = getHTTPClient();
    String uri = String.format("%s://%s:%d/%s", getProtocol(), server.getSocketAddress().getAddress().getHostAddress(), server.getSocketAddress().getPort(), GrantAccessToken.Paths.GET_TOKEN);
    HttpGet request = new HttpGet(uri);
    request.addHeader("Authorization", "xxxxx");
    HttpResponse response = client.execute(request);
    // Request is Unauthorized
    assertEquals(401, response.getStatusLine().getStatusCode());
    verify(TEST_AUDIT_LOGGER, timeout(10000).atLeastOnce()).trace(contains("401"));
}

98. ExternalAuthenticationServerTestBase#testStatusResponse()

View license
/**
   * Test an unauthorized status request to server.
   * @throws Exception
   */
@Test
public void testStatusResponse() throws Exception {
    HttpClient client = getHTTPClient();
    String uri = String.format("%s://%s:%d/%s", getProtocol(), server.getSocketAddress().getAddress().getHostAddress(), server.getSocketAddress().getPort(), Constants.EndPoints.STATUS);
    HttpGet request = new HttpGet(uri);
    HttpResponse response = client.execute(request);
    // Status request is authorized without any extra headers
    assertEquals(200, response.getStatusLine().getStatusCode());
}

99. ExternalAuthenticationServerTestBase#testInvalidPath()

View license
/**
   * Test that invalid paths return a 404 Not Found.
   * @throws Exception
   */
@Test
public void testInvalidPath() throws Exception {
    HttpClient client = getHTTPClient();
    String uri = String.format("%s://%s:%d/%s", getProtocol(), server.getSocketAddress().getAddress().getHostAddress(), server.getSocketAddress().getPort(), "invalid");
    HttpGet request = new HttpGet(uri);
    request.addHeader("Authorization", "Basic YWRtaW46cmVhbHRpbWU=");
    HttpResponse response = client.execute(request);
    assertEquals(404, response.getStatusLine().getStatusCode());
}

100. DownloadExampleActivity#downloadBitmap()

View license
private Bitmap downloadBitmap(String url) throws IOException {
    HttpUriRequest request = new HttpGet(url.toString());
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        byte[] bytes = EntityUtils.toByteArray(entity);
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bitmap;
    } else {
        throw new IOException("Download failed, HTTP response code " + statusCode + " - " + statusLine.getReasonPhrase());
    }
}