throws IOException { final MemoryManager mm = ctx.getMemoryManager(); Buffer buffer = mm.allocate(512); final byte[] b = new byte[512]; if (read > buffer.remaining()) { buffer = mm.reallocate(buffer, buffer.capacity() + 512); buffer.put(b, 0, read); buffer.trim(); if (buffer.hasRemaining()) { final HttpContent content = requestPacket.httpContentBuilder() .content(buffer) .last(true) .build(); buffer.allowBufferDispose(false); ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
/** * Build the <tt>HttpContent</tt> message. * * @return <tt>HttpContent</tt> */ public HttpContent build() { if (httpHeader == null) { throw new IllegalStateException("No HttpHeader specified to associate with this HttpContent."); } HttpContent httpContent = create(); httpContent.httpHeader = httpHeader; httpContent.setLast(last); if (content != null) { httpContent.setContent(content); } return httpContent; }
private void send() { final int chunkSize = 8192; try { boolean isLast; do { final Buffer buffer = ctx.getMemoryManager().allocate(chunkSize); buffer.allowBufferDispose(true); final long readNow = Buffers.readFromFileChannel(fc, buffer); isLast = readNow <= 0 || (remaining -= readNow) <= 0; buffer.trim(); ctx.write(HttpContent.builder(response) .content(buffer) .last(isLast) .build()); } while (!isLast && output.canWrite()); if (isLast) { done(); } else { output.notifyCanWrite(this); } } catch (IOException e) { done(); } }
@SuppressWarnings({"unchecked"}) public boolean generate(final FilterChainContext ctx, final Request request, final HttpRequestPacket requestPacket) throws IOException { final MemoryManager mm = ctx.getMemoryManager(); final byte[] data = request.getByteData(); final Buffer gBuffer = Buffers.wrap(mm, data); if (requestPacket.getContentLength() == -1) { requestPacket.setContentLengthLong(data.length); } final HttpContent content = requestPacket.httpContentBuilder() .content(gBuffer) .last(true) .build(); ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null)); return true; }
public void initialize(final HttpHeader outputHeader, final boolean sendfileEnabled, final FilterChainContext ctx) { this.outputHeader = outputHeader; if (builder == null) { this.builder = outputHeader.httpContentBuilder(); } else { builder.httpHeader(outputHeader); } this.sendfileEnabled = sendfileEnabled; this.ctx = ctx; httpContext = outputHeader.getProcessingState().getHttpContext(); connection = ctx.getConnection(); memoryManager = ctx.getMemoryManager(); }
final long len = bodyLocal.getContentLength(); if (len >= 0) { requestPacket.setContentLengthLong(len); } else { requestPacket.setChunked(true); final MemoryManager mm = ctx.getMemoryManager(); boolean last = false; buffer.allowBufferDispose(true); final long readBytes = bodyLocal.read(buffer.toByteBuffer()); if (readBytes > 0) { buffer.position((int) readBytes); buffer.trim(); } else { requestPacket.httpContentBuilder().content(buffer). last(last).build(); ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
@Override public void write(WebSocketResponse response) { if (ctx == null) { throw new UnsupportedOperationException("not supported on client side"); } final HttpResponsePacket responsePacket = ((HttpRequestPacket) httpContent.getHttpHeader()).getResponse(); responsePacket.setProtocol(Protocol.HTTP_1_1); responsePacket.setStatus(response.getStatus()); for (Map.Entry<String, String> entry : response.getHeaders().entrySet()) { responsePacket.setHeader(entry.getKey(), entry.getValue()); } ctx.write(HttpContent.builder(responsePacket).build()); }
public void sendInputStreamChunk() throws IOException { final Buffer buffer = memoryManager.allocate(bufferSize); final byte[] bufferByteArray = buffer.array(); final int offset = buffer.arrayOffset(); final int length = buffer.remaining(); int bytesRead = inputStream.read(bufferByteArray, offset, length); final HttpContent content; if (bytesRead == -1) { content = httpResponsePacket.httpTrailerBuilder().build(); isDone = true; } else { buffer.limit(bytesRead); content = httpResponsePacket.httpContentBuilder().content(buffer).build(); } ctx.write(content, this); }
throws IOException { if (requestPacket.getContentType() == null) { requestPacket.setContentType("application/x-www-form-urlencoded"); final MemoryManager mm = ctx.getMemoryManager(); final Buffer gBuffer = Buffers.wrap(mm, data); final HttpContent content = requestPacket.httpContentBuilder() .content(gBuffer) .last(true) .build(); if (requestPacket.getContentLength() == -1) { requestPacket.setContentLengthLong(data.length); ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
private NextAction sendRequest(FilterChainContext ctx, UpgradeRequest upgradeRequest) { HttpRequestPacket.Builder builder = HttpRequestPacket.builder(); if (proxy && !PROXY_CONNECTED.get(ctx.getConnection())) { UPGRADE_REQUEST.set(ctx.getConnection(), upgradeRequest); URI requestURI = upgradeRequest.getRequestURI(); final int requestPort = Utils.getWsPort(requestURI); builder = builder.uri(String.format("%s:%d", requestURI.getHost(), requestPort)); builder = builder.protocol(Protocol.HTTP_1_1); builder = builder.method(Method.CONNECT); if (proxyHeaders != null && proxyHeaders.size() > 0) { for (Map.Entry<String, String> entry : proxyHeaders.entrySet()) { builder.header(entry.getKey(), entry.getValue()); } } builder = builder.header(Header.Host, requestURI.getHost()); builder = builder.header(Header.ProxyConnection, "keep-alive"); builder = builder.header(Header.Connection, "keep-alive"); ctx.write(HttpContent.builder(builder.build()).build()); ctx.flush(null); } else { ctx.write(getHttpContent(upgradeRequest)); } // call the next filter in the chain return ctx.getInvokeAction(); }
requestPacket.setContentLengthLong(f.length()); final HttpTransactionContext context = HttpTransactionContext.currentTransaction(requestPacket); if (!SEND_FILE_SUPPORT || requestPacket.isSecure()) { final MemoryManager mm = ctx.getMemoryManager(); AtomicInteger written = new AtomicInteger(); boolean last = false; requestPacket.httpContentBuilder().content(b). last(last).build(); ctx.write(content, ((!requestPacket.isCommitted()) ? ctx.getTransportContext().getCompletionHandler() : null));
if (buffer.hasRemaining()) { throw new IOException("Last chunk was alredy written"); blockUntilQueueFree(feedableBodyGenerator.context.getConnection()); final HttpContent content = feedableBodyGenerator.contentBuilder.content(buffer).last(last).build(); final CompletionHandler<WriteResult> handler = ((last) ? new LastPacketCompletionHandler() : null); feedableBodyGenerator.context.write(content, handler);
/** * Builds {@link HttpContent} based on passed payload {@link Buffer}. * If the payload size is <tt>0</tt> and the input buffer has been terminated - * return {@link HttpBrokenContent}. */ private HttpContent buildHttpContent(final Buffer payload) { final Termination localTermination = closeFlag; final boolean isFin = localTermination == IN_FIN_TERMINATION; final HttpContent httpContent; // if payload size is not 0 or this is FIN payload if (payload.hasRemaining() || localTermination == null || isFin) { final HttpHeader inputHttpHeader = stream.getInputHttpHeader(); inputHttpHeader.setExpectContent(!isFin); httpContent = HttpContent.builder(inputHttpHeader) .content(payload) .last(isFin) .build(); } else { // create broken HttpContent httpContent = buildBrokenHttpContent( new EOFException(localTermination.getDescription())); } return httpContent; }
private void writeHttpResponse(FilterChainContext ctx, int status) { HttpResponsePacket responsePacket = getHttpRequest(ctx).getResponse(); responsePacket.setProtocol(Protocol.HTTP_1_1); responsePacket.setStatus(status); ctx.write(HttpContent.builder(responsePacket).build()); }
private void flushBuffer(final Buffer bufferToFlush, final boolean isLast, final MessageCloner<Buffer> messageCloner) throws IOException { final HttpContent content; if (isLast && trailersSupplier != null && (outputHeader.isChunked() || outputHeader.getProtocol().equals(Protocol.HTTP_2_0))) { forceCommitHeaders(false); HttpTrailer.Builder tBuilder = outputHeader.httpTrailerBuilder().content(bufferToFlush).last(true); final Map<String, String> trailers = trailersSupplier.get(); if (trailers != null && !trailers.isEmpty()) { for (Map.Entry<String, String> entry : trailers.entrySet()) { tBuilder.header(entry.getKey(), entry.getValue()); } } content = tBuilder.build(); } else { content = builder.content(bufferToFlush).last(isLast).build(); } ctx.write(null, content, null, messageCloner, IS_BLOCKING); }
/** * Method handles Grizzly {@link Connection} close phase. Check if the {@link Connection} is a {@link org.glassfish.tyrus.websockets.WebSocket}, if * yes - tries to close the websocket gracefully (sending close frame) and calls {@link * org.glassfish.tyrus.websockets.WebSocket#onClose(org.glassfish.tyrus.websockets.draft06.ClosingFrame)}. If the Grizzly {@link Connection} is not websocket - passes processing to the next * filter in the chain. * * @param ctx {@link FilterChainContext} * @return {@link NextAction} instruction for {@link FilterChain}, how it should continue the execution * @throws IOException */ @Override public NextAction handleClose(FilterChainContext ctx) throws IOException { // Get the Connection final org.glassfish.tyrus.websockets.Connection connection = getWebSocketConnection(ctx, HttpContent.builder(HttpRequestPacket.builder().build()).build()); // check if Connection has associated WebSocket (is websocket) if (webSocketInProgress(connection)) { // if yes - get websocket final WebSocket ws = getWebSocket(connection); if (ws != null) { // if there is associated websocket object (which means handshake was passed) // close it gracefully ws.close(); WebSocketEngine.getEngine().removeConnection(connection); } } return ctx.getInvokeAction(); }
public void respond(final FilterChainContext ctx, final WebSocketApplication application, final HttpResponsePacket response) { response.setProtocol(Protocol.HTTP_1_1); response.setStatus(HttpStatus.SWITCHING_PROTOCOLS_101); response.setHeader("Upgrade", "websocket"); response.setHeader("Connection", "Upgrade"); setHeaders(response); if (!getSubProtocol().isEmpty()) { response.setHeader(Constants.SEC_WS_PROTOCOL_HEADER, join(application.getSupportedProtocols(getSubProtocol()))); } if (!application.getSupportedExtensions().isEmpty() && !getExtensions().isEmpty()) { List<Extension> intersection = intersection(getExtensions(), application.getSupportedExtensions()); if (!intersection.isEmpty()) { application.onExtensionNegotiation(intersection); response.setHeader(Constants.SEC_WS_EXTENSIONS_HEADER, joinExtensions(intersection)); } } ctx.write(HttpContent.builder(response).build()); }