List of usage examples for org.apache.http.message BasicHttpResponse BasicHttpResponse
public BasicHttpResponse(StatusLine statusLine)
From source file:org.elasticsearch.client.RestHighLevelClientTests.java
public void testConvertExistsResponse() { RestStatus restStatus = randomBoolean() ? RestStatus.OK : randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); boolean result = RestHighLevelClient.convertExistsResponse(response); assertEquals(restStatus == RestStatus.OK, result); }
From source file:org.elasticsearch.client.RestHighLevelClientTests.java
public void testParseResponseException() throws IOException { {/* w w w .j av a 2 s. c o m*/ RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); ElasticsearchException elasticsearchException = restHighLevelClient .parseResponseException(responseException); assertEquals(responseException.getMessage(), elasticsearchException.getMessage()); assertEquals(restStatus, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getCause()); } { RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); httpResponse.setEntity( new StringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); ElasticsearchException elasticsearchException = restHighLevelClient .parseResponseException(responseException); assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage()); assertEquals(restStatus, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getSuppressed()[0]); } { RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); httpResponse.setEntity(new StringEntity("{\"error\":", ContentType.APPLICATION_JSON)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); ElasticsearchException elasticsearchException = restHighLevelClient .parseResponseException(responseException); assertEquals("Unable to parse response body", elasticsearchException.getMessage()); assertEquals(restStatus, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getCause()); assertThat(elasticsearchException.getSuppressed()[0], instanceOf(IOException.class)); } { RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); httpResponse.setEntity( new StringEntity("{\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); ElasticsearchException elasticsearchException = restHighLevelClient .parseResponseException(responseException); assertEquals("Unable to parse response body", elasticsearchException.getMessage()); assertEquals(restStatus, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getCause()); assertThat(elasticsearchException.getSuppressed()[0], instanceOf(IllegalStateException.class)); } }
From source file:net.sf.jsog.client.DefaultJsogClientImplTest.java
@Test public void testPostCustomContentTypeAndCharset() throws Exception { String url = "http://www.example.com"; JSOG expectedResult = JSOG.object("foo", "bar"); JSOG expectedRequest = JSOG.object("baz", "qux"); // Create and prepare the mock final HttpClient client = createMock(HttpClient.class); Capture<HttpPost> request = new Capture<HttpPost>(); HttpResponse response = new BasicHttpResponse(createStatusLine(200, "OK")); response.setEntity(createStringEntity(expectedResult)); expect(client.execute(capture(request))).andReturn(response); // Create the instance DefaultJsogClientImpl instance = new DefaultJsogClientImpl() { @Override// w w w. j a v a 2s. c om protected HttpClient getClient() { return client; } }; instance.setContentType("text/plain"); instance.setCharset("UTF-8"); // Run the test replay(client); JSOG actual = instance.postJsog(url, expectedRequest); assertEquals(expectedResult, actual); verify(client); assertEquals(expectedRequest.toString(), EntityUtils.toString(request.getValue().getEntity())); Header[] headers = request.getValue().getHeaders("Content-Type"); assertEquals(1, headers.length); Header header = headers[0]; assertEquals("text/plain; charset=UTF-8", header.getValue()); }
From source file:com.shonshampain.streamrecorder.util.StreamProxy.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;/*from w ww . jav a 2s . c o m*/ } String url = request.getRequestLine().getUri(); int mi = 0; Logger.d(DBG, TAG, "processing: " + url); Logger.d(DBG, TAG, "request: " + request.getRequestLine()); for (Header h : request.getAllHeaders()) { Logger.d(DBG, TAG, "header: [" + h.getName() + "] = [" + h.getValue() + "]"); } HttpResponse realResponse = download(url); if (realResponse == null) { startOver(null, client, FailType.CantDownload, null); return; } Logger.d(DBG, TAG, "downloading..."); final InputStream data = realResponse.getEntity().getContent(); StatusLine line = realResponse.getStatusLine(); HttpResponse response = new BasicHttpResponse(line); response.setHeaders(realResponse.getAllHeaders()); Logger.d(DBG, TAG, "reading headers"); StringBuilder httpString = new StringBuilder(); httpString.append(response.getStatusLine().toString()); httpString.append("\n"); for (Header h : response.getAllHeaders()) { if (h.getName().equalsIgnoreCase("Transfer-Encoding")) { /* The KCRW stream specifies chunked encoding in their headers, * however, when we read their stream, the data gets "unchunked". * Therefore, we cannot advertise a chunked encoding unless * we actually re-chunk the data; which we are not. */ httpString.append("Accept-Ranges: bytes\r\n"); httpString.append("Content-Length: 9999999999\r\n"); } else { if (h.getName().equalsIgnoreCase("icy-metaint")) { mi = Integer.parseInt(h.getValue()); Logger.d(DBG, TAG, "Creating new meta data extractor with interval: " + mi); mde = new MetaDataExtractor(mi); } httpString.append(h.getName()).append(": ").append(h.getValue()).append("\r\n"); } } httpString.append("\n"); Logger.d(DBG, TAG, "headers done: [" + httpString + "]"); try { byte[] buffer = httpString.toString().getBytes(); int readBytes; Logger.d(DBG_WRITES, TAG, "writing headers to client"); client.getOutputStream().write(buffer, 0, buffer.length); // Start streaming content. final byte[] buff = new byte[1024 * 50]; boolean endOfStream = false; ExecutorService executor = Executors.newFixedThreadPool(1); while (isRunning && !endOfStream) { Callable<Integer> readTask = new Callable<Integer>() { @Override public Integer call() throws Exception { return data.read(buff, 0, buff.length); } }; Future<Integer> future = executor.submit(readTask); try { readBytes = future.get(STREAM_STALLED_TIMEOUT, TimeUnit.MILLISECONDS); } catch (TimeoutException to) { startOver(data, client, FailType.Stall, null); return; } catch (InterruptedException ie) { Logger.e(TAG, "The read operation was interrupted"); continue; } endOfStream = readBytes == -1; if (!endOfStream) { Logger.d(DBG_READS, TAG, "Raw read: " + readBytes + " bytes"); if (mi > 0) { readBytes = mde.processBuffer(buff, readBytes); Logger.d(DBG_META, TAG, "Status: " + mde.getStatus() + ", running count: " + mde.getRunningCount()); } Logger.d(DBG_WRITES, TAG, "writing " + readBytes + " bytes of content to client"); client.getOutputStream().write(buff, 0, readBytes); if (fileHelper != null) { Logger.d(DBG, TAG, "writing " + readBytes + " bytes of content to file"); // NotificationHelper.build(context, "StreamRecorder Rip Control", "writing " + readBytes + " bytes", notificationId); fileHelper.write(fos, buff, readBytes); } } } } catch (Exception e) { startOver(data, client, FailType.Unexpected, e); } }
From source file:org.callimachusproject.auth.CookieAuthenticationManager.java
private HttpResponse getLogoutResponse() { BasicHttpResponse resp = new BasicHttpResponse(_204); resp.addHeader("Set-Cookie", sid + ";Max-Age=0;HttpOnly;Path=" + protectedPath + secureCookie); return resp;/*from w w w .j a v a2 s .c o m*/ }
From source file:org.callimachusproject.auth.DetachedRealm.java
public final HttpResponse forbidden(String method, Object resource, Map<String, String[]> request) throws Exception { if (forbidden == null) return null; HttpResponse resp = new BasicHttpResponse(_403); resp.setHeader("Cache-Control", "no-store"); try {/*from ww w . j a v a 2s. c o m*/ if (inForbidden.get() == null) { inForbidden.set(true); HttpEntity entity = client.getEntity(forbidden, "text/html;charset=UTF-8"); resp.setEntity(entity); } else { resp.setEntity(new StringEntity("Forbidden")); } return resp; } finally { inForbidden.remove(); } }
From source file:org.cruk.genologics.api.GenologicsAPIPaginatedBatchTest.java
private HttpResponse createMultipageFetchResponse(File responseFile) { HttpResponse response = new BasicHttpResponse( new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE); response.setEntity(new HttpEntityForMultipageFetch(responseFile)); return response; }
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void testCookieStored() throws Exception { CookieStore cookieStore = new BasicCookieStore(); do {/* w w w . j av a 2s . c om*/ HttpGet get = new HttpGet("http://example.com/setcookie"); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); BasicHttpResponse setcookie = new BasicHttpResponse(_200); setcookie.addHeader("Set-Cookie", "oat=meal"); setcookie.addHeader("Cache-Control", "no-store"); responses.add(setcookie); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); assertTrue(response.containsHeader("Set-Cookie")); return null; } }, localContext); } while (false); do { HttpGet get = new HttpGet("http://example.com/getcookie"); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); BasicHttpResponse getcookie = new BasicHttpResponse(_200); responses.add(getcookie); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); assertContains("oat=meal", asString(response.getEntity())); return null; } }, localContext); } while (false); }
From source file:org.callimachusproject.auth.DetachedRealm.java
public HttpResponse unauthorized(String method, Object resource, Map<String, String[]> req, HttpEntity body) throws Exception { HttpResponse unauth = unauthorizedHeaders(method, resource, req, body); if (unauthorized == null) return unauth; try {//from w w w. j a v a2 s .com BasicHttpResponse resp; if (unauth == null) { resp = new BasicHttpResponse(_401); } else { resp = new BasicHttpResponse(unauth.getStatusLine()); for (Header hd : unauth.getAllHeaders()) { if (hd.getName().equalsIgnoreCase("Transfer-Encoding")) continue; if (hd.getName().toLowerCase().startsWith("content-")) continue; resp.addHeader(hd); } } resp.setHeader("Cache-Control", "no-store"); if (inUnauthorized.get() == null) { inUnauthorized.set(true); HttpEntity entity = client.getEntity(unauthorized, "text/html;charset=UTF-8"); resp.setEntity(entity); } else { String via = Arrays.asList(req.get("via")).toString(); resp.setEntity(new StringEntity(via + " is unauthorized")); } return resp; } finally { inUnauthorized.remove(); if (unauth != null) { EntityUtils.consume(unauth.getEntity()); } } }
From source file:net.sf.jsog.client.DefaultJsogClientImplTest.java
@Test public void testPostNullCharset() throws Exception { String url = "http://www.example.com"; JSOG expectedResult = JSOG.object("foo", "bar"); JSOG expectedRequest = JSOG.object("baz", "qux"); // Create and prepare the mock final HttpClient client = createMock(HttpClient.class); Capture<HttpPost> request = new Capture<HttpPost>(); HttpResponse response = new BasicHttpResponse(createStatusLine(200, "OK")); response.setEntity(createStringEntity(expectedResult)); expect(client.execute(capture(request))).andReturn(response); // Create the instance DefaultJsogClientImpl instance = new DefaultJsogClientImpl() { @Override/* w ww . jav a2 s . c o m*/ protected HttpClient getClient() { return client; } }; instance.setCharset(null); // Run the test replay(client); JSOG actual = instance.postJsog(url, expectedRequest); assertEquals(expectedResult, actual); verify(client); assertEquals(expectedRequest.toString(), EntityUtils.toString(request.getValue().getEntity())); Header[] headers = request.getValue().getHeaders("Content-Type"); assertEquals(1, headers.length); Header header = headers[0]; assertEquals("application/json", header.getValue()); }