@Test public void testSimpleSigner() throws Exception { HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", "/query?a=b"); request.setEntity(new StringEntity("I'm an entity")); request.addHeader("foo", "bar"); request.addHeader("content-length", "0"); HttpCoreContext context = new HttpCoreContext(); context.setTargetHost(HttpHost.create("localhost")); createInterceptor().process(request, context); assertEquals("bar", request.getFirstHeader("foo").getValue()); assertEquals("wuzzle", request.getFirstHeader("Signature").getValue()); assertNull(request.getFirstHeader("content-length")); }
@Test public void testEncodedUriSigner() throws Exception { HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", "/foo-2017-02-25%2Cfoo-2017-02-26/_search?a=b"); request.setEntity(new StringEntity("I'm an entity")); request.addHeader("foo", "bar"); request.addHeader("content-length", "0"); HttpCoreContext context = new HttpCoreContext(); context.setTargetHost(HttpHost.create("localhost")); createInterceptor().process(request, context); assertEquals("bar", request.getFirstHeader("foo").getValue()); assertEquals("wuzzle", request.getFirstHeader("Signature").getValue()); assertNull(request.getFirstHeader("content-length")); assertEquals("/foo-2017-02-25%2Cfoo-2017-02-26/_search", request.getFirstHeader("resourcePath").getValue()); }
public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException { if (requestline == null) { throw new IllegalArgumentException("Request line may not be null"); } String method = requestline.getMethod(); if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(requestline); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(requestline); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(requestline); } else { throw new MethodNotSupportedException(method + " method not supported"); } }
public static String[] getHostNameAndPort(String hostName, int port, SessionId session) { String[] hostAndPort = new String[2]; String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: \n"; try { HttpHost host = new HttpHost(hostName, port); CloseableHttpClient client = HttpClients.createSystem(); URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm()); HttpResponse response = client.execute(host, r); String url = extractUrlFromResponse(response); if (url != null) { URL myURL = new URL(url); if ((myURL.getHost() != null) && (myURL.getPort() != -1)) { hostAndPort[0] = myURL.getHost(); hostAndPort[1] = Integer.toString(myURL.getPort()); } } } catch (Exception e) { Logger.getLogger(GridInfoExtractor.class.getName()).log(Level.SEVERE, null, errorMsg + e); } return hostAndPort; }
@Test public void consumesBodyOf100ContinueResponseIfItArrives() throws Exception { final HttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); final int nbytes = 128; req.setHeader("Content-Length","" + nbytes); req.setHeader("Content-Type", "application/octet-stream"); final HttpEntity postBody = new ByteArrayEntity(HttpTestUtils.getRandomBytes(nbytes)); req.setEntity(postBody); final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req); final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_CONTINUE, "Continue"); final Flag closed = new Flag(); final ByteArrayInputStream bais = makeTrackableBody(nbytes, closed); resp.setEntity(new InputStreamEntity(bais, -1)); try { impl.ensureProtocolCompliance(wrapper, resp); } catch (final ClientProtocolException expected) { } assertTrue(closed.set || bais.read() == -1); }
@Test public void testResponsesToPOSTWithoutCacheControlOrExpiresAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); post.setHeader("Content-Length", "128"); post.setEntity(HttpTestUtils.makeBody(128)); originResponse.removeHeaders("Cache-Control"); originResponse.removeHeaders("Expires"); EasyMock.expect( mockBackend.execute( EasyMock.isA(HttpRoute.class), EasyMock.isA(HttpRequestWrapper.class), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); impl.execute(route, HttpRequestWrapper.wrap(post), context, null); verifyMocks(); }
@Test public void testResponsesToPUTsAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); final BasicHttpEntityEnclosingRequest put = new BasicHttpEntityEnclosingRequest("PUT", "/", HttpVersion.HTTP_1_1); put.setEntity(HttpTestUtils.makeBody(128)); put.addHeader("Content-Length", "128"); originResponse.setHeader("Cache-Control", "max-age=3600"); EasyMock.expect( mockBackend.execute( EasyMock.isA(HttpRoute.class), EasyMock.isA(HttpRequestWrapper.class), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); impl.execute(route, HttpRequestWrapper.wrap(put), context, null); verifyMocks(); }
private void testDoesNotModifyHeaderOnRequest(final String header, final String value) throws Exception { final BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST","/",HttpVersion.HTTP_1_1); req.setEntity(HttpTestUtils.makeBody(128)); req.setHeader("Content-Length","128"); req.setHeader(header,value); final Capture<HttpRequestWrapper> cap = new Capture<HttpRequestWrapper>(); EasyMock.expect( mockBackend.execute( EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); impl.execute(route, HttpRequestWrapper.wrap(req), context, null); verifyMocks(); final HttpRequest captured = cap.getValue(); Assert.assertEquals(value, captured.getFirstHeader(header).getValue()); }
private void testDoesNotAddHeaderToRequestIfNotPresent(final String header) throws Exception { final BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST","/",HttpVersion.HTTP_1_1); req.setEntity(HttpTestUtils.makeBody(128)); req.setHeader("Content-Length","128"); req.removeHeaders(header); final Capture<HttpRequestWrapper> cap = new Capture<HttpRequestWrapper>(); EasyMock.expect( mockBackend.execute( EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); impl.execute(route, HttpRequestWrapper.wrap(req), context, null); verifyMocks(); final HttpRequest captured = cap.getValue(); Assert.assertNull(captured.getFirstHeader(header)); }
@Test public void testInvalidatesUrisInContentLocationHeadersOnPUTs() throws Exception { final HttpEntityEnclosingRequest putRequest = new BasicHttpEntityEnclosingRequest("PUT","/",HTTP_1_1); putRequest.setEntity(HttpTestUtils.makeBody(128)); putRequest.setHeader("Content-Length","128"); final String contentLocation = "http://foo.example.com/content"; putRequest.setHeader("Content-Location", contentLocation); final String theUri = "http://foo.example.com:80/"; cacheEntryHasVariantMap(new HashMap<String,String>()); cacheReturnsEntryForUri(theUri); impl.flushInvalidatedCacheEntries(host, putRequest); verify(mockEntry).getVariantMap(); verify(mockStorage).getEntry(theUri); verify(mockStorage).removeEntry(theUri); verify(mockStorage).removeEntry("http://foo.example.com:80/content"); }
@Test public void testInvalidatesUrisInLocationHeadersOnPUTs() throws Exception { final HttpEntityEnclosingRequest putRequest = new BasicHttpEntityEnclosingRequest("PUT","/",HTTP_1_1); putRequest.setEntity(HttpTestUtils.makeBody(128)); putRequest.setHeader("Content-Length","128"); final String contentLocation = "http://foo.example.com/content"; putRequest.setHeader("Location",contentLocation); final String theUri = "http://foo.example.com:80/"; cacheEntryHasVariantMap(new HashMap<String,String>()); cacheReturnsEntryForUri(theUri); impl.flushInvalidatedCacheEntries(host, putRequest); verify(mockEntry).getVariantMap(); verify(mockStorage).getEntry(theUri); verify(mockStorage).removeEntry(theUri); verify(mockStorage).removeEntry(cacheKeyGenerator.canonicalizeUri(contentLocation)); }
@Test public void testInvalidatesRelativeUrisInContentLocationHeadersOnPUTs() throws Exception { final HttpEntityEnclosingRequest putRequest = new BasicHttpEntityEnclosingRequest("PUT","/",HTTP_1_1); putRequest.setEntity(HttpTestUtils.makeBody(128)); putRequest.setHeader("Content-Length","128"); final String relativePath = "/content"; putRequest.setHeader("Content-Location",relativePath); final String theUri = "http://foo.example.com:80/"; cacheEntryHasVariantMap(new HashMap<String,String>()); cacheReturnsEntryForUri(theUri); impl.flushInvalidatedCacheEntries(host, putRequest); verify(mockEntry).getVariantMap(); verify(mockStorage).getEntry(theUri); verify(mockStorage).removeEntry(theUri); verify(mockStorage).removeEntry("http://foo.example.com:80/content"); }
@Test public void testDoesNotInvalidateUrisInContentLocationHeadersOnPUTsToDifferentHosts() throws Exception { final HttpEntityEnclosingRequest putRequest = new BasicHttpEntityEnclosingRequest("PUT","/",HTTP_1_1); putRequest.setEntity(HttpTestUtils.makeBody(128)); putRequest.setHeader("Content-Length","128"); final String contentLocation = "http://bar.example.com/content"; putRequest.setHeader("Content-Location",contentLocation); final String theUri = "http://foo.example.com:80/"; cacheEntryHasVariantMap(new HashMap<String,String>()); cacheReturnsEntryForUri(theUri); impl.flushInvalidatedCacheEntries(host, putRequest); verify(mockEntry).getVariantMap(); verify(mockStorage).getEntry(theUri); verify(mockStorage).removeEntry(theUri); }
@Ignore public void testHTTP1_1RequestsWithBodiesOfKnownLengthMustHaveContentLength() throws Exception { final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/", HTTP_1_1); post.setEntity(mockEntity); replayMocks(); final HttpResponse response = impl.execute(route, HttpRequestWrapper.wrap(post), context, null); verifyMocks(); Assert .assertEquals(HttpStatus.SC_LENGTH_REQUIRED, response.getStatusLine() .getStatusCode()); }
@Test public void testDigestAuthenticationQopAuthInt() throws Exception { final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " + "qop=\"auth,auth-int\""; final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("Post", "/"); request.setEntity(new StringEntity("abc\u00e4\u00f6\u00fcabc", HTTP.DEF_CONTENT_CHARSET)); final Credentials cred = new UsernamePasswordCredentials("username","password"); final DigestScheme authscheme = new DigestScheme(); final HttpContext context = new BasicHttpContext(); authscheme.processChallenge(authChallenge); final Header authResponse = authscheme.authenticate(cred, request, context); Assert.assertEquals("Post:/:acd2b59cd01c7737d8069015584c6cac", authscheme.getA2()); final Map<String, String> table = parseAuthResponse(authResponse); Assert.assertEquals("username", table.get("username")); Assert.assertEquals("realm1", table.get("realm")); Assert.assertEquals("/", table.get("uri")); Assert.assertEquals("auth-int", table.get("qop")); Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); }
@Test public void testDigestAuthenticationQopAuthIntNullEntity() throws Exception { final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " + "qop=\"auth,auth-int\""; final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); final HttpRequest request = new BasicHttpEntityEnclosingRequest("Post", "/"); final Credentials cred = new UsernamePasswordCredentials("username","password"); final DigestScheme authscheme = new DigestScheme(); final HttpContext context = new BasicHttpContext(); authscheme.processChallenge(authChallenge); final Header authResponse = authscheme.authenticate(cred, request, context); Assert.assertEquals("Post:/:d41d8cd98f00b204e9800998ecf8427e", authscheme.getA2()); final Map<String, String> table = parseAuthResponse(authResponse); Assert.assertEquals("username", table.get("username")); Assert.assertEquals("realm1", table.get("realm")); Assert.assertEquals("/", table.get("uri")); Assert.assertEquals("auth-int", table.get("qop")); Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); }
@Test public void testDigestAuthenticationQopAuthOrAuthIntNonRepeatableEntity() throws Exception { final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " + "qop=\"auth,auth-int\""; final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("Post", "/"); request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1)); final Credentials cred = new UsernamePasswordCredentials("username","password"); final DigestScheme authscheme = new DigestScheme(); final HttpContext context = new BasicHttpContext(); authscheme.processChallenge(authChallenge); final Header authResponse = authscheme.authenticate(cred, request, context); Assert.assertEquals("Post:/", authscheme.getA2()); final Map<String, String> table = parseAuthResponse(authResponse); Assert.assertEquals("username", table.get("username")); Assert.assertEquals("realm1", table.get("realm")); Assert.assertEquals("/", table.get("uri")); Assert.assertEquals("auth", table.get("qop")); Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); }
private URL getSesionNodeUrl(RemoteWebDriver remoteDriver) { URL hostFound = null; try { HttpCommandExecutor sessionExcuter = (HttpCommandExecutor) remoteDriver.getCommandExecutor(); HttpHost host = new HttpHost(sessionExcuter.getAddressOfRemoteServer().getHost(), sessionExcuter.getAddressOfRemoteServer().getPort()); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", new URL("http://" + sessionExcuter.getAddressOfRemoteServer().getHost() + ":" + sessionExcuter.getAddressOfRemoteServer().getPort() + "/grid/api/testsession?session=" + remoteDriver.getSessionId()).toExternalForm()); HttpResponse response = new DefaultHttpClient().execute(host, request); URL myURL = new URL(new JSONObject(EntityUtils.toString(response.getEntity())).getString("proxyId")); if ((myURL.getHost() != null) && (myURL.getPort() != -1)) { hostFound = myURL; } } catch (Exception e) { } return hostFound; }
/** * Creates a request that can be accepted by the AndroidHttpClient * @param request The request information * @throws UnsupportedEncodingException */ private static BasicHttpEntityEnclosingRequest createRealRequest(Request request) throws UnsupportedEncodingException { BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(request.getVerb(), request.getUrl()); if (request.getContent() != null) { realRequest.setEntity(new ByteArrayEntity(request.getContent())); } Map<String, String> headers = request.getHeaders(); for (String key : headers.keySet()) { realRequest.addHeader(key, headers.get(key)); } return realRequest; }
/** * For the given servlet request, return a new request object (for use with * Apache HttpClient), that may be executed in place of the original request * to make the real service call. * * @throws javax.servlet.ServletException */ private HttpUriRequest proxyRequest(HttpServletRequest request) throws ServletException, IOException { String newUri = serviceUriForRequest(request); BasicHttpEntityEnclosingRequest httpRequest = new BasicHttpEntityEnclosingRequest(request.getMethod(), newUri); HttpEntity entity = new InputStreamEntity(request.getInputStream(), request.getContentLength()); httpRequest.setEntity(entity); try { // Sadly have to do this to set the URI; it is not derived from the original httpRequest HttpRequestWrapper wrappedRequest = HttpRequestWrapper.wrap(httpRequest); wrappedRequest.setURI(new URI(newUri)); // Somehow, content type header does not come in the original request either wrappedRequest.setHeader("Content-Type", "application/json"); return wrappedRequest; } catch (URISyntaxException e) { LOGGER.error("Syntax exception in service URI, " + newUri, e); throw new LightblueServletException("Syntax exception in service URI, " + newUri, e); } }
public HttpRequest generateRequest() { synchronized (this.httpExchange) { HttpRequest request = this.httpExchange.getRequest(); System.out.println("[proxy->origin] " + this.httpExchange.getId() + " " + request.getRequestLine()); ConsoleFactory.printToConsole("[proxy->origin] " + this.httpExchange.getId() + " " + request.getRequestLine(),true); // Rewrite request!!!! if (request instanceof HttpEntityEnclosingRequest) { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest( request.getRequestLine()); r.setEntity(((HttpEntityEnclosingRequest) request).getEntity()); return r; } else { return new BasicHttpRequest(request.getRequestLine()); } } }
@Test public void testJsonBody() throws Exception { MyController controller = new MyController(); ReflectionControllerRequestHandler handler = new ControllerBuilder(new GsonBuilder().create()) .addController(controller) .withPathPrefix("/") .create(); HttpCoreContext context = HttpCoreContext.create(); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("PUT", "/stuff/putthis"); request.setHeader("Content-Type", "application/json"); request.setEntity(new StringEntity("{ \"name\": \"paul\" }")); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "")); handler.handle(request, response, context); assertTrue(response.getStatusLine().getStatusCode() == 200); String resultBody = EntityUtils.toString(response.getEntity()); assertTrue("itworked".equals(resultBody)); }
@Test public void testJsonResponse() throws Exception { MyController controller = new MyController(); ReflectionControllerRequestHandler handler = new ControllerBuilder(new GsonBuilder().create()) .addController(controller) .withPathPrefix("/") .create(); HttpCoreContext context = HttpCoreContext.create(); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", "/stuff/getjson"); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "")); handler.handle(request, response, context); assertTrue(response.getStatusLine().getStatusCode() == 200); String resultBody = EntityUtils.toString(response.getEntity()); Gson gson = new GsonBuilder().create(); MyController.TestObj retobj = gson.fromJson(resultBody, MyController.TestObj.class); assertNotNull(retobj); assertEquals("Jack", retobj.name); }
/** * getTestNodeIP * Getter/Creator for the Test Node IP * * @param hostName the name of the host (root) * @param port the port to run against (if any) * @param session the Browser Session * @return hostAndPort (String) */ public String[] getTestNodeIP(String hostName, int port, SessionId session) { String[] hostAndPort = new String[2]; String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: "; try { HttpHost host = new HttpHost(hostName, port); HttpClient client = HttpClientBuilder.create().build(); URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm()); HttpResponse response = client.execute(host, r); JSONObject object = extractObject(response); URL myURL = new URL(object.getString("proxyId")); if ((myURL.getHost() != null) && (myURL.getPort() != -1)) { hostAndPort[0] = myURL.getHost(); hostAndPort[1] = Integer.toString(myURL.getPort()); } } catch (Exception e) { LOG.fatal(errorMsg + e); throw new RuntimeException(errorMsg, e); } return hostAndPort; }
@Test public final void getCoapContentTypeHeaderSemiColonTest() throws UnsupportedEncodingException { // create the http message and associate the entity HttpRequest httpRequest = new BasicHttpEntityEnclosingRequest("get", "http://localhost"); HttpEntity httpEntity = new ByteArrayEntity("aaa".getBytes(Charset.forName("ISO-8859-1"))); ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(httpEntity); // create the header httpRequest.setHeader("content-type", "text/plain; charset=iso-8859-1"); Request coapRequest = new GETRequest(); // set the content-type int coapContentType = HttpTranslator.getCoapMediaType(httpRequest); coapRequest.setContentType(coapContentType); assertEquals(coapRequest.getContentType(), MediaTypeRegistry.TEXT_PLAIN); }
@Test public final void getCoapContentTypeHeaderTest() throws UnsupportedEncodingException { // create the http message and associate the entity HttpRequest httpRequest = new BasicHttpEntityEnclosingRequest("get", "http://localhost"); HttpEntity httpEntity = new ByteArrayEntity("aaa".getBytes()); ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(httpEntity); // create the header httpRequest.setHeader("content-type", "text/plain"); Request coapRequest = new GETRequest(); // set the content-type int coapContentType = HttpTranslator.getCoapMediaType(httpRequest); coapRequest.setContentType(coapContentType); assertEquals(MediaTypeRegistry.TEXT_PLAIN, coapRequest.getContentType()); }
@Test public final void getCoapContentTypeUnknownTest() throws UnsupportedEncodingException { // create the http message and associate the entity HttpRequest httpRequest = new BasicHttpEntityEnclosingRequest("get", "http://localhost"); HttpEntity httpEntity = new ByteArrayEntity("aaa".getBytes()); ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(httpEntity); // create the header httpRequest.setHeader("content-type", "multipart/form-data"); Request coapRequest = new GETRequest(); // set the content-type int coapContentType = HttpTranslator.getCoapMediaType(httpRequest); coapRequest.setContentType(coapContentType); assertEquals(coapRequest.getContentType(), MediaTypeRegistry.APPLICATION_OCTET_STREAM); }
@Test public final void getHttpRequestEntityTest() throws TranslationException, IOException { // create the coap request Request coapRequest = new POSTRequest(); coapRequest.setOption(new Option("coap://localhost:5683/resource", OptionNumberRegistry.PROXY_URI)); coapRequest.setContentType(MediaTypeRegistry.TEXT_PLAIN); String payload = "aaa"; coapRequest.setPayload(payload); // translate the request HttpRequest httpRequest = HttpTranslator.getHttpRequest(coapRequest); // check assertNotNull(httpRequest); assertNotNull(httpRequest.getAllHeaders()); assertEquals(httpRequest.getClass(), BasicHttpEntityEnclosingRequest.class); // check the content-type assertEquals(httpRequest.getFirstHeader("content-type").getValue().toLowerCase(), "text/plain; charset=ISO-8859-1".toLowerCase()); // check the content assertArrayEquals(payload.getBytes(), getByteArray(((HttpEntityEnclosingRequest) httpRequest).getEntity().getContent())); }
private HttpRequest newProxyRequest( final HttpServletRequest servletRequest, final String proxyRequestUri ) throws IOException { final String method = servletRequest.getMethod(); if ( null != servletRequest.getHeader( HttpHeaders.CONTENT_LENGTH ) || null != servletRequest.getHeader( HttpHeaders.TRANSFER_ENCODING ) ) { //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. final HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest( method, proxyRequestUri ); r.setEntity( new InputStreamEntity( servletRequest.getInputStream(), servletRequest.getContentLength() ) ); return r; } else { return new BasicHttpRequest( method, proxyRequestUri ); } }
/** JSON data is sent correctly */ public void uploadJson() { final DataTable table = DataTable.createBasicInstance(column).createRow("content"); server.register(url, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { HttpEntity entity = ((BasicHttpEntityEnclosingRequest) holder.request).getEntity(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.writeTo(baos); JsonNode json = new ObjectMapper().readTree(baos.toByteArray()); baos.close(); assertEquals(json, table.toJson()); } }); getService().uploadData(id, table); server.assertRequestUris(url); }
/** can import data from a data set */ public void uploadFromDataSet() { final DataTable table = DataTable.createBasicInstance(column).createRow("content"); server.register(url, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { HttpEntity entity = ((BasicHttpEntityEnclosingRequest) holder.request).getEntity(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.writeTo(baos); JsonNode json = new ObjectMapper().readTree(baos.toByteArray()); baos.close(); assertEquals(json, table.toJson()); } }); DataSet dataSet = new DataSetImpl(getService(), builder.buildDataSetNode(id, "", "", "", "")); dataSet.uploadData(table); server.assertRequestUris(url); }
/** JSON data is sent correctly */ public void uploadJson() { final DataTable table = DataTable.createBasicInstance(column).createRow("content"); server.register(url, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { HttpEntity entity = ((BasicHttpEntityEnclosingRequest) holder.request).getEntity(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.writeTo(baos); JsonNode json = new ObjectMapper().readTree(baos.toByteArray()); baos.close(); assertEquals(json, table.toJson()); } }); service.uploadData(id, table); server.assertRequestUris(url); }
/** can import data from a data set */ public void uploadFromDataSet() { final DataTable table = DataTable.createBasicInstance(column).createRow("content"); DataSet dataSet = new DataSetImpl(service, builder.buildDataSetNode(id, "", "", "", "")); server.register(url, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { HttpEntity entity = ((BasicHttpEntityEnclosingRequest) holder.request).getEntity(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.writeTo(baos); JsonNode json = new ObjectMapper().readTree(baos.toByteArray()); baos.close(); assertEquals(json, table.toJson()); } }); dataSet.uploadData(table); server.assertRequestUris(url); }
public static GridInfo getHostNameAndPort(String hubHost, int hubPort, SessionId session) { GridInfo retVal = null; try { HttpHost host = new HttpHost(hubHost, hubPort); DefaultHttpClient client = new DefaultHttpClient(); URL sessionURL = new URL("http://" + hubHost + ":" + hubPort + "/grid/api/testsession?session=" + session); BasicHttpEntityEnclosingRequest basicHttpEntityEnclosingRequest = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm()); HttpResponse response = client.execute(host, basicHttpEntityEnclosingRequest); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { JSONObject object = extractObject(response); retVal = new GridInfo(object); } else { System.out.println("Problem connecting to Grid Server"); } } catch (JSONException | IOException e) { throw new RuntimeException("Failed to acquire remote webdriver node and port info", e); } return retVal; }
public void performRegistration() throws Exception { String nodeConfigString = getNodeConfig().toString(); log.info("Registering Selendroid node with following config:\n" + nodeConfigString + "\n" + "at Selenium Grid hub: " + hub.toExternalForm()); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", hub.toExternalForm()); request.setEntity(new StringEntity(nodeConfigString)); HttpResponse response = getHttpClient().execute(getHttpHost(), request); if (response.getStatusLine().getStatusCode() != 200) { throw new SelendroidException("Error sending the registration request. Response from server: " + response.getStatusLine().toString()); } }
public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException { if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(method, uri); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(method, uri); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(method, uri); } else { throw new MethodNotSupportedException(method + " method not supported"); } }
public synchronized byte[] generate(QUser user, String uri, HashMap<String, String> params) { final HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", uri); r.addHeader("Cookie", "username=" + user.getName() + "; password=" + user.getPassword()); final StringBuilder sb = new StringBuilder(); params.keySet().stream().forEach((st) -> { sb.append("&").append(st).append("=").append(params.get(st)); }); final InputStream is = new ByteArrayInputStream(sb.substring(1).getBytes()); final BasicHttpEntity b = new BasicHttpEntity(); b.setContent(is); r.setEntity(b); sb.setLength(0); return generate(r).getData(); }
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { switch (request.getRequestLine().getMethod()) { case HttpPost.METHOD_NAME: String message = EntityUtils.toString(((BasicHttpEntityEnclosingRequest) request).getEntity()); collector.collect(message); response.setEntity(new StringEntity("{\"result\":\"OK\"}", ContentType.APPLICATION_JSON)); } }
private HttpRequest buildLogHttpRequest(String content) throws UnsupportedEncodingException { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/log"); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(content.getBytes("UTF-8"))); request.setEntity(entity); return request; }
public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException { Args.notNull(requestline, "Request line"); final String method = requestline.getMethod(); if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(requestline); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(requestline); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(requestline); } else { throw new MethodNotSupportedException(method + " method not supported"); } }