List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> out) throws Exception { // Make sure we have 4 bytes if (in.readableBytes() >= 4) { in.markReaderIndex();/*from ww w .j a v a 2 s .c o m*/ int length = in.readInt(); // See if we have the full frame. if (in.readableBytes() < length) { in.resetReaderIndex(); } else { byte code = in.readByte(); byte[] protobuf = new byte[length - 1]; in.readBytes(protobuf); switch (state) { case TLS_WAIT: switch (code) { case RiakMessageCodes.MSG_StartTls: logger.debug("Received MSG_RpbStartTls reply"); // change state this.state = State.SSL_WAIT; // insert SSLHandler SslHandler sslHandler = new SslHandler(sslEngine); // get promise Future<Channel> hsFuture = sslHandler.handshakeFuture(); // register callback hsFuture.addListener(new SslListener()); // Add handler chc.channel().pipeline().addFirst(Constants.SSL_HANDLER, sslHandler); break; case RiakMessageCodes.MSG_ErrorResp: logger.debug("Received MSG_ErrorResp reply to startTls"); promise.tryFailure((riakErrorToException(protobuf))); break; default: promise.tryFailure( new RiakResponseException(0, "Invalid return code during StartTLS; " + code)); } break; case AUTH_WAIT: chc.channel().pipeline().remove(this); switch (code) { case RiakMessageCodes.MSG_AuthResp: logger.debug("Received MSG_RpbAuthResp reply"); promise.trySuccess(null); break; case RiakMessageCodes.MSG_ErrorResp: logger.debug("Received MSG_ErrorResp reply to auth"); promise.tryFailure(riakErrorToException(protobuf)); break; default: promise.tryFailure( new RiakResponseException(0, "Invalid return code during Auth; " + code)); } break; default: // WTF? logger.error("Received message while not in TLS_WAIT or AUTH_WAIT"); promise.tryFailure( new IllegalStateException("Received message while not in TLS_WAIT or AUTH_WAIT")); } } } }
From source file:com.bay1ts.bay.core.Request.java
License:Apache License
private void readBodyAsBytes() { try {//from w ww. j av a 2 s . c om // bodyAsBytes = IOUtils.toByteArray(fullHttpRequest.getInputStream()); ByteBuf buf = fullHttpRequest.content(); //?.?.. bodyAsBytes = new byte[buf.readableBytes()]; buf.readBytes(bodyAsBytes); // bodyAsBytes=IOUtils.toByteArray() } catch (Exception e) { // LOG.warn("Exception when reading body", e); } }
From source file:com.beeswax.hexbid.parser.BidProtobufParser.java
License:Apache License
/** * Parse serialized protocol buffer Bytebuf to protobuf object.</br> * Preferencing implementation of {@link ProtobufDecoder} * // w w w . j av a 2 s . c om * @param bytebuf * @return protocol buffer message * @throws InvalidProtocolBufferException */ public static <T extends Message.Builder> Message parseProtoBytebuf(ByteBuf bytebuf, T messageBuilder) throws InvalidProtocolBufferException { final byte[] array; final int offset; final int length = bytebuf.readableBytes(); if (bytebuf.hasArray()) { array = bytebuf.array(); offset = bytebuf.arrayOffset() + bytebuf.readerIndex(); } else { array = new byte[length]; bytebuf.getBytes(bytebuf.readerIndex(), array, 0, length); offset = 0; } return messageBuilder.mergeFrom(array, offset, length).buildPartial(); }
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//from www. java 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.book.netty5.codec.NettyMessageEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf sendBuf) throws Exception { if (msg == null || msg.getHeader() == null) throw new Exception("The encode message is null"); sendBuf.writeInt((msg.getHeader().getCrcCode())); sendBuf.writeInt((msg.getHeader().getLength())); sendBuf.writeLong((msg.getHeader().getSessionID())); sendBuf.writeByte((msg.getHeader().getType())); sendBuf.writeByte((msg.getHeader().getPriority())); sendBuf.writeInt((msg.getHeader().getAttachment().size())); String key = null;//from w ww. j a v a 2 s . com byte[] keyArray = null; Object value = null; for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) { key = param.getKey(); keyArray = key.getBytes("UTF-8"); sendBuf.writeInt(keyArray.length); sendBuf.writeBytes(keyArray); value = param.getValue(); marshallingEncoder.encode(value, sendBuf); } key = null; keyArray = null; value = null; if (msg.getBody() != null) { marshallingEncoder.encode(msg.getBody(), sendBuf); } else { sendBuf.writeInt(0); } sendBuf.setInt(4, sendBuf.readableBytes() - 8); }
From source file:com.bosscs.spark.commons.extractor.client.codecs.ActionDecoder.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // Wait until the length prefix is available. if (in.readableBytes() < 5) { return;/*from w ww.j av a 2 s .co m*/ } // Wait until the whole data is available. int dataLength = in.readInt(); if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } // Convert the received data into a new BigInteger. byte[] decoded = new byte[dataLength]; in.readBytes(decoded); ByteArrayInputStream bis = new ByteArrayInputStream(decoded); ObjectInput inObj = null; Action action = null; try { inObj = new ObjectInputStream(bis); action = (Action) inObj.readObject(); } catch (IOException | ClassNotFoundException e) { LOG.error(e.getMessage()); } finally { try { bis.close(); } catch (IOException ex) { // ignore close exception } try { if (inObj != null) { inObj.close(); } } catch (IOException ex) { // ignore close exception } } out.add(action); }
From source file:com.bosscs.spark.commons.extractor.client.codecs.ResponseDecoder.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // Wait until the length prefix is available. if (in.readableBytes() < 5) { return;/* w ww .ja v a 2s . co m*/ } // Wait until the whole data is available. int dataLength = in.readInt(); if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } // Convert the received data into a new BigInteger. byte[] decoded = new byte[dataLength]; in.readBytes(decoded); ByteArrayInputStream bis = new ByteArrayInputStream(decoded); ObjectInput inObj = null; Response response = null; try { inObj = new ObjectInputStream(bis); response = (Response) inObj.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } finally { try { bis.close(); } catch (IOException ex) { // ignore close exception } try { if (inObj != null) { inObj.close(); } } catch (IOException ex) { // ignore close exception } } out.add(response); }
From source file:com.brainlounge.zooterrain.netty.WebSocketServerInboundHandler.java
License:Apache License
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, ByteBuf content, String contentType) {//from w w w . j a v a 2s . c o m FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, contentType); setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); }
From source file:com.buildria.mocking.builder.action.RawBodyActionTest.java
License:Open Source License
@Test public void testApplyResponse() throws Exception { byte[] content = "content".getBytes(); Action action = new RawBodyAction(content); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p"); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); res.headers().add(ACCEPT, "application/xml"); HttpResponse out = action.apply(req, res); assertThat(out, notNullValue());//from w w w . j a va 2 s . c o m assertThat(out.headers().get(CONTENT_LENGTH), is("7")); assertThat(out.headers().get(ACCEPT), is("application/xml")); assertThat(out, instanceOf(DefaultFullHttpResponse.class)); DefaultFullHttpResponse response = (DefaultFullHttpResponse) out; ByteBuf buf = response.content(); byte[] actual = new byte[buf.readableBytes()]; buf.readBytes(actual); assertThat(actual, is(content)); }
From source file:com.buildria.mocking.stub.Call.java
License:Open Source License
public static Call fromRequest(HttpRequest req) { Objects.requireNonNull(req);/*from ww w . j av a2 s .c o m*/ Call call = new Call(); call.method = req.getMethod().name(); QueryStringDecoder decoder = new QueryStringDecoder(req.getUri()); call.path = QueryStringDecoder.decodeComponent(decoder.path()); Map<String, List<String>> params = decoder.parameters(); for (String name : params.keySet()) { List<String> values = params.get(name); for (String value : values) { call.parameters.add(new Pair(name, value)); } } HttpHeaders headers = req.headers(); for (String name : headers.names()) { List<String> values = headers.getAll(name); for (String value : values) { call.headers.add(new Pair(name, value)); } if (CONTENT_TYPE.equalsIgnoreCase(name)) { call.contentType = MediaType.parse(headers.get(CONTENT_TYPE)); } } if (req instanceof ByteBufHolder) { ByteBuf buf = ((ByteBufHolder) req).content(); if (buf != null) { call.body = new byte[buf.readableBytes()]; buf.readBytes(call.body); } } return call; }