List of usage examples for io.netty.buffer ByteBuf readBytes
public abstract ByteBuf readBytes(ByteBuffer dst);
From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java
License:Open Source License
public static String readStringFixLength(ByteBuf in, int length) { if (length <= 0) { return null; }/*from w w w. j a v a 2s . c o m*/ byte[] result = new byte[length]; in.readBytes(result); String s = new String(result, 0, length); return s; }
From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java
License:Open Source License
public static String readStringWithLength(ByteBuf in, String charset) throws UnsupportedEncodingException { int length = (int) readLength(in); if (length <= 0) { return null; }/*from w ww .ja v a 2s .com*/ byte[] result = new byte[length]; in.readBytes(result); String s = new String(result, 0, length, charset); return s; }
From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java
License:Open Source License
public static String readStringWithLength(ByteBuf in) { int length = (int) readLength(in); if (length <= 0) { return ""; }//from ww w. j a va2 s . c o m byte[] result = new byte[length]; in.readBytes(result); String s = new String(result, 0, length); return s; }
From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java
License:Open Source License
public static Duration readTime(ByteBuf in) { in.readBytes(6); int hour = readInt(in); int minute = readInt(in); int second = readInt(in); return Duration.ofSeconds(hour * 3600 + minute * 60 + second); }
From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java
License:Apache License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); try {//from w w w .j a v a 2 s. c o m fos.flush(); fos.close(); fos = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Send the uppercase string back. String fileName = ((TextWebSocketFrame) frame).text(); logger.debug(String.format("Received file name is [%s]", fileName)); destFile = new File(fileName + ".received"); try { fos = new FileOutputStream(destFile); } catch (FileNotFoundException e) { e.printStackTrace(); } ctx.channel().write(new TextWebSocketFrame(fileName.toUpperCase())); } if (frame instanceof BinaryWebSocketFrame) { byte[] buffer = null; ByteBuf rawMessage = ((BinaryWebSocketFrame) frame).content(); //logger.debug(">>>> BinaryWebSocketFrame Found, " + rawMessage); // check if this ByteBuf is DIRECT (no backing byte[]) if (rawMessage.hasArray() == false) { int size = rawMessage.readableBytes(); buffer = new byte[size]; rawMessage.readBytes(buffer); try { fos.write(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { buffer = rawMessage.array(); } logger.debug(">>>> Read Byte Array: " + buffer.length); return; } }
From source file:com.basho.riak.client.core.netty.HealthCheckDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> list) throws Exception { // Make sure we have 4 bytes if (in.readableBytes() >= 4) { in.markReaderIndex();//from w w w. j av a2 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); chc.channel().pipeline().remove(this); if (code == RiakMessageCodes.MSG_ErrorResp) { logger.debug("Received MSG_ErrorResp reply to healthcheck"); future.setException((riakErrorToException(protobuf))); } else { logger.debug("Healthcheck op successful; returned code {}", code); future.setMessage(new RiakMessage(code, protobuf)); } } } }
From source file:com.basho.riak.client.core.netty.RiakMessageCodec.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // Make sure we have 4 bytes if (in.readableBytes() >= 4) { in.markReaderIndex();//from w w 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(); return; } else { byte code = in.readByte(); byte[] array = new byte[length - 1]; in.readBytes(array); out.add(new RiakMessage(code, array)); } } }
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();// w w w. ja v a 2 s . c om 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 w w .j ava2 s.co m // 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.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 w ww.j a v a 2s. 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); }