@Override public NextAction handleWrite(FilterChainContext context) throws IOException { Connection<?> connection = context.getConnection(); GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); try { ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(1024); // Do not need to close Object msg = context.getMessage(); codec.encode(channel, channelBuffer, msg); GrizzlyChannel.removeChannelIfDisconnected(connection); Buffer buffer = connection.getTransport().getMemoryManager().allocate(channelBuffer.readableBytes()); buffer.put(channelBuffer.toByteBuffer()); buffer.flip(); buffer.allowBufferDispose(true); context.setMessage(buffer); } finally { GrizzlyChannel.removeChannelIfDisconnected(connection); } return context.getInvokeAction(); }
@Override @SuppressWarnings("rawtypes") public void send(Object message, boolean sent) throws RemotingException { super.send(message, sent); int timeout = 0; try { GrizzlyFuture future = connection.write(message); if (sent) { timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); future.get(timeout, TimeUnit.MILLISECONDS); } } catch (TimeoutException e) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + "in timeout(" + timeout + "ms) limit", e); } catch (Throwable e) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); } }
@Override public InetSocketAddress getRemoteAddress() { return (InetSocketAddress) connection.getPeerAddress(); }
private void feederFlush(final Connection c) { if (isServiceThread()) { c.getTransport().getWorkerThreadPool().execute(new Runnable() { @Override public void run() { feederFlush0(c); } }); } else { feederFlush0(c); } }
/** * @return {@link Executor}, which will be used for notifying user * registered {@link WriteHandler}. */ protected Executor getThreadPool() { if (!Threads.isService()) { return null; } final ExecutorService es = connection.getTransport().getWorkerThreadPool(); return es != null && !es.isShutdown() ? es : null; }
private void sendEndResponse(final FilterChainContext ctx) throws IOException { final Connection connection = ctx.getConnection(); final MemoryManager mm = connection.getTransport().getMemoryManager(); final Buffer buffer = mm.allocate(6); buffer.put((byte) 'A'); buffer.put((byte) 'B'); buffer.putShort((short) 2); buffer.put(AjpConstants.JK_AJP13_END_RESPONSE); buffer.put((byte) 1); buffer.flip(); buffer.allowBufferDispose(true); ctx.write(buffer); }
@SuppressWarnings("unchecked") protected void sendRaw(byte[] rawData) { final Connection connection = protocolHandler.getConnection(); final MemoryManager mm = connection.getTransport().getMemoryManager(); final Buffer buffer = Buffers.wrap(mm, rawData); buffer.allowBufferDispose(false); connection.write(buffer); }
@Override public Buffer clone(final Connection connection, final Buffer originalMessage) { final SSLConnectionContext sslCtx = getSslConnectionContext(connection); final int copyThreshold = sslCtx.getNetBufferSize() / 2; final Buffer lastOutputBuffer = sslCtx.resetLastOutputBuffer(); final int totalRemaining = originalMessage.remaining(); if (totalRemaining < copyThreshold) { return move(connection.getMemoryManager(), originalMessage); } if (lastOutputBuffer.remaining() < copyThreshold) { final Buffer tmpBuf = copy(connection.getMemoryManager(), originalMessage); if (originalMessage.isComposite()) { ((CompositeBuffer) originalMessage).replace( lastOutputBuffer, tmpBuf); } else { assert originalMessage == lastOutputBuffer; } lastOutputBuffer.tryDispose(); return tmpBuf; } return originalMessage; } }
/** * Delegates close operation to {@link Transport}'s specific transport * filter. */ @Override public NextAction handleClose(final FilterChainContext ctx) throws IOException { final Filter transportFilter0 = getTransportFilter0( ctx.getConnection().getTransport()); if (transportFilter0 != null) { return transportFilter0.handleClose(ctx); } return null; }
@SuppressWarnings({"unchecked"}) @Override public NextAction handleConnect(FilterChainContext ctx) throws IOException { System.out.println("\nClient connected!\n"); HttpRequestPacket.Builder builder = createRequest(); HttpRequestPacket request = builder.build(); request.addHeader(Header.Host, HOST_HEADER_VALUE); System.out.println("Writing request:\n"); System.out.println(request.toString()); ctx.write(request); // write the request // for each of the content parts in CONTENT, wrap in a Buffer, // create the HttpContent to wrap the buffer and write the // content. MemoryManager mm = ctx.getConnection().getTransport().getMemoryManager(); for (int i = 0, len = CONTENT.length; i < len; i++) { HttpContent.Builder contentBuilder = request.httpContentBuilder(); Buffer b = Buffers.wrap(mm, CONTENT[i]); contentBuilder.content(b); HttpContent content = contentBuilder.build(); System.out.println(b.toStringContent()); ctx.write(content); } // since the request created by createRequest() is chunked, // we need to write the trailer to signify the end of the // POST data ctx.write(request.httpTrailerBuilder().build()); System.out.println("\n"); return ctx.getStopAction(); // discontinue filter chain execution }
/** * This method will be called, to notify about {@link Connection} closing. */ @Override public NextAction handleClose(FilterChainContext ctx) throws IOException { final Connection connection = ctx.getConnection(); final Connection peerConnection = peerConnectionAttribute.get(connection); // Close peer connection as well, if it wasn't closed before if (peerConnection != null && peerConnection.isOpen()) { peerConnection.closeSilently(); } return ctx.getInvokeAction(); }
@Override public Executor getExecutor(final Request request) { if (!Threads.isService()) { return null; // Execute in the current thread } return request.getContext().getConnection().getTransport().getWorkerThreadPool(); } }
@Override public NextAction handleRead(final FilterChainContext ctx) throws IOException { ctx.getConnection().close(); return ctx.getStopAction(); } }
protected static void fireIOEvent(final Connection connection, final IOEvent ioEvent, final IOEventLifeCycleListener listener, final Logger logger) { try { connection.getTransport().fireIOEvent(ioEvent, connection, listener); } catch (Exception e) { logger.log(Level.WARNING, LogMessages.WARNING_GRIZZLY_IOSTRATEGY_UNCAUGHT_EXCEPTION(), e); connection.closeSilently(); } }
static GrizzlyChannel getOrAddChannel(Connection<?> connection, URL url, ChannelHandler handler) { if (connection == null) { return null; } GrizzlyChannel ret = ATTRIBUTE.get(connection); if (ret == null) { ret = new GrizzlyChannel(connection, url, handler); if (connection.isOpen()) { ATTRIBUTE.set(connection, ret); } } return ret; }
private DefaultHttpRequestContext createRequestContext(FilterChainContext ctx, String scheme, GrizzlyHttpRequestAdapter httpRequest) { DefaultClientConnection clientConnection; SSLSession sslSession = (SSLSession) ctx.getAttributes().getAttribute(SSL_SESSION_ATTRIBUTE_KEY); if (sslSession != null) { clientConnection = new DefaultClientConnection(sslSession, (InetSocketAddress) ctx.getConnection().getPeerAddress()); } else { clientConnection = new DefaultClientConnection((InetSocketAddress) ctx.getConnection().getPeerAddress()); } ServerConnection serverConnection = new DefaultServerConnection((InetSocketAddress) ctx.getConnection().getLocalAddress()); return new DefaultHttpRequestContext(scheme, httpRequest, clientConnection, serverConnection); }
public ResponseStreamingCompletionHandler(final FilterChainContext ctx, final HttpRequestPacket request, final HttpResponse httpResponse, ResponseStatusCallback responseStatusCallback) { Preconditions.checkArgument((httpResponse.getEntity() instanceof InputStreamHttpEntity), "http response must have an input stream entity"); this.ctx = ctx; httpResponsePacket = buildHttpResponsePacket(request, httpResponse); inputStream = ((InputStreamHttpEntity) httpResponse.getEntity()).getInputStream(); memoryManager = ctx.getConnection().getTransport().getMemoryManager(); this.responseStatusCallback = responseStatusCallback; }
@Override public void onError(final Context context, final Object description) throws IOException { context.getConnection().closeSilently(); } }
public FilterChainContext createContext(final Connection connection, final Operation operation) { FilterChain filterChain = (FilterChain) connection.getProcessor(); final FilterChainContext ctx = filterChain.obtainFilterChainContext(connection); final int idx = filterChain.indexOf(this); ctx.setOperation(operation); ctx.setFilterIdx(idx); ctx.setStartIdx(idx); return ctx; }
@Before public void setUp() { HttpEntity entity = new ByteArrayHttpEntity(new byte[1]); responseMock = mock(HttpResponse.class); when(request.getProtocol()).thenReturn(HTTP_1_1); when(responseMock.getEntity()).thenReturn(entity); when(ctx.getConnection()).thenReturn(connection); when(connection.getMemoryManager()).thenReturn(null); when(ctx.getMemoryManager()).thenReturn(null); }