public void testResponseProcessing() throws Exception { ContentDecoder contentDecoder = mock(ContentDecoder.class); IOControl ioControl = mock(IOControl.class); HttpContext httpContext = mock(HttpContext.class); HeapBufferedAsyncResponseConsumer consumer = spy(new HeapBufferedAsyncResponseConsumer(TEST_BUFFER_LIMIT)); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); HttpResponse httpResponse = new BasicHttpResponse(statusLine); httpResponse.setEntity(new StringEntity("test", ContentType.TEXT_PLAIN)); //everything goes well consumer.responseReceived(httpResponse); consumer.consumeContent(contentDecoder, ioControl); consumer.responseCompleted(httpContext); verify(consumer).releaseResources(); verify(consumer).buildResult(httpContext); assertTrue(consumer.isDone()); assertSame(httpResponse, consumer.getResult()); consumer.responseCompleted(httpContext); verify(consumer, times(1)).releaseResources(); verify(consumer, times(1)).buildResult(httpContext); }
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); consumer.onResponseReceived(new BasicHttpResponse(statusLine)); final AtomicReference<Long> contentLength = new AtomicReference<>(); HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) { @Override public long getContentLength() { return contentLength.get(); } }; contentLength.set(randomLong(bufferLimit)); consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE)); try { consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); } catch(ContentTooLongException e) { assertEquals("entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage()); } }
@Before @SuppressWarnings("unchecked") public void createRestClient() throws IOException { CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() { @Override public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable { HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0]; HttpUriRequest request = (HttpUriRequest)requestProducer.generateRequest(); HttpHost httpHost = requestProducer.getTarget(); HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2]; assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class)); FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3]; //return the desired status code or exception depending on the path if (request.getURI().getPath().equals("/soe")) { futureCallback.failed(new SocketTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/coe")) { futureCallback.failed(new ConnectTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/ioe")) { futureCallback.failed(new IOException(httpHost.toString())); } else { int statusCode = Integer.parseInt(request.getURI().getPath().substring(1)); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); futureCallback.completed(new BasicHttpResponse(statusLine)); } return null; } }); int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5); httpHosts = new HttpHost[numHosts]; for (int i = 0; i < numHosts; i++) { httpHosts[i] = new HttpHost("localhost", 9200 + i); } failureListener = new HostsTrackingFailureListener(); restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener); }
@Test public void testExecute_non2xx_exception() throws IOException { HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found")); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes())); resp.setEntity(entity); Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class)); Map<String, String> headers = new HashMap<>(); headers.put("Account-Id", "fubar"); headers.put("Content-Type", "application/json"); try { client.execute( new GenericApiGatewayRequestBuilder() .withBody(new ByteArrayInputStream("test request".getBytes())) .withHttpMethod(HttpMethodName.POST) .withHeaders(headers) .withResourcePath("/test/orders").build()); Assert.fail("Expected exception"); } catch (GenericApiGatewayException e) { assertEquals("Wrong status code", 404, e.getStatusCode()); assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage()); } }
private Segment segmentInResponseToCode(int code) { NoOpResponseHandler responseHandler = new NoOpResponseHandler(); TracedResponseHandler<String> tracedResponseHandler = new TracedResponseHandler<>(responseHandler); HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, code, "")); Segment segment = AWSXRay.beginSegment("test"); AWSXRay.beginSubsegment("someHttpCall"); try { tracedResponseHandler.handleResponse(httpResponse); } catch (IOException e) { throw new RuntimeException(e); } AWSXRay.endSubsegment(); AWSXRay.endSegment(); return segment; }
@Test public void post_whenResponseIsFailure_logsException() throws IOException { ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class); HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 400, "")); response.setEntity(new StringEntity("failure reason here")); when(httpClient.execute(requestCaptor.capture())).thenReturn(response); MsTeamsNotification w = factory.getMsTeamsNotification(httpClient); MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent(); content.setBuildDescriptionWithLinkSyntax("http://foo"); content.setCommits(new ArrayList<Commit>()); w.setPayload(content); w.setEnabled(true); w.post(); assertNotNull(w.getResponse()); assertFalse(w.getResponse().getOk()); }
@Test public void logsRequestAndResponseFields() { HttpContext context = new BasicHttpContext(); context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com"); OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor(new FakeClock(20)); interceptor.process(new BasicHttpRequest("GET", "/something"), context); interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context); Map<String, Object> fields = new ConcurrentHashMap<>(); fields.put("requestMethod", "GET"); fields.put("requestURI", "http://www.google.com/something"); testAppender.assertEvent(0, INFO, "Outbound request start", appendEntries(fields)); fields.put("responseTime", 20L); fields.put("responseCode", 200); testAppender.assertEvent(1, INFO, "Outbound request finish", appendEntries(fields)); }
@Test public void allowEmptyConstructorToBuildDefaultClock() { testAppender.clearEvents(); HttpContext context = new BasicHttpContext(); context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com"); OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor(); interceptor.process(new BasicHttpRequest("GET", "/something"), context); interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context); assertThat(testAppender.getEvents()).extracting("message") .contains("Outbound request start", Index.atIndex(0)) .contains("Outbound request finish", Index.atIndex(1)); }
/** * Wait for the server is ready. */ private void waitForServerReady() throws IOException, InterruptedException { final HttpGet httpget = new HttpGet(getPingUri()); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "")); int counter = 0; while (true) { try { response = httpclient.execute(httpget); final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { break; } checkRetries(counter); } catch (final HttpHostConnectException ex) { // NOSONAR - Wait, and check later log.info("Check failed, retrying..."); checkRetries(counter); } finally { EntityUtils.consume(response.getEntity()); } counter++; } }
@Test public void downloadNewStatementsClosesEntityStream() throws Exception { final Config filesStep = ConfigFactory.parseString("{ method = get, path = /files }"); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); final HttpEntity entity = mock(HttpEntity.class); final InputStream stream = mock(InputStream.class); doReturn(Collections.singletonList(filesStep)).when(config).getConfigList("fileList"); when(client.execute(any(HttpGet.class))).thenReturn(response); when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null)); when(response.getEntity()).thenReturn(entity); when(entity.isStreaming()).thenReturn(true); when(entity.getContent()).thenReturn(stream); download.downloadNewStatements(); verify(response).getEntity(); verify(entity).getContent(); verify(stream).close(); }
@Test public void downloadNewStatementsCapturesResult() throws Exception { final Config filesStep = ConfigFactory.parseString("{ method = get, path = /files, " + "result = { format = json, extract = [{ name = var, selector = x }] } }"); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); final HttpEntity entity = mock(HttpEntity.class); final InputStream stream = new ByteArrayInputStream("{\"x\":\"value\"}".getBytes("UTF-8")); doReturn(Collections.singletonList(filesStep)).when(config).getConfigList("fileList"); when(client.execute(any(HttpGet.class))).thenReturn(response); when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null)); when(response.getEntity()).thenReturn(entity); when(entity.getContent()).thenReturn(stream); download.downloadNewStatements(); verify(response).getEntity(); verify(context).putValue("var", "value"); }
@Test public void downloadNewStatementsCapturesFileList() throws Exception { final Config filesStep = ConfigFactory.parseString("{ method = get, path = /files, " + "result = { format = html, files.selector = { path = li, fields = [\"text()\"] } } }"); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); final HttpEntity entity = mock(HttpEntity.class); final InputStream stream = new ByteArrayInputStream("<html><body><li>file url</li></body></html>".getBytes("UTF-8")); doReturn(Collections.singletonList(filesStep)).when(config).getConfigList("fileList"); when(context.getBaseUrl()).thenReturn("http://example.com"); when(client.execute(any(HttpGet.class))).thenReturn(response); when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null)); when(response.getEntity()).thenReturn(entity); when(entity.getContent()).thenReturn(stream); download.downloadNewStatements(); verify(response).getEntity(); verify(context).addFile(Collections.singletonList("file url")); }
@Test public void downloadNewStatementsSavesNewFile() throws Exception { final Config downloadStep = ConfigFactory.parseString("{ method = get, path = /files, save = true }"); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); final HttpEntity entity = mock(HttpEntity.class); final InputStream stream = new ByteArrayInputStream("statement content".getBytes("UTF-8")); final List<Object> fileKeys = Collections.singletonList("file key"); final File statement = new File("./test.txt"); if (statement.exists()) statement.delete(); doReturn(Collections.emptyList()).when(config).getConfigList("fileList"); doReturn(Collections.singletonList(downloadStep)).when(config).getConfigList("download"); when(context.getFileList()).thenReturn(Collections.singletonList(fileKeys)); when(context.getFile(fileKeys)).thenReturn(statement); when(client.execute(any(HttpGet.class))).thenReturn(response); when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null)); when(response.getEntity()).thenReturn(entity); when(entity.getContent()).thenReturn(stream); download.downloadNewStatements(); verify(response).getEntity(); verify(context).addStatement(statement); }
public void canCreateInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_CREATED, "Created"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/created.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); Instance instance = new Instance() .setName("some_name") .setPackageId(new UUID(12L, 24L)) .setImage(new UUID(8L, 16L)) .setTags(Collections.singletonMap(TEST_TAG_KEY, TEST_TAG)); try (CloudApiConnectionContext context = createMockContext(response)) { final Instance created = instanceApi.create(context, instance); assertNotNull(created); assertNotNull(created.getId()); } }
public void errorsCorrectlyWhenDeletingUnknownInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_NOT_FOUND, "Not Found"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/error/not_found.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); boolean thrown = false; try (CloudApiConnectionContext context = createMockContext(response)) { UUID instanceId = new UUID(512L, 1024L); instanceApi.delete(context, instanceId); } catch (CloudApiResponseException e) { thrown = true; assertTrue(e.getMessage().contains("VM not found"), "Unexpected message on exception"); } assertTrue(thrown, "CloudApiResponseException never thrown"); }
public void canWaitForStateChangeWhenItAlreadyChanged() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/domain/instance.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9"); final String stateToChangeFrom = "provisioning"; try (CloudApiConnectionContext context = createMockContext(response)) { final Instance running = instanceApi.waitForStateChange( context, instanceId, stateToChangeFrom, 0L, 0L); assertEquals(running.getId(), instanceId, "ids should match"); assertNotEquals(running.getState(), stateToChangeFrom, "shouldn't be in [" + stateToChangeFrom + "] state"); assertEquals(running.getState(), "running", "should be in running state"); } }
public void canFindRunningInstanceById() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/domain/instance.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9"); try (CloudApiConnectionContext context = createMockContext(response)) { Instance found = instanceApi.findById(context, instanceId); assertNotNull(found, "expecting instance to be found"); assertEquals(found.getId(), instanceId, "expecting ids to match"); } }
public void canAddAdditionalTagsToAnInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/additional_tags.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9"); try (CloudApiConnectionContext context = createMockContext(response)) { Map<String, String> tags = instanceApi.addTags(context, instanceId, ImmutableMap.of("additional_1", "val1", "additional_2", "val2")); assertEquals(tags.size(), 3, "Expecting 3 tags"); assertEquals(tags.get("name"), "value"); assertEquals(tags.get("additional_1"), "val1"); assertEquals(tags.get("additional_2"), "val2"); } }
public void canReplaceTagsOnAnInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/replace_tags.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9"); try (CloudApiConnectionContext context = createMockContext(response)) { Map<String, String> tags = instanceApi.replaceTags(context, instanceId, ImmutableMap.of("additional_1", "val1", "additional_2", "val2")); assertEquals(tags.size(), 2, "Expecting 2 tags"); assertEquals(tags.get("additional_1"), "val1"); assertEquals(tags.get("additional_2"), "val2"); } }
@SuppressWarnings("boxing") @Test public void testUnsuccessfulResponse() throws Exception { final InputStream instream = Mockito.mock(InputStream.class); final HttpEntity entity = Mockito.mock(HttpEntity.class); Mockito.when(entity.isStreaming()).thenReturn(true); Mockito.when(entity.getContent()).thenReturn(instream); final StatusLine sl = new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not Found"); final HttpResponse response = Mockito.mock(HttpResponse.class); Mockito.when(response.getStatusLine()).thenReturn(sl); Mockito.when(response.getEntity()).thenReturn(entity); final BasicResponseHandler handler = new BasicResponseHandler(); try { handler.handleResponse(response); Assert.fail("HttpResponseException expected"); } catch (final HttpResponseException ex) { Assert.assertEquals(404, ex.getStatusCode()); Assert.assertEquals("Not Found", ex.getMessage()); } Mockito.verify(entity).getContent(); Mockito.verify(instream).close(); }
public void canFindTheSmallestMemoryPackages() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/packages/packages.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); try (CloudApiConnectionContext context = createMockContext(response)) { Collection<Package> packages = packagesApi.smallestMemory(context); assertFalse(packages.isEmpty(), "This should not be an empty collection"); assertEquals(packages.size(), 1); final Package pkg = packages.iterator().next(); assertEquals(pkg.getName(), "t4-standard-128M", "Package name is unexpected. Actual package:\n" + pkg); } }
@Before public void initExecutor() throws IOException { SelfCloseableHttpClient httpMock = mock(SelfCloseableHttpClient.class); when(httpMock.execute(any())).thenAnswer(invocationOnMock -> { HttpGet get = (HttpGet) invocationOnMock.getArguments()[0]; mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append(" "); if (mockReturnCode == 100000) throw new RuntimeException("FAIL"); BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null); BasicHttpEntity entity = new BasicHttpEntity(); String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}"; InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8)); entity.setContent(stream); CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getEntity()).thenReturn(entity); when(response.getStatusLine()).thenReturn(statusLine); return response; }); executor = new ConfigServerHttpRequestExecutor(configServers, httpMock); }
private HttpCacheEntry makeCacheEntryWithVariantMap() { final Header[] headers = new Header[5]; for (int i = 0; i < headers.length; i++) { headers[i] = new BasicHeader("header" + i, "value" + i); } final String body = "Lorem ipsum dolor sit amet"; final ProtocolVersion pvObj = new ProtocolVersion("HTTP", 1, 1); final StatusLine slObj = new BasicStatusLine(pvObj, 200, "ok"); final Map<String,String> variantMap = new HashMap<String,String>(); variantMap.put("test variant 1","true"); variantMap.put("test variant 2","true"); final HttpCacheEntry cacheEntry = new HttpCacheEntry(new Date(), new Date(), slObj, headers, new HeapResource(Base64.decodeBase64(body .getBytes(UTF8))), variantMap, HeaderConstants.GET_METHOD); return cacheEntry; }
@Test public void testUnsuitableUnvalidatableCacheEntryCausesBackendRequest() throws Exception { mockImplMethods(CALL_BACKEND); cacheInvalidatorWasCalled(); requestPolicyAllowsCaching(true); requestIsFatallyNonCompliant(null); getCacheEntryReturns(mockCacheEntry); cacheEntrySuitable(false); cacheEntryValidatable(false); expect(mockConditionalRequestBuilder.buildConditionalRequest(request, mockCacheEntry)) .andReturn(request); backendExpectsRequestAndReturn(request, mockBackendResponse); expect(mockBackendResponse.getProtocolVersion()).andReturn(HttpVersion.HTTP_1_1); expect(mockBackendResponse.getStatusLine()).andReturn( new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "Ok")); replayMocks(); final HttpResponse result = impl.execute(route, request, context); verifyMocks(); Assert.assertSame(mockBackendResponse, result); Assert.assertEquals(0, impl.getCacheMisses()); Assert.assertEquals(1, impl.getCacheHits()); Assert.assertEquals(1, impl.getCacheUpdates()); }
@Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { response.setStatusLine(new BasicStatusLine( HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "Authentication Required")); response.setHeader("Connection", "Keep-Alive"); if (!request.containsHeader(HttpHeaders.AUTHORIZATION)) { response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "NTLM"); } else { response.setHeader(HttpHeaders.WWW_AUTHENTICATE, authenticateHeaderValue); } }
@Override public HttpResponse execute(HttpUriRequest request, HttpContext context) { requestExecuted = request; StatusLine statusLine = new BasicStatusLine( new ProtocolVersion("HTTP", 1, 1), mStatusCode, ""); HttpResponse response = new BasicHttpResponse(statusLine); response.setEntity(mResponseEntity); return response; }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
private static Response mockResponse() { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); HttpResponse httpResponse = new BasicHttpResponse(statusLine); return new Response(requestLine, new HttpHost("localhost", 9200), httpResponse); }
@Before public void setUp() throws IOException { AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar")); mockClient = Mockito.mock(SdkHttpClient.class); HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream("test payload".getBytes())); resp.setEntity(entity); Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class)); ClientConfiguration clientConfig = new ClientConfiguration(); client = new GenericApiGatewayClientBuilder() .withClientConfiguration(clientConfig) .withCredentials(credentials) .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com") .withRegion(Region.getRegion(Regions.fromName("us-east-1"))) .withApiKey("12345") .withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null)) .build(); }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
@Test public void testLambdaInvokeSubsegmentContainsFunctionName() { // Setup test AWSLambda lambda = AWSLambdaClientBuilder.standard().withRequestHandlers(new TracingHandler()).withRegion(Regions.US_EAST_1).withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake"))).build(); AmazonHttpClient amazonHttpClient = new AmazonHttpClient(new ClientConfiguration()); ConnectionManagerAwareHttpClient apacheHttpClient = Mockito.mock(ConnectionManagerAwareHttpClient.class); HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); BasicHttpEntity responseBody = new BasicHttpEntity(); responseBody.setContent(new ByteArrayInputStream("null".getBytes(StandardCharsets.UTF_8))); // Lambda returns "null" on successful fn. with no return value httpResponse.setEntity(responseBody); try { Mockito.doReturn(httpResponse).when(apacheHttpClient).execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class)); } catch (IOException e) { } Whitebox.setInternalState(amazonHttpClient, "httpClient", apacheHttpClient); Whitebox.setInternalState(lambda, "client", amazonHttpClient); // Test logic Segment segment = AWSXRay.beginSegment("test"); InvokeRequest request = new InvokeRequest(); request.setFunctionName("testFunctionName"); InvokeResult r = lambda.invoke(request); System.out.println(r.getStatusCode()); System.out.println(r); Assert.assertEquals(1, segment.getSubsegments().size()); Assert.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation")); System.out.println(segment.getSubsegments().get(0).getAws()); Assert.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name")); }
public HttpResponse newHttpResponse(final ProtocolVersion ver, final int status, HttpContext context) { if (ver == null) { throw new IllegalArgumentException("HTTP version may not be null"); } final Locale loc = determineLocale(context); final String reason = reasonCatalog.getReason(status, loc); StatusLine statusline = new BasicStatusLine(ver, status, reason); return new BasicHttpResponse(statusline, reasonCatalog, loc); }
@Test public void testLoginFailure() throws Exception { final GenericException f = new GenericException( "message", new Header[]{}, new BasicStatusLine(new ProtocolVersion("http", 1, 1), 403, "Forbidden")); assertTrue(new SwiftExceptionMappingService().map(f) instanceof AccessDeniedException); assertEquals("Access denied", new SwiftExceptionMappingService().map(f).getMessage()); assertEquals("Message. 403 Forbidden. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map(f).getDetail()); }
@Before public void setUp() throws Exception { HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "")); PostMessageResponse successfulResponse = new PostMessageResponse(); successfulResponse.setOk(true); successfulResponse.setError("channel_not_found"); response.setEntity(new StringEntity(successfulResponse.toJson())); when(httpClient.execute(isA(HttpUriRequest.class))).thenReturn(response); msteamsNotificationImpl = new MsTeamsNotificationImpl(httpClient); spyMsTeamsNotification = spy(msteamsNotificationImpl); whl = new MsTeamsNotificationListener(sBuildServer, settings, configSettings, manager, factory); projSettings = new MsTeamsNotificationProjectSettings(); when(factory.getMsTeamsNotification()).thenReturn(spyMsTeamsNotification); //when(manager.isRegisteredFormat("JSON")).thenReturn(true); // when(manager.getFormat("JSON")).thenReturn(payload); //when(manager.getServer()).thenReturn(sBuildServer); when(sBuildServer.getProjectManager()).thenReturn(projectManager); when(projectManager.findProjectById("project1")).thenReturn(sProject); when(sBuildServer.getHistory()).thenReturn(buildHistory); when(sBuildServer.getRootUrl()).thenReturn("http://test.server"); when(previousSuccessfulBuild.getBuildStatus()).thenReturn(Status.NORMAL); when(previousSuccessfulBuild.isPersonal()).thenReturn(false); when(previousFailedBuild.getBuildStatus()).thenReturn(Status.FAILURE); when(previousFailedBuild.isPersonal()).thenReturn(false); finishedSuccessfulBuilds.add(previousSuccessfulBuild); finishedFailedBuilds.add(previousFailedBuild); sBuildType.setProject(sProject); when(settings.getSettings(sRunningBuild.getProjectId(), "msteamsNotifications")).thenReturn(projSettings); whl.register(); }
@Test public void post_whenResponseIsOk_doesNotThrow() throws IOException { ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class); HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "")); PostMessageResponse successfulResponse = new PostMessageResponse(); successfulResponse.setOk(true); successfulResponse.setError("channel_not_found"); response.setEntity(new StringEntity(successfulResponse.toJson())); when(httpClient.execute(requestCaptor.capture())).thenReturn(response); MsTeamsNotification w = factory.getMsTeamsNotification(httpClient); MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent(); content.setBuildDescriptionWithLinkSyntax("http://foo"); content.setCommits(new ArrayList<Commit>()); w.setPayload(content); w.setEnabled(true); w.post(); List<HttpPost> capturedRequests = requestCaptor.getAllValues(); HttpPost request = capturedRequests.get(0); assertNotNull(w.getResponse()); assertTrue(w.getResponse().getOk()); }
private DefaultBotSession getDefaultBotSession() throws IOException { HttpResponse response = new BasicHttpResponse(new BasicStatusLine( new ProtocolVersion("HTTP", 1, 1), 200, "")); response.setStatusCode(200); response.setEntity(new StringEntity("{}")); HttpClient mockHttpClient = Mockito.mock(HttpClient.class); Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))) .thenReturn(response); DefaultBotSession session = new DefaultBotSession(); session.setCallback(new FakeLongPollingBot()); session.setOptions(new DefaultBotOptions()); return session; }