List of usage examples for io.netty.handler.codec.http HttpContent copy
@Override
HttpContent copy();
From source file:com.neoba.DsyncserverHandler.java
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpContent con) throws Exception { ByteBuf in = (ByteBuf) con.copy().content(); if (in.array().length == 0) { String time = (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())).toString(); respondAndFlush(Unpooled.wrappedBuffer( ("<h1>Neoba Experimental Server 1</h1>" + time + "<br>Status:OK<br>Please use the client") .getBytes()),/*from w ww. jav a2s . com*/ ctx, true); logger.info("Browser request - responded"); return; } //System.out.println(new String(in.array())); msgcount += 1; logger.info("Message Received from ip " + ctx.channel().remoteAddress() + ":" + msgcount); ConsoleUtils.printhex("request", in.array(), in.array().length); MessageInterpreter mi = new MessageInterpreter(ctx, in); ByteBuf reply = mi.generateReply(); ConsoleUtils.printhex("response", reply.array(), reply.array().length); respondAndFlush(reply, ctx, false); logger.info("Message Responded :" + msgcount); }
From source file:fileShare.ShareHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; System.out.println("==================================HttpRequest=================================="); System.out.println(msg.toString()); URI uri = new URI(request.getUri()); if (uri.getPath().startsWith("/getFile")) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append(i + ","); }//from w w w . j a v a2s . com //HttpContent httpContent = blockingFile.take(); //ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteses); ByteBuf wrappedBufferA = copiedBuffer(sb.toString(), CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, wrappedBufferA); response.headers().set(CONTENT_TYPE, "application/octet-stream"); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, wrappedBufferA.readableBytes()); // Write the initial line and the header. //ctx.write(response); ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx); return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } catch (IncompatibleDataDecoderException e1) { // GET Method: should not try to create a HttpPostRequestDecoder // So OK but stop here responseContent.append(e1.getMessage()); responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); writeResponse(ctx.channel()); return; } readingChunks = HttpHeaders.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { System.out.println( "==================================HttpContent=================================="); //? System.out.println(new String(((DefaultHttpContent) chunk).content().array())); blockingFile.put(chunk.copy()); decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; send = false; reset(); } } } }
From source file:org.thingsplode.synapse.endpoint.handlers.ResponseIntrospector.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg == null) { logger.warn("Message@Endpoint <to be sent> is NULL."); } else if (logger.isDebugEnabled() && ((msg instanceof HttpResponse) || (msg instanceof HttpContent))) { if (!(msg instanceof HttpResponse)) { HttpContent content = (HttpContent) msg; logger.debug("Message@Endpoint to be sent: http content -> " + content.toString()); } else {/* w w w . j a v a 2 s . c om*/ final StringBuilder hb = new StringBuilder(); ((HttpResponse) msg).headers().entries().forEach(e -> { hb.append(e.getKey()).append(" : ").append(e.getValue()).append("\n"); }); String payloadAsSring = null; if (msg instanceof FullHttpResponse) { ByteBuf content = ((FullHttpResponse) msg).content(); byte[] dst = content.copy().array(); //content.copy().getBytes(0, dst); content.retain(); payloadAsSring = new String(dst, Charset.forName("UTF-8")); } String msgStatus = (((HttpResponse) msg).status() != null ? ((HttpResponse) msg).status().toString() : "NULL"); logger.debug("Message@Endpoint [" + msg.getClass().getSimpleName() + "] to be sent: \n\n" + "Status: " + msgStatus + "\n" + hb.toString() + "\n" + "Payload: [" + (!Util.isEmpty(payloadAsSring) ? payloadAsSring : "EMPTY") + "]\n"); } } else if (logger.isDebugEnabled() && (msg instanceof WebSocketFrame)) { if (msg instanceof TextWebSocketFrame) { logger.debug("Message@Endpoint [" + msg.getClass().getSimpleName() + "] to be sent: " + msg.getClass().getSimpleName() + " \n\n" + ((TextWebSocketFrame) msg).text()); } else { logger.debug("Message@Endpoint [" + msg.getClass().getSimpleName() + "] to be sent: \n\n {" + msg.getClass().getSimpleName() + " -> " + msg.toString() + "}"); } } else { logger.debug( "Unknown message (" + msg.getClass().getSimpleName() + ") will be dispatched to the client."); } ctx.write(msg, promise); }