List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:com.alibaba.dubbo.qos.server.handler.LocalHostPermitHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (!acceptForeignIp) { if (!((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().isLoopbackAddress()) { ByteBuf cb = Unpooled.wrappedBuffer( (QosConstants.BR_STR + "Foreign Ip Not Permitted." + QosConstants.BR_STR).getBytes()); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); }/*from w ww . j a v a 2 s .c o m*/ } }
From source file:com.alibaba.dubbo.qos.server.handler.QosProcessHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { welcomeFuture = ctx.executor().schedule(new Runnable() { @Override/*from w ww . j av a2 s .c o m*/ public void run() { if (welcome != null) { ctx.write(Unpooled.wrappedBuffer(welcome.getBytes())); ctx.writeAndFlush(Unpooled.wrappedBuffer(prompt.getBytes())); } } }, 500, TimeUnit.MILLISECONDS); }
From source file:com.andrewkroh.cisco.xmlservices.DefaultXmlPushService.java
License:Apache License
/** * Builds a HTTP POST request containing the marshaled CiscoIPPhoneExecute * object in the body.//from w w w .j a va 2 s .co m * * <p/> * The phones require authentication in order to execute the commands. The * specified {@code username} and {@code password} will be included in the * request using HTTP Basic Authentication. * * @param hostname * hostname of the server where the request will be sent * @param username * username for authentiation to the phone * @param password * password for authentication to the phone * @param command * command to execute, this will be marshaled to XML * @param baseCallbackUrl * optional base URL to the callback resource, any URLs in the * outgoing command will have $BASEURL replaced with this value. * {@code callbackUrl} cannot not end with '/'. * @return a fully-populated HTTP request */ private static HttpRequest buildRequest(String hostname, String username, String password, CiscoIPPhoneExecute command, String baseCallbackUrl) { Preconditions.checkNotNull(username, "Username cannot be null."); Preconditions.checkNotNull(password, "Password cannot be null."); Preconditions.checkNotNull(command, "CiscoIPPhoneExecute object cannot be null."); if (baseCallbackUrl != null) { replaceBaseUrlPlaceholder(command, baseCallbackUrl); } // Marshal object to XML and escape the XML: String objectAsXml = XmlMarshaller.marshalToXml(command); String urlEncodedXml = urlEncode(objectAsXml); // Build the content of the POST body: StringBuilder postContent = new StringBuilder(); postContent.append("XML="); postContent.append(urlEncodedXml); // Encode the POST body to bytes: byte[] encodedPostContent = postContent.toString().getBytes(ENCODING); ByteBuf postContentByteBuf = Unpooled.wrappedBuffer(encodedPostContent); // Encode credentials: String encodedCredentials = base64EncodeCredentials(username, password); // Build the HTTP request: FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, CISCO_CGI_EXECUTE_PATH, postContentByteBuf); request.headers().set(HttpHeaders.Names.HOST, hostname); request.headers().set(HttpHeaders.Names.AUTHORIZATION, encodedCredentials); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, encodedPostContent.length); return request; }
From source file:com.andrewkroh.cisco.xmlservices.HttpTestServerHandler.java
License:Apache License
public void setResponse(Object ciscoJaxbObject) { // Marshal object to XML: String objectAsXml = XmlMarshaller.marshalToXml(ciscoJaxbObject); // Build the content of the response body: byte[] bodyContent = objectAsXml.toString().getBytes(Charsets.ISO_8859_1); ByteBuf bodyContentByteBuf = Unpooled.wrappedBuffer(bodyContent); // Build the HTTP response: FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, bodyContentByteBuf); response.headers().set(HttpHeaders.Names.CACHE_CONTROL, Arrays.asList(HttpHeaders.Values.MUST_REVALIDATE, HttpHeaders.Values.NO_STORE)); response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, bodyContent.length); httpResponseRef.set(response);//from www . java 2 s .c o m }
From source file:com.android.tools.idea.diagnostics.crash.GoogleCrashTest.java
License:Apache License
@Ignore @Test/*from w w w . j av a 2 s . co m*/ public void checkServerReceivesPostedData() throws Exception { String expectedReportId = "deadcafe"; Map<String, String> attributes = new ConcurrentHashMap<>(); myTestServer.setResponseSupplier(httpRequest -> { if (httpRequest.method() != HttpMethod.POST) { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST); } HttpPostRequestDecoder requestDecoder = new HttpPostRequestDecoder(httpRequest); try { for (InterfaceHttpData httpData : requestDecoder.getBodyHttpDatas()) { if (httpData instanceof Attribute) { Attribute attr = (Attribute) httpData; attributes.put(attr.getName(), attr.getValue()); } } } catch (IOException e) { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST); } finally { requestDecoder.destroy(); } return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(expectedReportId.getBytes(UTF_8))); }); CrashReport report = CrashReport.Builder.createForException(ourIndexNotReadyException) .setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build(); CompletableFuture<String> reportId = myReporter.submit(report); assertEquals(expectedReportId, reportId.get()); // assert that the server get the expected data assertEquals("AndroidStudioTestProduct", attributes.get(GoogleCrash.KEY_PRODUCT_ID)); assertEquals("1.2.3.4", attributes.get(GoogleCrash.KEY_VERSION)); // Note: the exception message should have been elided assertEquals("com.intellij.openapi.project.IndexNotReadyException: <elided>\n" + STACK_TRACE, attributes.get(GoogleCrash.KEY_EXCEPTION_INFO)); List<String> descriptions = Arrays.asList("2.3.0.0\n1.8.0_73-b02", "2.3.0.1\n1.8.0_73-b02"); report = CrashReport.Builder.createForCrashes(descriptions).setProduct("AndroidStudioTestProduct") .setVersion("1.2.3.4").build(); attributes.clear(); reportId = myReporter.submit(report); assertEquals(expectedReportId, reportId.get()); // check that the crash count and descriptions made through assertEquals(descriptions.size(), Integer.parseInt(attributes.get("numCrashes"))); assertEquals("2.3.0.0\n1.8.0_73-b02\n\n2.3.0.1\n1.8.0_73-b02", attributes.get("crashDesc")); Path testData = Paths.get(AndroidTestBase.getTestDataPath()); List<String> threadDump = Files.readAllLines(testData.resolve(Paths.get("threadDumps", "1.txt")), UTF_8); report = CrashReport.Builder.createForPerfReport("td.txt", Joiner.on('\n').join(threadDump)).build(); attributes.clear(); reportId = myReporter.submit(report); assertEquals(expectedReportId, reportId.get()); assertEquals(threadDump.stream().collect(Collectors.joining("\n")), attributes.get("td.txt")); }
From source file:com.artigile.homestats.HomeStatsHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; byte responseBody[]; final String uri = req.uri(); if (uri.startsWith("/getCurrentHumidity")) { responseBody = getHumidity(); } else if (uri.startsWith("/getCurrentTemp")) { responseBody = getTemperature(); } else if (uri.startsWith("/getCurrentPressure")) { responseBody = getPressure(); } else if (uri.startsWith("/getData")) { responseBody = readDataFromDb(); } else {/*w ww .ja va 2 s .c o m*/ responseBody = "404".getBytes(); } if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(responseBody)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } } }
From source file:com.baidu.jprotobuf.pbrpc.management.HttpServerInboundHandler.java
License:Apache License
private void writeResponse(ChannelHandlerContext ctx, String content) throws Exception { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(content.getBytes("UTF-8"))); response.headers().set(CONTENT_TYPE, "text/html"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, Values.KEEP_ALIVE); }// ww w . j a v a2 s . c o m ctx.write(response); ctx.flush(); }
From source file:com.barry.netty.ServerInitializer.java
License:Apache License
@Override public void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); byte[] bytes = { Constant.TAIL_BYTE }; ByteBuf delimiter = Unpooled.wrappedBuffer(bytes); pipeline.addLast("logging", new LoggingHandler()); // ??// www. j a v a 2s . c om pipeline.addLast("decoderContent", new MessageBufferDecoder()); // ??? pipeline.addLast("DelimiterDecode", new DelimiterBasedFrameDecoder(Constant.MAX_LEN, false, delimiter)); // ??? pipeline.addLast("decoderObj", new MsgDecoder()); // pipeline.addLast("handler", new ServerHandler()); }
From source file:com.beeswax.hexbid.handler.BidHandler.java
License:Apache License
/** * /*w w w. ja v a 2s .c om*/ * Process full bid request with following error codes:</br> * </br> * 200 if it sets bid price in {@link BidAgentResponse} successfully.</br> * 204 if no bid is made for this request</br> * 400 if there is a parsing error {@link BidAgentRequest} or it fails to get bidding strategy.</br> * 500 if server experienced an error.</br> * * @param ChannelHandlerContext * * @return FullHttpResponse * */ public FullHttpResponse processRequest(ChannelHandlerContext ctx, FullHttpRequest request) { LOGGER.debug("/bid request"); try { final BidAgentRequest bidRequest = (BidAgentRequest) BidProtobufParser .parseProtoBytebuf(request.content(), BidAgentRequest.newBuilder()); final Optional<BidAgentResponse> bidResponse = bidder.SetBid(bidRequest); if (!bidResponse.isPresent()) { LOGGER.debug("No Bid"); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT); } final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(bidResponse.get().toByteArray())); response.headers().set(HttpHeaderNames.CONTENT_TYPE, new AsciiString("application/x-protobuf")); return response; } catch (InvalidProtocolBufferException | IllegalArgumentException e) { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, Unpooled.wrappedBuffer("Bad request".getBytes())); } catch (Exception e) { LOGGER.error("Unexpected error when setting bid", e); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer("Internal error when setting bid".getBytes())); } }
From source file:com.beeswax.hexbid.handler.BidHandlerTest.java
License:Apache License
@Test public void processRequestTest_NoAdcandidate() { final BidAgentRequest.Builder requestBuilder = BidAgentRequest.newBuilder(); final ByteBuf requestByteBuf = Unpooled.wrappedBuffer(requestBuilder.build().toByteArray()); final FullHttpRequest request = Mockito.mock(FullHttpRequest.class); Mockito.when(request.content()).thenReturn(requestByteBuf); final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); final BidHandler handler = new BidHandler(); final FullHttpResponse response = handler.processRequest(ctx, request); Assert.assertEquals(HttpResponseStatus.NO_CONTENT, response.status()); Assert.assertEquals(0, response.content().readableBytes()); }