List of usage examples for org.apache.http.entity AbstractHttpEntity AbstractHttpEntity
protected AbstractHttpEntity()
From source file:org.gradle.cache.tasks.http.HttpTaskOutputCache.java
@Override public void store(TaskCacheKey key, final TaskOutputWriter output) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); try {// w ww.j a v a2 s.co m final URI uri = root.resolve(key.getHashCode()); HttpPut httpPut = new HttpPut(uri); httpPut.setEntity(new AbstractHttpEntity() { @Override public boolean isRepeatable() { return true; } @Override public long getContentLength() { return -1; } @Override public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void writeTo(OutputStream outstream) throws IOException { output.writeTo(outstream); } @Override public boolean isStreaming() { return false; } }); CloseableHttpResponse response = httpClient.execute(httpPut); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response for PUT {}: {}", uri, response.getStatusLine()); } } finally { httpClient.close(); } }
From source file:com.polydeucesys.eslogging.testutils.MockCloseableHttpClient.java
public static CloseableHttpResponse responseWithBody(final int statusCode, final String body) { CloseableHttpResponse resp = new BasicCloseableHttpResponse(new StatusLine() { @Override/*from w w w .j a v a 2 s . c o m*/ public int getStatusCode() { // TODO Auto-generated method stub return statusCode; } @Override public ProtocolVersion getProtocolVersion() { // TODO Auto-generated method stub return null; } @Override public String getReasonPhrase() { // TODO Auto-generated method stub return null; } }); resp.setEntity(new AbstractHttpEntity() { @Override public boolean isRepeatable() { // TODO Auto-generated method stub return true; } @Override public long getContentLength() { // TODO Auto-generated method stub return 0; } @Override public InputStream getContent() throws IOException, IllegalStateException { return new ByteArrayInputStream(body.getBytes()); } @Override public void writeTo(OutputStream outstream) throws IOException { // TODO Auto-generated method stub } @Override public boolean isStreaming() { // TODO Auto-generated method stub return false; } }); resp.setHeader(new BasicHeader("Content-Type", "text")); return resp; }
From source file:io.undertow.server.ReadTimeoutTestCase.java
@Test public void testReadTimeout() throws IOException, InterruptedException { DefaultServer.setRootHandler(new HttpHandler() { @Override/*from w ww . ja v a2s . c o m*/ public void handleRequest(final HttpServerExchange exchange) throws Exception { final StreamSinkChannel response = exchange.getResponseChannel(); final StreamSourceChannel request = exchange.getRequestChannel(); try { request.setOption(Options.READ_TIMEOUT, 100); } catch (IOException e) { throw new RuntimeException(e); } request.getReadSetter() .set(ChannelListeners.drainListener(Long.MAX_VALUE, new ChannelListener<Channel>() { @Override public void handleEvent(final Channel channel) { new StringWriteChannelListener("COMPLETED") { @Override protected void writeDone(final StreamSinkChannel channel) { exchange.endExchange(); } }.setup(response); } }, new ChannelExceptionHandler<StreamSourceChannel>() { @Override public void handleException(final StreamSourceChannel channel, final IOException e) { exchange.endExchange(); exception = e; errorLatch.countDown(); } })); request.wakeupReads(); } }); final TestHttpClient client = new TestHttpClient(); try { HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL()); post.setEntity(new AbstractHttpEntity() { @Override public InputStream getContent() throws IOException, IllegalStateException { return null; } @Override public void writeTo(final OutputStream outstream) throws IOException { for (int i = 0; i < 5; ++i) { outstream.write('*'); outstream.flush(); try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } } } @Override public boolean isStreaming() { return true; } @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return 5; } }); post.addHeader(Headers.CONNECTION_STRING, "close"); try { client.execute(post); } catch (IOException e) { } if (errorLatch.await(5, TimeUnit.SECONDS)) { Assert.assertEquals(ReadTimeoutException.class, exception.getClass()); } else { Assert.fail("Read did not time out"); } } finally { client.getConnectionManager().shutdown(); } }
From source file:ch.cyberduck.core.sds.provider.HttpComponentsConnector.java
private HttpEntity getHttpEntity(final ClientRequest clientRequest) { final Object entity = clientRequest.getEntity(); if (entity == null) { return null; }/* w w w .j av a 2 s. c om*/ return new AbstractHttpEntity() { @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return -1; } @Override public InputStream getContent() throws IOException, IllegalStateException { return null; } @Override public void writeTo(final OutputStream outputStream) throws IOException { clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(final int contentLength) throws IOException { return outputStream; } }); clientRequest.writeEntity(); } @Override public boolean isStreaming() { return false; } }; }
From source file:org.gradle.caching.http.internal.HttpBuildCacheService.java
@Override public void store(BuildCacheKey key, final BuildCacheEntryWriter output) throws BuildCacheException { final URI uri = root.resolve(key.getHashCode()); HttpPut httpPut = new HttpPut(uri); httpPut.addHeader(HttpHeaders.CONTENT_TYPE, BUILD_CACHE_CONTENT_TYPE); addDiagnosticHeaders(httpPut);// w w w. j a v a 2 s .c o m httpPut.setEntity(new AbstractHttpEntity() { @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return output.getSize(); } @Override public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void writeTo(OutputStream outstream) throws IOException { output.writeTo(outstream); } @Override public boolean isStreaming() { return false; } }); CloseableHttpResponse response = null; try { response = httpClientHelper.performHttpRequest(httpPut); StatusLine statusLine = response.getStatusLine(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response for PUT {}: {}", safeUri(uri), statusLine); } int statusCode = statusLine.getStatusCode(); if (!isHttpSuccess(statusCode)) { String defaultMessage = String.format("Storing entry at '%s' response status %d: %s", safeUri(uri), statusCode, statusLine.getReasonPhrase()); if (isRedirect(statusCode)) { handleRedirect(uri, response, statusCode, defaultMessage, "storing entry at"); } else { throwHttpStatusCodeException(statusCode, defaultMessage); } } } catch (ClientProtocolException e) { Throwable cause = e.getCause(); if (cause instanceof NonRepeatableRequestException) { throw wrap(cause.getCause()); } else { throw wrap(cause); } } catch (IOException e) { throw wrap(e); } finally { HttpClientUtils.closeQuietly(response); } }
From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java
protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers, final Output writer, final BindingSession session, BigInteger offset, BigInteger length) { int respCode = -1; try {/*from w ww. ja v a2s . co m*/ // log before connect if (LOG.isDebugEnabled()) { LOG.debug("Session {}: {} {}", session.getSessionId(), method, url); } // get HTTP client object from session DefaultHttpClient httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT); if (httpclient == null) { session.writeLock(); try { httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT); if (httpclient == null) { httpclient = createHttpClient(url, session); session.put(HTTP_CLIENT, httpclient, true); } } finally { session.writeUnlock(); } } HttpRequestBase request = null; if ("GET".equals(method)) { request = new HttpGet(url.toString()); } else if ("POST".equals(method)) { request = new HttpPost(url.toString()); } else if ("PUT".equals(method)) { request = new HttpPut(url.toString()); } else if ("DELETE".equals(method)) { request = new HttpDelete(url.toString()); } else { throw new CmisRuntimeException("Invalid HTTP method!"); } // set content type if (contentType != null) { request.setHeader("Content-Type", contentType); } // set other headers if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { request.addHeader(header.getKey(), header.getValue()); } } // authenticate AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session); if (authProvider != null) { Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString()); if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getKey() != null && isNotEmpty(header.getValue())) { String key = header.getKey(); if (key.equalsIgnoreCase("user-agent")) { request.setHeader("User-Agent", header.getValue().get(0)); } else { for (String value : header.getValue()) { if (value != null) { request.addHeader(key, value); } } } } } } } // range if ((offset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((offset == null) || (offset.signum() == -1)) { offset = BigInteger.ZERO; } sb.append(offset.toString()); sb.append('-'); if ((length != null) && (length.signum() == 1)) { sb.append(offset.add(length.subtract(BigInteger.ONE)).toString()); } request.setHeader("Range", sb.toString()); } // compression Object compression = session.get(SessionParameter.COMPRESSION); if ((compression != null) && Boolean.parseBoolean(compression.toString())) { request.setHeader("Accept-Encoding", "gzip,deflate"); } // locale if (session.get(CmisBindingsHelper.ACCEPT_LANGUAGE) instanceof String) { request.setHeader("Accept-Language", session.get(CmisBindingsHelper.ACCEPT_LANGUAGE).toString()); } // send data if (writer != null) { Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION); final boolean clientCompressionFlag = (clientCompression != null) && Boolean.parseBoolean(clientCompression.toString()); if (clientCompressionFlag) { request.setHeader("Content-Encoding", "gzip"); } AbstractHttpEntity streamEntity = new AbstractHttpEntity() { @Override public boolean isChunked() { return true; } @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return -1; } @Override public boolean isStreaming() { return false; } @Override public InputStream getContent() throws IOException { throw new UnsupportedOperationException(); } @Override public void writeTo(final OutputStream outstream) throws IOException { OutputStream connOut = null; if (clientCompressionFlag) { connOut = new GZIPOutputStream(outstream, 4096); } else { connOut = outstream; } OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); try { writer.write(out); } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e); } out.flush(); if (connOut instanceof GZIPOutputStream) { ((GZIPOutputStream) connOut).finish(); } } }; ((HttpEntityEnclosingRequestBase) request).setEntity(streamEntity); } // connect HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); // get stream, if present respCode = response.getStatusLine().getStatusCode(); InputStream inputStream = null; InputStream errorStream = null; if ((respCode == 200) || (respCode == 201) || (respCode == 203) || (respCode == 206)) { if (entity != null) { inputStream = entity.getContent(); } else { inputStream = new ByteArrayInputStream(new byte[0]); } } else { if (entity != null) { errorStream = entity.getContent(); } else { errorStream = new ByteArrayInputStream(new byte[0]); } } // collect headers Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>(); for (Header header : response.getAllHeaders()) { List<String> values = responseHeaders.get(header.getName()); if (values == null) { values = new ArrayList<String>(); responseHeaders.put(header.getName(), values); } values.add(header.getValue()); } // log after connect if (LOG.isTraceEnabled()) { LOG.trace("Session {}: {} {} > Headers: {}", session.getSessionId(), method, url, responseHeaders.toString()); } // forward response HTTP headers if (authProvider != null) { authProvider.putResponseHeaders(url.toString(), respCode, responseHeaders); } // get the response return new Response(respCode, response.getStatusLine().getReasonPhrase(), responseHeaders, inputStream, errorStream); } catch (Exception e) { String status = (respCode > 0 ? " (HTTP status code " + respCode + ")" : ""); throw new CmisConnectionException("Cannot access \"" + url + "\"" + status + ": " + e.getMessage(), e); } }
From source file:com.pmi.restlet.ext.httpclient.internal.HttpMethodCall.java
/** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * * @param request/* w w w. ja v a 2 s . c om*/ * The high-level request. * @return The result status. */ @Override public Status sendRequest(Request request) { Status result = null; try { final Representation entity = request.getEntity(); // Set the request headers for (Parameter header : getRequestHeaders()) { if (!header.getName().equals(HeaderConstants.HEADER_CONTENT_LENGTH)) { getHttpRequest().addHeader(header.getName(), header.getValue()); } } // For those method that accept enclosing entities, provide it if ((entity != null) && (getHttpRequest() instanceof HttpEntityEnclosingRequestBase)) { final HttpEntityEnclosingRequestBase eem = (HttpEntityEnclosingRequestBase) getHttpRequest(); eem.setEntity(new AbstractHttpEntity() { public InputStream getContent() throws IOException, IllegalStateException { return entity.getStream(); } public long getContentLength() { return entity.getSize(); } @Override public Header getContentType() { return new BasicHeader(HeaderConstants.HEADER_CONTENT_TYPE, (entity.getMediaType() != null) ? entity.getMediaType().toString() : null); } public boolean isRepeatable() { return !entity.isTransient(); } public boolean isStreaming() { return (entity.getSize() == Representation.UNKNOWN_SIZE); } public void writeTo(OutputStream os) throws IOException { entity.write(os); } }); } // Ensure that the connection is active this.httpResponse = this.clientHelper.getHttpClient().execute(getHttpRequest()); // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); } catch (IOException ioe) { this.clientHelper.getLogger().log(Level.WARNING, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); // Release the connection getHttpRequest().abort(); } return result; }
From source file:org.restlet.ext.httpclient.internal.HttpMethodCall.java
/** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * //from w w w.j a va2s . com * @param request * The high-level request. * @return The result status. */ @Override public Status sendRequest(Request request) { Status result = null; try { final Representation entity = request.getEntity(); // Set the request headers for (org.restlet.engine.header.Header header : getRequestHeaders()) { if (!header.getName().equals(HeaderConstants.HEADER_CONTENT_LENGTH)) { getHttpRequest().addHeader(header.getName(), header.getValue()); } } // For those method that accept enclosing entities, provide it if ((entity != null) && (getHttpRequest() instanceof HttpEntityEnclosingRequestBase)) { final HttpEntityEnclosingRequestBase eem = (HttpEntityEnclosingRequestBase) getHttpRequest(); eem.setEntity(new AbstractHttpEntity() { public InputStream getContent() throws IOException, IllegalStateException { return entity.getStream(); } public long getContentLength() { return entity.getSize(); } public Header getContentType() { return new BasicHeader(HeaderConstants.HEADER_CONTENT_TYPE, (entity.getMediaType() != null) ? entity.getMediaType().toString() : null); } public boolean isRepeatable() { return !entity.isTransient(); } public boolean isStreaming() { return (entity.getSize() == Representation.UNKNOWN_SIZE); } public void writeTo(OutputStream os) throws IOException { entity.write(os); os.flush(); } }); } // Ensure that the connection is active this.httpResponse = this.clientHelper.getHttpClient().execute(getHttpRequest()); // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); } catch (IOException ioe) { this.clientHelper.getLogger().log(Level.WARNING, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); // Release the connection getHttpRequest().abort(); } return result; }
From source file:com.sun.jersey.client.apache4.ApacheHttpClient4Handler.java
private HttpEntity getHttpEntity(final ClientRequest cr, final boolean isBufferingEnabled) { final Object entity = cr.getEntity(); if (entity == null) return null; final RequestEntityWriter requestEntityWriter = getRequestEntityWriter(cr); try {//from www . ja v a2 s . c o m HttpEntity httpEntity = new AbstractHttpEntity() { @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return requestEntityWriter.getSize(); } @Override public InputStream getContent() throws IOException, IllegalStateException { if (isBufferingEnabled) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(512); writeTo(buffer); return new ByteArrayInputStream(buffer.toByteArray()); } else { return null; } } @Override public void writeTo(OutputStream outputStream) throws IOException { requestEntityWriter.writeRequestEntity(outputStream); } @Override public boolean isStreaming() { return false; } }; if (!isBufferingEnabled) { // TODO return InputStreamEntity return httpEntity; } else { return new BufferedHttpEntity(httpEntity); } } catch (Exception ex) { // TODO warning/error? } return null; }