Example usage for org.apache.http.entity AbstractHttpEntity AbstractHttpEntity

List of usage examples for org.apache.http.entity AbstractHttpEntity AbstractHttpEntity

Introduction

In this page you can find the example usage for org.apache.http.entity AbstractHttpEntity AbstractHttpEntity.

Prototype

protected AbstractHttpEntity() 

Source Link

Usage

From source file:com.basistech.rosette.api.HttpRosetteAPI.java

private void setupPlainRequest(final Object request, final ObjectWriter finalWriter, HttpPost post) {
    // just posting json.
    post.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
    post.setEntity(new AbstractHttpEntity() {
        @Override/*from www .ja va2 s  .  c  o  m*/
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public long getContentLength() {
            return -1;
        }

        @Override
        public InputStream getContent() throws IOException, UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void writeTo(OutputStream outstream) throws IOException {
            finalWriter.writeValue(outstream, request);
        }

        @Override
        public boolean isStreaming() {
            return false;
        }
    });
}

From source file:ch.cyberduck.core.azure.AzurePath.java

@Override
protected void upload(final BandwidthThrottle throttle, final StreamListener listener, final boolean check) {
    if (attributes().isFile()) {
        try {//from  w w  w.j av  a2s  .  co m
            if (check) {
                this.getSession().check();
            }

            final Status status = this.status();
            status.setResume(false);
            final InputStream in = this.getLocal().getInputStream();
            try {
                AzureSession.AzureContainer container = this.getSession().getContainer(this.getContainerName());
                final BlobProperties properties = new BlobProperties(this.getKey());
                properties.setContentType(this.getLocal().getMimeType());
                NameValueCollection metadata = new NameValueCollection();
                // Default metadata for new files
                for (String m : Preferences.instance().getList("azure.metadata.default")) {
                    if (StringUtils.isBlank(m)) {
                        log.warn("Invalid header " + m);
                        continue;
                    }
                    if (!m.contains("=")) {
                        log.warn("Invalid header " + m);
                        continue;
                    }
                    int split = m.indexOf('=');
                    String name = m.substring(0, split);
                    if (StringUtils.isBlank(name)) {
                        log.warn("Missing key in " + m);
                        continue;
                    }
                    String value = m.substring(split + 1);
                    if (StringUtils.isEmpty(value)) {
                        log.warn("Missing value in " + m);
                        continue;
                    }
                    metadata.put(name, value);
                }
                properties.setMetadata(metadata);
                boolean blob = container.createBlob(properties, new AbstractHttpEntity() {
                    private boolean consumed = false;

                    public boolean isRepeatable() {
                        return false;
                    }

                    @Override
                    public Header getContentType() {
                        return new BasicHeader(HTTP.CONTENT_TYPE, getLocal().getMimeType());
                    }

                    public long getContentLength() {
                        return getLocal().attributes().getSize() - status.getCurrent();
                    }

                    public InputStream getContent() throws IOException, IllegalStateException {
                        return getLocal().getInputStream();
                    }

                    public void writeTo(OutputStream out) throws IOException {
                        upload(out, in, throttle, listener);
                        consumed = true;
                    }

                    public boolean isStreaming() {
                        return !consumed;
                    }

                    @Override
                    public void consumeContent() throws IOException {
                        this.consumed = true;
                        // If the input stream is from a connection, closing it will read to
                        // the end of the content. Otherwise, we don't care what it does.
                        getLocal().getInputStream().close();
                    }
                });
                if (!blob) {
                    this.status().setComplete(false);
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        } catch (StorageException e) {
            this.error("Upload failed", e);
        } catch (IOException e) {
            this.error("Upload failed", e);
        }
    }
}

From source file:org.openrdf.http.client.SesameSession.java

/**
 * Sends a transaction list as serialized XML to the server.
 * // ww w .j a v  a  2  s.  com
 * @deprecated since 2.8.0
 * @param txn
 * @throws IOException
 * @throws RepositoryException
 * @throws UnauthorizedException
 */
@Deprecated
public void sendTransaction(final Iterable<? extends TransactionOperation> txn)
        throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();

    HttpPost method = new HttpPost(Protocol.getStatementsLocation(getQueryURL()));

    // Create a RequestEntity for the transaction data
    method.setEntity(new AbstractHttpEntity() {

        public long getContentLength() {
            return -1; // don't know
        }

        public Header getContentType() {
            return new BasicHeader("Content-Type", Protocol.TXN_MIME_TYPE);
        }

        public boolean isRepeatable() {
            return true;
        }

        public boolean isStreaming() {
            return true;
        }

        public InputStream getContent() throws IOException, IllegalStateException {
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            writeTo(buf);
            return new ByteArrayInputStream(buf.toByteArray());
        }

        public void writeTo(OutputStream out) throws IOException {
            TransactionWriter txnWriter = new TransactionWriter();
            txnWriter.serialize(txn, out);
        }
    });

    try {
        executeNoContent(method);
    } catch (RepositoryException e) {
        throw e;
    } catch (OpenRDFException e) {
        throw new RepositoryException(e);
    }
}

From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

/**
 * Sends a transaction list as serialized XML to the server.
 * //from  w w  w  .ja v  a 2 s  .  com
 * @deprecated since 2.8.0
 * @param txn
 * @throws IOException
 * @throws RepositoryException
 * @throws UnauthorizedException
 */
@Deprecated
public void sendTransaction(final Iterable<? extends TransactionOperation> txn)
        throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();

    HttpPost method = new HttpPost(Protocol.getStatementsLocation(getQueryURL()));

    try {
        // Create a RequestEntity for the transaction data
        method.setEntity(new AbstractHttpEntity() {

            public long getContentLength() {
                return -1; // don't know
            }

            public Header getContentType() {
                return new BasicHeader("Content-Type", Protocol.TXN_MIME_TYPE);
            }

            public boolean isRepeatable() {
                return true;
            }

            public boolean isStreaming() {
                return true;
            }

            public InputStream getContent() throws IOException, IllegalStateException {
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                writeTo(buf);
                return new ByteArrayInputStream(buf.toByteArray());
            }

            public void writeTo(OutputStream out) throws IOException {
                TransactionWriter txnWriter = new TransactionWriter();
                txnWriter.serialize(txn, out);
            }
        });

        try {
            executeNoContent(method);
        } catch (RepositoryException e) {
            throw e;
        } catch (RDF4JException e) {
            throw new RepositoryException(e);
        }
    } finally {
        method.reset();
    }
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

private HttpEntity getHttpEntity(final ClientRequest clientRequest, final boolean bufferingEnabled) {
    final Object entity = clientRequest.getEntity();

    if (entity == null) {
        return null;
    }//from   ww  w . j  a v  a2 s. com

    final AbstractHttpEntity httpEntity = new AbstractHttpEntity() {
        @Override
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public long getContentLength() {
            return -1;
        }

        @Override
        public InputStream getContent() throws IOException, IllegalStateException {
            if (bufferingEnabled) {
                final ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
                writeTo(buffer);
                return new ByteArrayInputStream(buffer.toByteArray());
            } else {
                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;
        }
    };

    if (bufferingEnabled) {
        try {
            return new BufferedHttpEntity(httpEntity);
        } catch (final IOException e) {
            throw new ProcessingException(LocalizationMessages.ERROR_BUFFERING_ENTITY(), e);
        }
    } else {
        return httpEntity;
    }
}

From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

protected void upload(final Reader contents, String baseURI, final RDFFormat dataFormat, boolean overwrite,
        boolean preserveNodeIds, Action action, Resource... contexts)
        throws IOException, RDFParseException, RepositoryException, UnauthorizedException {
    final Charset charset = dataFormat.hasCharset() ? dataFormat.getCharset() : Charset.forName("UTF-8");

    HttpEntity entity = new AbstractHttpEntity() {

        private InputStream content;

        public long getContentLength() {
            return -1; // don't know
        }/* w w w  .  j  a  va2  s. co  m*/

        public Header getContentType() {
            return new BasicHeader("Content-Type",
                    dataFormat.getDefaultMIMEType() + "; charset=" + charset.name());
        }

        public boolean isRepeatable() {
            return false;
        }

        public boolean isStreaming() {
            return true;
        }

        public synchronized InputStream getContent() throws IOException, IllegalStateException {
            if (content == null) {
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                writeTo(buf);
                content = new ByteArrayInputStream(buf.toByteArray());
            }
            return content;
        }

        public void writeTo(OutputStream out) throws IOException {
            try {
                OutputStreamWriter writer = new OutputStreamWriter(out, charset);
                IOUtil.transfer(contents, writer);
                writer.flush();
            } finally {
                contents.close();
            }
        }
    };

    upload(entity, baseURI, overwrite, preserveNodeIds, action, contexts);
}

From source file:org.gradle.caching.http.internal.HttpBuildCache.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.setEntity(new AbstractHttpEntity() {
        @Override/*  w  w w. j  ava  2s  .  co  m*/
        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 = null;
    try {
        response = httpClient.execute(httpPut);
        StatusLine statusLine = response.getStatusLine();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for PUT {}: {}", safeUri(uri), statusLine);
        }
        int statusCode = statusLine.getStatusCode();
        if (!isHttpSuccess(statusCode)) {
            throwHttpStatusCodeException(statusCode,
                    String.format("Storing key '%s' in %s response status %d: %s", key, getDescription(),
                            statusCode, statusLine.getReasonPhrase()));
        }
    } catch (IOException e) {
        // TODO: We should consider different types of exceptions as fatal/recoverable.
        // Right now, everything is considered recoverable.
        throw new BuildCacheException(String.format("Storing key '%s' in %s", key, getDescription()), e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}