List of usage examples for io.netty.buffer ByteBuf toString
public abstract String toString(Charset charset);
From source file:com.bjond.soa.RibbonPing.java
License:Open Source License
public static void main(String[] args) throws Exception { System.out.println("RibbonPing has been invoked printf"); ///////////////////////////////////////////////////////////////////////// // Eureka Registry Incantation // ///////////////////////////////////////////////////////////////////////// final LifecycleInjector injector = InjectorBuilder.fromModule(new EurekaModule()) .overrideWith(new AbstractModule() { @Override//w ww .ja v a 2 s .c o m protected void configure() { // the default impl of EurekaInstanceConfig is CloudInstanceConfig, which we only want in an AWS // environment. Here we override that by binding MyDataCenterInstanceConfig to EurekaInstanceConfig. bind(EurekaInstanceConfig.class).toProvider(MyDataCenterInstanceConfigProvider.class) .in(Scopes.SINGLETON); } }).createInjector(); // this is the vip address for the example service to talk to as defined in conf/sample-eureka-service.properties final String vipAddress = "sampleservice.mydomain.net"; final EurekaClient eurekaClient = injector.getInstance(EurekaClient.class); // This is the line that gathers the list of N number of service URL's for vipAddress. final List<InstanceInfo> listOfInstanceInfo = eurekaClient.getInstancesByVipAddress(vipAddress, false); final InstanceInfo nextServerInfo = listOfInstanceInfo.get(0); // I happen to know there is only one for this test thus I cheat here. System.out.println("Found an instance of example service to talk to from eureka: " + nextServerInfo.getVIPAddress() + ":" + nextServerInfo.getPort()); System.out.println("healthCheckUrl: " + nextServerInfo.getHealthCheckUrl()); System.out.println("override: " + nextServerInfo.getOverriddenStatus()); System.out.println("hostname: " + nextServerInfo.getHostName()); System.out.println("InstanceInfo: " + nextServerInfo.toString()); System.out.println("List<InstanceInfo>: " + listOfInstanceInfo.toString()); System.out.println("RibbonPing has made contact with the Eureka Server"); ///////////////////////////////////////////////////////////////////////// // Programmatic Configuration // ///////////////////////////////////////////////////////////////////////// // The printed properties should correspond to the values set within eureka-client.properties file. final String vipAddressContext = (String) ConfigurationManager.getConfigInstance() .getProperty("IRestService.ribbon.DeploymentContextBasedVipAddresses"); System.out.println("vipAddressContext: " + vipAddressContext); final String sNIWSServerListClassName = (String) ConfigurationManager.getConfigInstance() .getProperty("IRestService.ribbon.NIWSServerListClassName"); System.out.println("NIWSServerListClassName: " + sNIWSServerListClassName); // Let's set the retries for teh IRestService ribbon interface specifically. ConfigurationManager.getConfigInstance() .setProperty("IRestService.ribbon.DeploymentContextBasedVipAddresses." + CommonClientConfigKey.MaxAutoRetriesNextServer, "3"); ///////////////////////////////////////////////////////////////////////// // Proxy Connection // ///////////////////////////////////////////////////////////////////////// final IRestService restService = Ribbon.from(IRestService.class); ByteBuf buffer = restService.ping().execute(); byte[] bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); System.out.println("AS ARRAY: " + new String(bytes, "UTF-8")); System.out.println("Made a ping invocation successfully."); // Send an argument. NOTE that you must escape this for query parameters buffer = restService.echo(URLEncoder.encode("hello world", "UTF-8")).execute(); bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); System.out.println("AS ARRAY: " + new String(bytes, "UTF-8")); System.out.println("Made a ping invocation successfully."); // You can use query params in POST per usual. buffer = restService.echoPost(URLEncoder.encode("hello POST world", "UTF-8")).execute(); bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); System.out.println("AS ARRAY: " + new String(bytes, "UTF-8")); System.out.println("Made a ping invocation successfully."); ///////////////////////////////////////////////////////////////////////// // HttpResourceGroup // ///////////////////////////////////////////////////////////////////////// // Make an invocation using HTTPResourceGroup. // In other words how to perform REST invocations without an annotated proxy. // I would need to construct a list of these if I wanted to round robin a number of servers. // The server list is a comma seperated list for additional servers such as: "localhost:8080,localhost:8088" final String server = String.format("http://%s:%s", nextServerInfo.getHostName(), nextServerInfo.getPort()); final HttpResourceGroup httpResourceGroup = Ribbon.createHttpResourceGroup(vipAddress, ClientOptions.create().withMaxAutoRetriesNextServer(3).withConfigurationBasedServerList(server)); @SuppressWarnings("unchecked") final HttpRequestTemplate<ByteBuf> pingByTemplate = httpResourceGroup .newTemplateBuilder("ping", ByteBuf.class).withMethod("GET") .withUriTemplate("/bjond-resteasy-poc/services/poc/ping").build(); RibbonResponse<ByteBuf> result = pingByTemplate.requestBuilder().build().withMetadata().execute(); ByteBuf buf = result.content(); String value = buf.toString(Charset.forName("UTF-8")); System.out.println("Result: " + value); @SuppressWarnings("unchecked") final HttpRequestTemplate<ByteBuf> echoByTemplate = httpResourceGroup .newTemplateBuilder("echo", ByteBuf.class).withMethod("GET") .withUriTemplate("/bjond-resteasy-poc/services/poc/echo?value={value}").build(); result = echoByTemplate.requestBuilder() .withRequestProperty("value", URLEncoder.encode("hello template world", "UTF-8")).build() .withMetadata().execute(); buf = result.content(); value = buf.toString(Charset.forName("UTF-8")); // this toString() trick only works here. Does not work with annotated proxies. Why? System.out.println("Result: " + value); ///////////////////////////////////////////////////////////////////////// // shutdown // ///////////////////////////////////////////////////////////////////////// ((ProxyLifeCycle) restService).shutdown(); eurekaClient.shutdown(); injector.shutdown(); ConfigurationManager.getConfigInstance().clear(); System.out.println("Shutting down"); // there is some daemon thread presumably in eureka-client I can't find. System.exit(0); }
From source file:com.buildria.mocking.builder.action.BodyActionTest.java
License:Open Source License
@Test public void testApplyResponseUTF8() throws Exception { Object content = person;//from www. j a v a2s.com List<Action> actions = new ArrayList<>(); actions.add(new HeaderAction("Content-Type", "application/json; charset=UTF-8")); Action action = new BodyAction(content, actions); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p"); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse out = action.apply(req, res); assertThat(out, notNullValue()); assertThat(out, instanceOf(DefaultFullHttpResponse.class)); DefaultFullHttpResponse response = (DefaultFullHttpResponse) out; ByteBuf buf = response.content(); byte[] json = buf.toString(StandardCharsets.UTF_8).getBytes(); assertThat(Integer.valueOf(out.headers().get("Content-Length")), is(json.length)); ObjectSerializerContext ctx = new ObjectSerializerContext(SubType.JSON, StandardCharsets.UTF_8); ObjectSerializer serializer = ObjectSerializerFactory.create(ctx); byte[] expected = serializer.serialize(person); assertThat(json, is(expected)); }
From source file:com.buildria.mocking.builder.action.BodyActionTest.java
License:Open Source License
@Test public void testApplyResponseUTF16BE() throws Exception { Object content = person;// w w w . j a v a 2s. co m List<Action> actions = new ArrayList<>(); actions.add(new HeaderAction("Content-Type", "application/json; charset=UTF-16BE")); Action action = new BodyAction(content, actions); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p"); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse out = action.apply(req, res); assertThat(out, notNullValue()); assertThat(out, instanceOf(DefaultFullHttpResponse.class)); DefaultFullHttpResponse response = (DefaultFullHttpResponse) out; ByteBuf buf = response.content(); byte[] json = buf.toString(StandardCharsets.UTF_8).getBytes(); assertThat(Integer.valueOf(out.headers().get("Content-Length")), is(json.length)); ObjectSerializerContext ctx = new ObjectSerializerContext(SubType.JSON, StandardCharsets.UTF_16BE); ObjectSerializer serializer = ObjectSerializerFactory.create(ctx); byte[] expected = serializer.serialize(person); assertThat(json, is(expected)); }
From source file:com.chiorichan.factory.postprocessors.JSMinPostProcessor.java
License:Mozilla Public License
@Override public ByteBuf process(EvalMetaData meta, ByteBuf buf) throws Exception { // A simple way to ignore JS files that might already be minimized if (meta.fileName != null && meta.fileName.toLowerCase().endsWith(".min.js")) return buf; String code = buf.toString(Charset.defaultCharset()); List<SourceFile> externs = Lists.newArrayList(); List<SourceFile> inputs = Arrays.asList(SourceFile.fromCode( (meta.fileName == null || meta.fileName.isEmpty()) ? "fakefile.js" : meta.fileName, code)); Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options); compiler.compile(externs, inputs, options); return Unpooled.buffer().writeBytes(StringUtils.trimToNull(compiler.toSource()).getBytes()); }
From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { send100Continue(ctx);//w w w . j a va 2 s.com } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(request.headers().get(HttpHeaderNames.HOST, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { CharSequence key = h.getKey(); CharSequence value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (CharSequence name : trailer.trailingHeaders().names()) { for (CharSequence value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.codnos.dbgp.internal.handlers.DBGpCommandDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception { int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL); if (nullPosition < 0) return;//from w ww . ja v a 2s . c o m int length = nullPosition - in.readerIndex(); ByteBuf msgBuffer = in.readBytes(length); in.readByte(); objects.add(msgBuffer.toString(UTF_8)); msgBuffer.release(); }
From source file:com.codnos.dbgp.internal.handlers.DBGpResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception { final int length = in.readableBytes(); LOGGER.fine("got something from engine (" + length + " bytes)"); int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL); int readerIndex = in.readerIndex(); int numberOfBytes = nullPosition - readerIndex; LOGGER.fine("found nullposition on " + nullPosition + " and readerIndex is " + readerIndex + " calculated number of bytes " + numberOfBytes); if (numberOfBytes <= 0) { LOGGER.fine("not enough to read, finishing"); in.resetReaderIndex();/*w ww .j a v a 2s . co m*/ return; } if (nullPosition > length) { LOGGER.fine("have null position further than length, finishing"); in.resetReaderIndex(); return; } ByteBuf sizeBuf = in.readBytes(numberOfBytes); in.readByte(); String sizeBufAsString = sizeBuf.toString(UTF_8); int size = Integer.parseInt(sizeBufAsString); int expectedSize = sizeBuf.readableBytes() + NULL_BYTE_SIZE + size + NULL_BYTE_SIZE; if (length < expectedSize) { LOGGER.fine("don't have the whole message yet (expected " + expectedSize + "), finishing"); in.resetReaderIndex(); sizeBuf.release(); return; } ByteBuf messageBuf = in.readBytes(size); in.readByte(); objects.add(messageBuf.toString(UTF_8)); sizeBuf.release(); messageBuf.release(); }
From source file:com.codnos.dbgp.internal.handlers.DBGpResponseEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf byteBuf) throws Exception { String message = (String) msg; byte[] initBytes = message.getBytes(UTF_8); String size = String.valueOf(initBytes.length); byte[] sizeBytes = size.getBytes(UTF_8); final ByteBuf initMessageBuffer = ctx.alloc().buffer(sizeBytes.length + 1 + initBytes.length + 1); initMessageBuffer.writeBytes(sizeBytes); initMessageBuffer.writeZero(1);//from w w w . j a v a 2s . co m initMessageBuffer.writeBytes(initBytes); initMessageBuffer.writeZero(1); LOGGER.fine("sending response=" + initMessageBuffer.toString(UTF_8)); ctx.writeAndFlush(initMessageBuffer); }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out, HttpResponse res) { channel.write(res);//from w ww. java2s.c o m if (log.isTraceEnabled()) { log.trace("Out message: {} - sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId()); } if (out.isReadable()) { channel.write(out); } else { out.release(); } channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE); }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void handleWebsocket(final OutPacketMessage msg, ChannelHandlerContext ctx) throws IOException { while (true) { Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport()); Packet packet = queue.poll();/*from w w w .j av a2 s .co m*/ if (packet == null) { break; } final ByteBuf out = encoder.allocateBuffer(ctx.alloc()); encoder.encodePacket(packet, out, ctx.alloc(), true); WebSocketFrame res = new TextWebSocketFrame(out); if (log.isTraceEnabled()) { log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId()); } if (out.isReadable()) { ctx.channel().writeAndFlush(res); } else { out.release(); } for (ByteBuf buf : packet.getAttachments()) { ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc()); outBuf.writeByte(4); outBuf.writeBytes(buf); if (log.isTraceEnabled()) { log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId()); } ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf)); } } }