List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:com.openddal.server.mysql.MySQLServerHandler.java
License:Apache License
private void sendError(ChannelHandlerContext ctx, Throwable t) { SQLException e = ServerException.toSQLException(t); StringWriter writer = new StringWriter(500); e.printStackTrace(new PrintWriter(writer)); String message = writer.toString(); ByteBuf out = ctx.alloc().buffer(); ERR err = new ERR(); err.sequenceId = nextSequenceId();// w ww. j a va 2 s . c om err.errorCode = e instanceof JdbcSQLException ? ErrorCode.ER_ERROR_WHEN_EXECUTING_COMMAND : e.getErrorCode(); err.errorMessage = message; out.writeBytes(err.toPacket()); ctx.writeAndFlush(out); ACCESSLOGGER.markError((int) err.errorCode, err.errorMessage); }
From source file:com.openddal.server.mysql.MySQLServerHandler.java
License:Apache License
private void sendUpdateResult(ChannelHandlerContext ctx, QueryResult rs) { ByteBuf out = ctx.alloc().buffer(); OK ok = new OK(); ok.sequenceId = nextSequenceId();/*from w w w .java2s. co m*/ ok.affectedRows = rs.getUpdateResult(); ok.setStatusFlag(Flags.SERVER_STATUS_AUTOCOMMIT); out.writeBytes(ok.toPacket()); ctx.writeAndFlush(out); }
From source file:com.openddal.server.mysql.MySQLServerHandler.java
License:Apache License
private void sendQueryResult(ChannelHandlerContext ctx, QueryResult rs) { Resultset resultset = new Resultset(); ByteBuf out = ctx.alloc().buffer(); try {//from ww w .j av a 2s .com resultset.sequenceId = nextSequenceId(); Resultset.characterSet = session.getCharsetIndex(); ResultInterface result = rs.getQueryResult(); int columnCount = result.getVisibleColumnCount(); for (int i = 0; i < columnCount; i++) { ColumnDefinition columnPacket = ResultColumn.getColumn(result, i); resultset.addColumn(columnPacket); } while (result.next()) { ResultsetRow rowPacket = new ResultsetRow(); Value[] v = result.currentRow(); for (int i = 0; i < columnCount; i++) { Value value = v[i]; rowPacket.data.add(value.getString()); } resultset.addRow(rowPacket); } List<byte[]> packets = resultset.toPackets(); for (byte[] bs : packets) { out.writeBytes(bs); } } catch (Exception e) { ERR err = new ERR(); err.sequenceId = resultset.sequenceId++; err.errorCode = ErrorCode.ER_UNKNOWN_ERROR; err.errorMessage = "write resultset error:" + e.getMessage(); out.writeBytes(err.toPacket()); } finally { ctx.writeAndFlush(out); } }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.ConnectEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext chc, ConnectMessage message, ByteBuf out) { ByteBuf staticHeaderBuff = chc.alloc().buffer(12); ByteBuf buff = chc.alloc().buffer(); ByteBuf variableHeaderBuff = chc.alloc().buffer(12); try {//from w w w . ja v a 2 s.c o m staticHeaderBuff.writeBytes(Utils.encodeString("MQIsdp")); //version staticHeaderBuff.writeByte(0x03); //connection flags and Strings byte connectionFlags = 0; if (message.isCleanSession()) { connectionFlags |= 0x02; } if (message.isWillFlag()) { connectionFlags |= 0x04; } connectionFlags |= ((message.getWillQos() & 0x03) << 3); if (message.isWillRetain()) { connectionFlags |= 0x020; } if (message.isPasswordFlag()) { connectionFlags |= 0x040; } if (message.isUserFlag()) { connectionFlags |= 0x080; } staticHeaderBuff.writeByte(connectionFlags); //Keep alive timer staticHeaderBuff.writeShort(message.getKeepAlive()); //Variable part if (message.getClientID() != null) { variableHeaderBuff.writeBytes(Utils.encodeString(message.getClientID())); if (message.isWillFlag()) { variableHeaderBuff.writeBytes(Utils.encodeString(message.getWillTopic())); variableHeaderBuff.writeBytes(Utils.encodeString(message.getWillMessage())); } if (message.isUserFlag() && message.getUsername() != null) { variableHeaderBuff.writeBytes(Utils.encodeString(message.getUsername())); if (message.isPasswordFlag() && message.getPassword() != null) { variableHeaderBuff.writeBytes(Utils.encodeString(message.getPassword())); } } } int variableHeaderSize = variableHeaderBuff.readableBytes(); buff.writeByte(AbstractMessage.CONNECT << 4); buff.writeBytes(Utils.encodeRemainingLength(12 + variableHeaderSize)); buff.writeBytes(staticHeaderBuff).writeBytes(variableHeaderBuff); out.writeBytes(buff); } finally { staticHeaderBuff.release(); buff.release(); variableHeaderBuff.release(); } }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubAckEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext chc, SubAckMessage message, ByteBuf out) { if (message.types().isEmpty()) { throw new IllegalArgumentException("Found a suback message with empty topics"); }// w ww .j a v a 2 s . c o m int variableHeaderSize = 2 + message.types().size(); ByteBuf buff = chc.alloc().buffer(6 + variableHeaderSize); try { buff.writeByte(AbstractMessage.SUBACK << 4); buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize)); buff.writeShort(message.getMessageID()); for (AbstractMessage.QOSType c : message.types()) { buff.writeByte(c.ordinal()); } out.writeBytes(buff); } finally { buff.release(); } }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubscribeEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext chc, SubscribeMessage message, ByteBuf out) { if (message.subscriptions().isEmpty()) { throw new IllegalArgumentException("Found a subscribe message with empty topics"); }/* www .ja v a2 s .c o m*/ if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } ByteBuf variableHeaderBuff = chc.alloc().buffer(4); ByteBuf buff = null; try { variableHeaderBuff.writeShort(message.getMessageID()); for (SubscribeMessage.Couple c : message.subscriptions()) { variableHeaderBuff.writeBytes(Utils.encodeString(c.getTopicFilter())); variableHeaderBuff.writeByte(c.getQos()); } int variableHeaderSize = variableHeaderBuff.readableBytes(); byte flags = Utils.encodeFlags(message); buff = chc.alloc().buffer(2 + variableHeaderSize); buff.writeByte(AbstractMessage.SUBSCRIBE << 4 | flags); buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize)); buff.writeBytes(variableHeaderBuff); out.writeBytes(buff); } finally { variableHeaderBuff.release(); buff.release(); } }
From source file:com.relayrides.pushy.apns.ApnsClientHandler.java
License:Open Source License
@Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise writePromise) throws Http2Exception { if (message instanceof PushNotificationAndResponsePromise) { final PushNotificationAndResponsePromise pushNotificationAndResponsePromise = (PushNotificationAndResponsePromise) message; final ApnsPushNotification pushNotification = pushNotificationAndResponsePromise.getPushNotification(); if (this.responsePromises.containsKey(pushNotification)) { writePromise.tryFailure(new PushNotificationStillPendingException()); } else {/*from w w w . jav a2s .com*/ this.responsePromises.put(pushNotification, pushNotificationAndResponsePromise.getResponsePromise()); pushNotificationAndResponsePromise.getResponsePromise().addListener( new GenericFutureListener<Future<PushNotificationResponse<ApnsPushNotification>>>() { @Override public void operationComplete( final Future<PushNotificationResponse<ApnsPushNotification>> future) { // Regardless of the outcome, when the response promise is finished, we want to remove it from // the map of pending promises. ApnsClientHandler.this.responsePromises.remove(pushNotification); } }); this.write(context, pushNotification, writePromise); } } else if (message instanceof ApnsPushNotification) { final ApnsPushNotification pushNotification = (ApnsPushNotification) message; try { final int streamId = (int) this.nextStreamId; final Http2Headers headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName()) .authority(this.authority).path(APNS_PATH_PREFIX + pushNotification.getToken()) .addInt(APNS_EXPIRATION_HEADER, pushNotification.getExpiration() == null ? 0 : (int) (pushNotification.getExpiration().getTime() / 1000)); final String authenticationToken = this.apnsClient .getAuthenticationTokenSupplierForTopic(pushNotification.getTopic()).getToken(); headers.add(APNS_AUTHORIZATION_HEADER, "bearer " + authenticationToken); if (pushNotification.getCollapseId() != null) { headers.add(APNS_COLLAPSE_ID_HEADER, pushNotification.getCollapseId()); } if (pushNotification.getPriority() != null) { headers.addInt(APNS_PRIORITY_HEADER, pushNotification.getPriority().getCode()); } if (pushNotification.getTopic() != null) { headers.add(APNS_TOPIC_HEADER, pushNotification.getTopic()); } final ChannelPromise headersPromise = context.newPromise(); this.encoder().writeHeaders(context, streamId, headers, 0, false, headersPromise); log.trace("Wrote headers on stream {}: {}", streamId, headers); final ByteBuf payloadBuffer = context.alloc().ioBuffer(INITIAL_PAYLOAD_BUFFER_CAPACITY); payloadBuffer.writeBytes(pushNotification.getPayload().getBytes(StandardCharsets.UTF_8)); final ChannelPromise dataPromise = context.newPromise(); this.encoder().writeData(context, streamId, payloadBuffer, 0, true, dataPromise); log.trace("Wrote payload on stream {}: {}", streamId, pushNotification.getPayload()); final PromiseCombiner promiseCombiner = new PromiseCombiner(); promiseCombiner.addAll(headersPromise, dataPromise); promiseCombiner.finish(writePromise); writePromise.addListener(new GenericFutureListener<ChannelPromise>() { @Override public void operationComplete(final ChannelPromise future) throws Exception { if (future.isSuccess()) { ApnsClientHandler.this.pushNotificationsByStreamId.put(streamId, pushNotification); ApnsClientHandler.this.authenticationTokensByStreamId.put(streamId, authenticationToken); } else { log.trace("Failed to write push notification on stream {}.", streamId, future.cause()); final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = ApnsClientHandler.this.responsePromises .get(pushNotification); if (responsePromise != null) { responsePromise.tryFailure(future.cause()); } else { log.error("Notification write failed, but no response promise found."); } } } }); this.nextStreamId += 2; if (this.nextStreamId >= STREAM_ID_RESET_THRESHOLD) { // This is very unlikely, but in the event that we run out of stream IDs (the maximum allowed is // 2^31, per https://httpwg.github.io/specs/rfc7540.html#StreamIdentifiers), we need to open a new // connection. Just closing the context should be enough; automatic reconnection should take things // from there. context.close(); } } catch (NoKeyForTopicException | SignatureException e) { writePromise.tryFailure(e); } } else { // This should never happen, but in case some foreign debris winds up in the pipeline, just pass it through. log.error("Unexpected object in pipeline: {}", message); context.write(message, writePromise); } }
From source file:com.relayrides.pushy.apns.ApnsClientHandler.java
License:Open Source License
@Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception { if (event instanceof IdleStateEvent) { assert PING_TIMEOUT < ApnsClient.PING_IDLE_TIME_MILLIS; log.trace("Sending ping due to inactivity."); final ByteBuf pingDataBuffer = context.alloc().ioBuffer(8, 8); pingDataBuffer.writeLong(this.nextPingId++); this.encoder().writePing(context, false, pingDataBuffer, context.newPromise()) .addListener(new GenericFutureListener<ChannelFuture>() { @Override// www.j a v a 2s . co m public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { ApnsClientHandler.this.pingTimeoutFuture = future.channel().eventLoop() .schedule(new Runnable() { @Override public void run() { log.debug("Closing channel due to ping timeout."); future.channel().close(); } }, PING_TIMEOUT, TimeUnit.SECONDS); } else { log.debug("Failed to write PING frame.", future.cause()); future.channel().close(); } } }); this.flush(context); } super.userEventTriggered(context, event); }
From source file:com.replaymod.sponge.recording.spongecommon.SpongeConnectionEventListener.java
License:MIT License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!firedInitializing && "net.minecraft.network.login.server.S02PacketLoginSuccess".equals(msg.getClass().getName())) { Object profile = Reflection.getFieldValueByType(msg.getClass(), "com.mojang.authlib.GameProfile", msg); String name = (String) Reflection.getFieldValueByType(profile.getClass(), "java.lang.String", profile); UUID uuid = (UUID) Reflection.getFieldValueByType(profile.getClass(), "java.util.UUID", profile); spongeConnection.getGame().getEventManager() .post(new SpongeConnectionInitializingEvent(spongeConnection, name, uuid)); firedInitializing = true;// w w w.jav a 2s . c o m Optional<Recorder> recorder = spongeConnection.getRecorder(); if (recorder.isPresent()) { SpongeRecorder spongeRecorder = (SpongeRecorder) recorder.get(); ByteBuf buf = ctx.alloc().buffer(16); buf.writeLong(uuid.getMostSignificantBits()); buf.writeLong(uuid.getLeastSignificantBits()); spongeRecorder.writePacket(false, buf); buf.release(); } } super.write(ctx, msg, promise); }
From source file:com.sample.netty.socket.client.ClientHandlerOutbound.java
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ByteBuf encoded = ctx.alloc().buffer(4); encoded.writeBytes(((String) msg).getBytes()); ctx.writeAndFlush(encoded, promise); LOG.trace("[CLIENT SEND MENSSAGE] " + msg); }