List of usage examples for org.apache.http.nio ContentEncoder complete
void complete() throws IOException;
From source file:org.apache.synapse.transport.passthru.SourceResponse.java
/** * Consume the content through the Pipe and write them to the wire * @param conn connection// w w w .j a va 2s . c om * @param encoder encoder * @throws java.io.IOException if an error occurs * @return number of bytes written */ public int write(NHttpServerConnection conn, ContentEncoder encoder) throws IOException { int bytes = 0; if (pipe != null) { bytes = pipe.consume(encoder); } else { encoder.complete(); } // Update connection state if (encoder.isCompleted()) { SourceContext.updateState(conn, ProtocolState.RESPONSE_DONE); sourceConfiguration.getMetrics().notifySentMessageSize(conn.getMetrics().getSentBytesCount()); if (response != null && !this.connStrategy.keepAlive(response, conn.getContext())) { SourceContext.updateState(conn, ProtocolState.CLOSING); sourceConfiguration.getSourceConnections().closeConnection(conn); } else if (SourceContext.get(conn).isShutDown()) { // we need to shut down if the shutdown flag is set SourceContext.updateState(conn, ProtocolState.CLOSING); sourceConfiguration.getSourceConnections().closeConnection(conn); } else { // Reset connection state sourceConfiguration.getSourceConnections().releaseConnection(conn); // Ready to deal with a new request conn.requestInput(); } } return bytes; }
From source file:NGzipCompressingEntity.java
public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException { if (baos == null) { baos = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(baos); InputStream in = wrappedEntity.getContent(); byte[] tmp = new byte[2048]; int l;/*w w w . jav a 2s. c o m*/ while ((l = in.read(tmp)) != -1) { gzip.write(tmp, 0, l); } gzip.close(); buffer = ByteBuffer.wrap(baos.toByteArray()); } encoder.write(buffer); if (!buffer.hasRemaining()) encoder.complete(); }
From source file:org.apache.cxf.transport.http.asyncclient.CXFHttpAsyncRequestProducer.java
public void produceContent(final ContentEncoder enc, final IOControl ioc) throws IOException { if (content != null) { if (buffer == null) { if (content.getTempFile() == null) { buffer = ByteBuffer.wrap(content.getBytes()); } else { fis = content.getInputStream(); chan = (fis instanceof FileInputStream) ? ((FileInputStream) fis).getChannel() : Channels.newChannel(fis); buffer = ByteBuffer.allocate(8 * 1024); }//from w w w .jav a 2 s. c o m } int i = -1; buffer.rewind(); if (buffer.hasRemaining() && chan != null) { i = chan.read(buffer); buffer.flip(); } enc.write(buffer); if (!buffer.hasRemaining() && i == -1) { enc.complete(); } } else { buf.produceContent(enc, ioc); } }
From source file:org.apache.synapse.transport.nhttp.NhttpSharedOutputBuffer.java
public int produceContent(final ContentEncoder encoder, final IOControl ioctrl) throws IOException { if (this.shutdown) { return -1; }/*from w w w. j a v a 2 s. c o m*/ this.lock.lock(); try { if (ioctrl != null) { this.ioctrl = ioctrl; } setOutputMode(); int bytesWritten = 0; if (super.hasData()) { bytesWritten = encoder.write(this.buffer); if (encoder.isCompleted()) { this.endOfStream = true; } } if (!super.hasData()) { // No more buffered content // If at the end of the stream, terminate if (this.endOfStream && !encoder.isCompleted()) { encoder.complete(); } if (!this.endOfStream) { // suspend output events if (this.ioctrl != null) { this.ioctrl.suspendOutput(); } } } this.condition.signalAll(); return bytesWritten; } finally { this.lock.unlock(); } }
From source file:org.jenkinsci.plugins.relution_publisher.net.requests.ZeroCopyFileRequestProducer.java
@Override public synchronized void produceContent(final ContentEncoder encoder, final IOControl ioctrl) throws IOException { if (!this.writeHeader(encoder, ioctrl)) { return;/*w ww .ja va 2 s. c o m*/ } if (this.mFileChannel == null) { this.mFileChannel = this.mAccessfile.getChannel(); this.mIndexFile = 0; } final long transferred; if (encoder instanceof FileContentEncoder) { transferred = ((FileContentEncoder) encoder).transfer(this.mFileChannel, this.mIndexFile, Integer.MAX_VALUE); } else { transferred = this.mFileChannel.transferTo(this.mIndexFile, Integer.MAX_VALUE, new ContentEncoderChannel(encoder)); } if (transferred > 0) { this.mIndexFile += transferred; } if (this.mIndexFile >= this.mFileChannel.size()) { if (this.writeFooter(encoder, ioctrl)) { this.closeChannel(); encoder.complete(); } } }
From source file:org.apache.cxf.transport.http.asyncclient.SharedOutputBuffer.java
public int produceContent(final ContentEncoder encoder, final IOControl ioc) throws IOException { if (this.shutdown) { return -1; }//from w w w.j a va 2 s.c o m this.lock.lock(); try { this.ioctrl = ioc; setOutputMode(); int bytesWritten = 0; if (largeWrapper != null || super.hasData()) { if (!this.buffer.hasRemaining() && largeWrapper != null) { bytesWritten = encoder.write(largeWrapper); } else { bytesWritten = encoder.write(this.buffer); } if (encoder.isCompleted()) { this.endOfStream = true; } } if ((largeWrapper == null || !largeWrapper.hasRemaining()) && !super.hasData()) { // No more buffered content // If at the end of the stream, terminate if (this.endOfStream && !encoder.isCompleted()) { encoder.complete(); } if (!this.endOfStream && this.ioctrl != null) { // suspend output events this.ioctrl.suspendOutput(); } } // no need to signal if the large wrapper is present and has data remaining if (largeWrapper == null || !largeWrapper.hasRemaining()) { this.condition.signalAll(); } return bytesWritten; } finally { this.lock.unlock(); } }
From source file:org.apache.synapse.transport.passthru.Pipe.java
/** * Consume the data from the buffer. Before calling this method attachConsumer * method must be called with a valid IOControl. * * @param encoder encoder used to write the data means there will not be any data * written in to this buffer// w ww. j a v a 2 s. c o m * @return number of bytes written (consumed) * @throws IOException if an error occurred while consuming data */ public int consume(final ContentEncoder encoder) throws IOException { if (consumerIoControl == null) { throw new IllegalStateException("Consumer cannot be null when calling consume"); } if (hasHttpProducer && producerIoControl == null) { throw new IllegalStateException("Producer cannot be null when calling consume"); } lock.lock(); ControlledByteBuffer consumerBuffer; if (outputBuffer != null) { consumerBuffer = outputBuffer; } else { consumerBuffer = buffer; } try { // if producer at error we have to stop the encoding and return immediately if (producerError) { encoder.complete(); return -1; } setOutputMode(consumerBuffer); int bytesWritten = encoder.write(consumerBuffer.getByteBuffer()); setInputMode(consumerBuffer); if (consumerBuffer.position() == 0) { if (outputBuffer == null) { if (producerCompleted) { encoder.complete(); } else { // buffer is empty. Wait until the producer fills up // the buffer consumerIoControl.suspendOutput(); } } else if (serializationComplete || rawSerializationComplete) { encoder.complete(); } } if (bytesWritten > 0) { if (!encoder.isCompleted() && !producerCompleted && hasHttpProducer) { producerIoControl.requestInput(); } } writeCondition.signalAll(); return bytesWritten; } finally { lock.unlock(); } }
From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java
/** * <p>//from w ww . ja va 2 s. c om * Initiate a transaction for sending data. * </p> * * <p> * If a proxy server requires auth, the proxy server returns 407 response with available auth schema such as basic or digest. * Then client has to resend the same request with its credential added. * This mechanism is problematic for sending data from NiFi. * </p> * * <p> * In order to resend a POST request with auth param, * NiFi has to either read flow-file contents to send again, or keep the POST body somewhere. * If we store that in memory, it would causes OOM, or storing it on disk slows down performance. * Rolling back processing session would be overkill. * Reading flow-file contents only when it's ready to send in a streaming way is ideal. * </p> * * <p> * Additionally, the way proxy authentication is done is vary among Proxy server software. * Some requires 407 and resend cycle for every requests, while others keep a connection between a client and * the proxy server, then consecutive requests skip auth steps. * The problem is, that how should we behave is only told after sending a request to the proxy. * </p> * * In order to handle above concerns correctly and efficiently, this method do the followings: * * <ol> * <li>Send a GET request to controller resource, to initiate an HttpAsyncClient. The instance will be used for further requests. * This is not required by the Site-to-Site protocol, but it can setup proxy auth state safely.</li> * <li>Send a POST request to initiate a transaction. While doing so, it captures how a proxy server works. * If 407 and resend cycle occurs here, it implies that we need to do the same thing again when we actually send the data. * Because if the proxy keeps using the same connection and doesn't require an auth step, it doesn't do so here.</li> * <li>Then this method stores whether the final POST request should wait for the auth step. * So that {@link #openConnectionForSend} can determine when to produce contents.</li> * </ol> * * <p> * The above special sequence is only executed when a proxy instance is set, and its username is set. * </p> * * @param post a POST request to establish transaction * @return POST request response * @throws IOException thrown if the post request failed */ private HttpResponse initiateTransactionForSend(final HttpPost post) throws IOException { if (shouldCheckProxyAuth()) { final CloseableHttpAsyncClient asyncClient = getHttpAsyncClient(); final HttpGet get = createGetControllerRequest(); final Future<HttpResponse> getResult = asyncClient.execute(get, null); try { final HttpResponse getResponse = getResult.get(readTimeoutMillis, TimeUnit.MILLISECONDS); logger.debug("Proxy auth check has done. getResponse={}", getResponse.getStatusLine()); } catch (final ExecutionException e) { logger.debug("Something has happened at get controller requesting thread for proxy auth check. {}", e.getMessage()); throw toIOException(e); } catch (TimeoutException | InterruptedException e) { throw new IOException(e); } } final HttpAsyncRequestProducer asyncRequestProducer = new HttpAsyncRequestProducer() { private boolean requestHasBeenReset = false; @Override public HttpHost getTarget() { return URIUtils.extractHost(post.getURI()); } @Override public HttpRequest generateRequest() throws IOException, HttpException { final BasicHttpEntity entity = new BasicHttpEntity(); post.setEntity(entity); return post; } @Override public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException { encoder.complete(); if (shouldCheckProxyAuth() && requestHasBeenReset) { logger.debug("Produced content again, assuming the proxy server requires authentication."); proxyAuthRequiresResend.set(true); } } @Override public void requestCompleted(HttpContext context) { debugProxyAuthState(context); } @Override public void failed(Exception ex) { final String msg = String.format("Failed to create transaction for %s", post.getURI()); logger.error(msg, ex); eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg); } @Override public boolean isRepeatable() { return true; } @Override public void resetRequest() throws IOException { requestHasBeenReset = true; } @Override public void close() throws IOException { } }; final Future<HttpResponse> responseFuture = getHttpAsyncClient().execute(asyncRequestProducer, new BasicAsyncResponseConsumer(), null); final HttpResponse response; try { response = responseFuture.get(readTimeoutMillis, TimeUnit.MILLISECONDS); } catch (final ExecutionException e) { logger.debug("Something has happened at initiate transaction requesting thread. {}", e.getMessage()); throw toIOException(e); } catch (TimeoutException | InterruptedException e) { throw new IOException(e); } return response; }