io.netty.handler.codec.EncoderException Java Examples
The following examples show how to use
io.netty.handler.codec.EncoderException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PublishWritePromiseListener.java From hivemq-community-edition with Apache License 2.0 | 6 votes |
@Override public void operationComplete(final Future<? super Void> future) throws Exception { if (!future.isSuccess()) { final Throwable cause = future.cause(); if (Exceptions.isConnectionClosedException(cause)) { log.trace("Failed to write publish. Client not connected anymore"); statusFuture.set(PublishStatus.NOT_CONNECTED); } else if (cause instanceof EncoderException) { Exceptions.rethrowError("Failed to write publish. Encoding Failure.", cause); final Throwable rootCause = cause.getCause(); if (cause != rootCause) { Exceptions.rethrowError("Failed to write publish. Encoding Failure, root cause:", rootCause); } statusFuture.set(PublishStatus.FAILED); } else { Exceptions.rethrowError("Failed to write publish.", cause); statusFuture.set(PublishStatus.FAILED); } } }
Example #2
Source File: VarNumberSerializer.java From ProtocolSupport with GNU Affero General Public License v3.0 | 6 votes |
public static void writeFixedSizeVarInt(ByteBuf to, int i, int length) { int writerIndex = to.writerIndex(); while ((i & 0xFFFFFF80) != 0x0) { to.writeByte(i | 0x80); i >>>= 7; } int paddingBytes = length - (to.writerIndex() - writerIndex) - 1; if (paddingBytes < 0) { throw new EncoderException("Fixed size VarInt too big"); } if (paddingBytes == 0) { to.writeByte(i); } else { to.writeByte(i | 0x80); while (--paddingBytes > 0) { to.writeByte(0x80); } to.writeByte(0); } }
Example #3
Source File: KeyValueHandlerTest.java From couchbase-jvm-core with Apache License 2.0 | 6 votes |
@Test public void shouldPropagateErrorOnEncode() { String id = "key"; ByteBuf content = Unpooled.buffer(); content.release(); // provoke a IllegalReferenceCountException UpsertRequest request = new UpsertRequest(id, content, BUCKET); request.partition((short) 1); TestSubscriber<CouchbaseResponse> ts = TestSubscriber.create(); request.observable().subscribe(ts); try { channel.writeOutbound(request); fail("Expected exception, none thrown."); } catch (EncoderException ex) { assertTrue(ex.getCause() instanceof IllegalReferenceCountException); } List<Throwable> onErrorEvents = ts.getOnErrorEvents(); assertTrue(onErrorEvents.get(0) instanceof RequestCancelledException); assertTrue(onErrorEvents.get(0).getCause() instanceof IllegalReferenceCountException); }
Example #4
Source File: ByteBufUtilsEU.java From enderutilities with GNU Lesser General Public License v3.0 | 6 votes |
public static void writeNBTTagCompoundToBuffer(ByteBuf buf, NBTTagCompound tag) { if (tag == null) { buf.writeByte(0); return; } try { CompressedStreamTools.write(tag, new ByteBufOutputStream(buf)); } catch (IOException ioexception) { EnderUtilities.logger.error("IOException while trying to write a NBTTagCompound to ByteBuf"); throw new EncoderException(ioexception); } }
Example #5
Source File: APDUEncoder.java From neoscada with Eclipse Public License 1.0 | 6 votes |
private void handleIFormat ( final InformationTransfer msg, ByteBuf out ) { final ByteBuf data = msg.getData (); try { out = out.order ( ByteOrder.LITTLE_ENDIAN ); final int len = data.readableBytes (); if ( len > Constants.APCI_MAX_DATA_LENGTH ) { throw new EncoderException ( String.format ( "Packet too big - %s bytes", len ) ); } out.ensureWritable ( 6 + len ); out.writeByte ( Constants.START_BYTE ); out.writeByte ( 4 + len ); out.writeShort ( msg.getSendSequenceNumber () << 1 ); out.writeShort ( msg.getReceiveSequenceNumber () << 1 ); out.writeBytes ( data ); } finally { ReferenceCountUtil.release ( msg.getData () ); } }
Example #6
Source File: ProtostuffEncoder.java From c5-replicator with Apache License 2.0 | 6 votes |
@Override protected void encode(ChannelHandlerContext ctx, Message<T> msg, List<Object> out) throws Exception { Schema<T> schema = msg.cachedSchema(); LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput(); schema.writeTo(lcpo, (T) msg); List<ByteBuffer> buffers = lcpo.buffer.finish(); long size = lcpo.buffer.size(); if (size > Integer.MAX_VALUE) { throw new EncoderException("Serialized form was too large, actual size: " + size); } out.add(Unpooled.wrappedBuffer(buffers.toArray(new ByteBuffer[]{}))); }
Example #7
Source File: AbstractPacketEncoder.java From ProtocolSupportBungee with GNU Affero General Public License v3.0 | 6 votes |
@Override public void write(final ChannelHandlerContext ctx, final Object msgObject, final ChannelPromise promise) throws Exception { try { if (acceptOutboundMessage(msgObject)) { DefinedPacket msg = (DefinedPacket) msgObject; try { encode(ctx, msg, null); } finally { ReferenceCountUtil.release(msg); } } else { ctx.write(msgObject, promise); } } catch (EncoderException e) { throw e; } catch (Throwable e2) { throw new EncoderException(e2); } }
Example #8
Source File: LowCopyProtocolEncoder.java From Jupiter with Apache License 2.0 | 6 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ByteBuf buf = null; try { if (msg instanceof PayloadHolder) { PayloadHolder cast = (PayloadHolder) msg; buf = encode(cast); ctx.write(buf, promise); buf = null; } else { ctx.write(msg, promise); } } catch (Throwable t) { throw new EncoderException(t); } finally { if (buf != null) { buf.release(); } } }
Example #9
Source File: PacketCustom.java From CodeChickenLib with GNU Lesser General Public License v2.1 | 6 votes |
/** * Decompresses the remaining ByteBuf (after type has been read) using Snappy */ private void decompress() { Inflater inflater = new Inflater(); try { int len = readInt(); byte[] out = new byte[len]; inflater.setInput(array(), readerIndex(), readableBytes()); inflater.inflate(out); clear(); writeByteArray(out); } catch (Exception e) { throw new EncoderException(e); } finally { inflater.end(); } }
Example #10
Source File: PacketCustom.java From CodeChickenLib with GNU Lesser General Public License v2.1 | 6 votes |
/** * Compresses the payload ByteBuf after the type byte */ private void do_compress() { Deflater deflater = new Deflater(); try { readerIndex(1); int len = readableBytes(); deflater.setInput(array(), readerIndex(), len); deflater.finish(); byte[] out = new byte[len]; int clen = deflater.deflate(out); if (clen >= len - 5 || !deflater.finished())//not worth compressing, gets larger return; clear(); writeByte(type | 0x80); writeVarInt(len); writeByteArray(out); } catch (Exception e) { throw new EncoderException(e); } finally { readerIndex(0); deflater.end(); } }
Example #11
Source File: EppProtocolModuleTest.java From nomulus with Apache License 2.0 | 6 votes |
@Test public void testFailure_nonOkOutboundMessage() throws Exception { // First inbound message is hello. channel.readInbound(); byte[] outputBytes = readResourceBytes(getClass(), "login_response.xml").read(); // Verify outbound message is not written to the peer as the response is not OK. EncoderException thrown = assertThrows( EncoderException.class, () -> channel.writeOutbound( makeEppHttpResponse(outputBytes, HttpResponseStatus.UNAUTHORIZED))); assertThat(Throwables.getRootCause(thrown)).isInstanceOf(NonOkHttpResponseException.class); assertThat(thrown).hasMessageThat().contains("401 Unauthorized"); assertThat((Object) channel.readOutbound()).isNull(); // Channel is closed. assertThat(channel.isActive()).isFalse(); }
Example #12
Source File: PacketCustom.java From CodeChickenLib with GNU Lesser General Public License v2.1 | 5 votes |
public NBTTagCompound readNBTTagCompound() { try { return readNBTTagCompoundFromBuffer(); } catch (IOException e) { throw new EncoderException(e); } }
Example #13
Source File: MCDataOutputWrapper.java From CodeChickenLib with GNU Lesser General Public License v2.1 | 5 votes |
public MCDataOutputWrapper writeArray(byte[] barray) { try { dataout.write(barray); } catch (IOException e) { throw new EncoderException(e); } return this; }
Example #14
Source File: MCDataOutputWrapper.java From CodeChickenLib with GNU Lesser General Public License v2.1 | 5 votes |
@Override public MCDataOutputWrapper writeChar(char c) { try { dataout.writeChar(c); } catch (IOException e) { throw new EncoderException(e); } return this; }
Example #15
Source File: MCDataOutputWrapper.java From CodeChickenLib with GNU Lesser General Public License v2.1 | 5 votes |
public MCDataOutputWrapper writeLong(long l) { try { dataout.writeLong(l); } catch (IOException e) { throw new EncoderException(e); } return this; }
Example #16
Source File: MCDataOutputWrapper.java From CodeChickenLib with GNU Lesser General Public License v2.1 | 5 votes |
public MCDataOutputWrapper writeDouble(double d) { try { dataout.writeDouble(d); } catch (IOException e) { throw new EncoderException(e); } return this; }
Example #17
Source File: MCDataOutputWrapper.java From CodeChickenLib with GNU Lesser General Public License v2.1 | 5 votes |
public MCDataOutputWrapper writeNBTTagCompound(NBTTagCompound nbt) { if (nbt == null) this.writeByte(0); else try { CompressedStreamTools.write(nbt, dataout); } catch (IOException ioexception) { throw new EncoderException(ioexception); } return this; }
Example #18
Source File: ItemStackSerializer.java From ProtocolSupport with GNU Affero General Public License v3.0 | 5 votes |
/** * Writes tag using legacy protocol version format (Prefixes serialized nbt data with short length). * @param to buffer to write to * @param tag nbt compound */ public static void writeShortTag(ByteBuf to, NBTCompound tag) { if (tag == null) { to.writeShort(-1); } else { ArraySerializer.writeShortByteArray(to, lTo -> { try (DataOutputStream outputstream = new DataOutputStream(new GZIPOutputStream(new ByteBufOutputStream(lTo)))) { DefaultNBTSerializer.INSTANCE.serializeTag(outputstream, tag); } catch (Exception e) { throw new EncoderException(e); } }); } }
Example #19
Source File: EppServiceHandlerTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testFailure_disconnectOnNonOKResponseStatus() throws Exception { setHandshakeSuccess(); String content = "<epp>stuff</epp>"; EncoderException thrown = assertThrows( EncoderException.class, () -> channel.writeOutbound( makeEppHttpResponse(content, HttpResponseStatus.BAD_REQUEST))); assertThat(Throwables.getRootCause(thrown)).isInstanceOf(NonOkHttpResponseException.class); assertThat(thrown).hasMessageThat().contains(HttpResponseStatus.BAD_REQUEST.toString()); assertThat((Object) channel.readOutbound()).isNull(); assertThat(channel.isActive()).isFalse(); }
Example #20
Source File: ItemStackSerializer.java From ProtocolSupport with GNU Affero General Public License v3.0 | 5 votes |
/** * Writes tag using latest protocol version format (Directly serializes nbt to buffer). * @param to buffer to write to * @param tag nbt compound */ public static void writeDirectTag(ByteBuf to, NBTCompound tag) { try (ByteBufOutputStream outputstream = new ByteBufOutputStream(to)) { if (tag != null) { DefaultNBTSerializer.INSTANCE.serializeTag(outputstream, tag); } else { DefaultNBTSerializer.INSTANCE.serializeTag(outputstream, NBTEnd.INSTANCE); } } catch (IOException e) { throw new EncoderException(e); } }
Example #21
Source File: Mqtt5MessageWithUserPropertiesEncoder.java From hivemq-community-edition with Apache License 2.0 | 5 votes |
@Override public void encode(@NotNull final ChannelHandlerContext ctx, @NotNull final T message, @NotNull final ByteBuf out) { Preconditions.checkNotNull(ctx, "ChannelHandlerContext must never be null"); Preconditions.checkNotNull(message, "Message must never be null"); Preconditions.checkNotNull(out, "ByteBuf must never be null"); if (message.getOmittedProperties() > 0) { final String clientIdFromChannel = ctx.channel().attr(ChannelAttributes.CLIENT_ID).get(); final String clientId = clientIdFromChannel != null ? clientIdFromChannel : "UNKNOWN"; final long maximumPacketSize = calculateMaxMessageSize(ctx.channel()); //PUBLISH must not omit any properties if (message instanceof PUBLISH) { // The maximal packet size exceeds the clients accepted packet size ctx.fireUserEventTriggered(new PublishDroppedEvent((PUBLISH) message)); messageDroppedService.publishMaxPacketSizeExceeded(clientId, ((PUBLISH) message).getTopic(), ((PUBLISH) message).getQoS().getQosNumber(), maximumPacketSize, message.getEncodedLength()); log.trace("Could not encode publish message for client ({}): Maximum packet size limit exceeded", clientId); return; } if (message.getPropertyLength() < 0 && message.getEncodedLength() > maximumPacketSize) { messageDroppedService.messageMaxPacketSizeExceeded(clientId, message.getType().name(), maximumPacketSize, message.getEncodedLength()); log.trace("Could not encode message of type {} for client {}: Packet to large", message.getType(), clientId); throw new EncoderException("Maximum packet size exceeded"); } } encode(message, out); }
Example #22
Source File: AbstractPacketEncoder.java From ProtocolSupport with GNU Affero General Public License v3.0 | 5 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!(msg instanceof ByteBuf)) { super.write(ctx, msg, promise); return; } ByteBuf input = (ByteBuf) msg; if (!input.isReadable()) { input.release(); promise.setSuccess(); return; } ClientBoundMiddlePacket packetTransformer = null; try { packetTransformer = registry.getTransformer(connection.getNetworkState(), VarNumberSerializer.readVarInt(input)); codec.channelWrite(promise, packetTransformer, input, (transformer, data) -> transformer.encode(data)); if (input.isReadable()) { throw new DecoderException("Data not read fully, bytes left " + input.readableBytes()); } } catch (Exception exception) { if (ServerPlatform.get().getMiscUtils().isDebugging()) { input.readerIndex(0); throw new EncoderException(MessageFormat.format( "Unable to transform or read clientbound middle packet(type {0}, data {1})", packetTransformer != null ? packetTransformer.getClass().getName() : "unknown", Arrays.toString(MiscSerializer.readAllBytes(input)) ), exception); } else { throw exception; } } finally { input.release(); } }
Example #23
Source File: EncoderUnitTest.java From xio with Apache License 2.0 | 5 votes |
@Test public void testErrorNoPayload() { thrown.expect(EncoderException.class); thrown.expectMessage("Encoder received Message without anything to encode"); Integer payload = new Integer(1); Request request = new Request(UUID.randomUUID(), SettableFuture.create()); Message message = new Message(request, payload); channel.writeOutbound(message); channel.runPendingTasks(); }
Example #24
Source File: EncoderUnitTest.java From xio with Apache License 2.0 | 5 votes |
@Test public void testErrorInvalidPayload() { thrown.expect(EncoderException.class); thrown.expectMessage("Can only encode Message or ByteBuf"); Integer payload = new Integer(1); Request request = new Request(UUID.randomUUID(), SettableFuture.create()); Message message = new Message(request, payload); channel.writeOutbound(payload); channel.writeOutbound(message); channel.runPendingTasks(); }
Example #25
Source File: Encoder.java From xio with Apache License 2.0 | 5 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof ByteBuf) { if (currentMessage == null) { currentMessage = ctx.alloc().compositeBuffer(); currentMessage.retain(); currentHeader = ctx.alloc().buffer(40, 256); currentMessage.addComponent(currentHeader); } currentMessage.addComponent(true, (ByteBuf) msg); promise.setSuccess(); } else if (msg instanceof Message) { if (error) { reset(); throw new EncoderException("Can only encode Message or ByteBuf"); } if (currentMessage == null) { reset(); throw new EncoderException("Encoder received Message without anything to encode"); } encodeMessage((Message) msg, currentMessage.readableBytes(), currentHeader); currentMessage.addComponent(true, 0, currentHeader); ctx.write(currentMessage, promise); reset(); } else { error = true; } }
Example #26
Source File: GelfMessageJsonEncoderTest.java From gelfclient with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = EncoderException.class) public void testExceptionIsPassedThrough() throws Exception { final JsonFactory jsonFactory = mock(JsonFactory.class); when(jsonFactory.createGenerator(any(OutputStream.class), eq(JsonEncoding.UTF8))).thenThrow(new IOException()); final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder(jsonFactory)); assertTrue(channel.writeOutbound(new GelfMessage("test"))); }
Example #27
Source File: GelfMessageChunkEncoder.java From gelfclient with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override protected void encode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { if (buf.readableBytes() > MAX_MESSAGE_SIZE) { throw new EncoderException("Message too big. " + buf.readableBytes() + " bytes (max " + MAX_MESSAGE_SIZE + ")"); } if (buf.readableBytes() <= MAX_CHUNK_SIZE) { // Need to retain() the buffer here to avoid releasing the buffer too early. out.add(buf.retain()); } else { final Chunker chunker = new Chunker(buf.readableBytes()); try { while (buf.readableBytes() > 0) { if (buf.readableBytes() >= MAX_CHUNK_SIZE) { out.add(chunker.nextChunk(buf.readSlice(MAX_CHUNK_SIZE))); } else { out.add(chunker.nextChunk(buf.readSlice(buf.readableBytes()))); } } } catch (Exception e) { LOG.error("Chunk encoder error", e); buf.release(); } } }
Example #28
Source File: ModbusRequestEncoder.java From modbus with Apache License 2.0 | 5 votes |
@Override public ByteBuf encode(ModbusPdu modbusPdu, ByteBuf buffer) throws EncoderException { try { switch (modbusPdu.getFunctionCode()) { case ReadCoils: return encodeReadCoils((ReadCoilsRequest) modbusPdu, buffer); case ReadDiscreteInputs: return encodeReadDiscreteInputs((ReadDiscreteInputsRequest) modbusPdu, buffer); case ReadHoldingRegisters: return encodeReadHoldingRegisters((ReadHoldingRegistersRequest) modbusPdu, buffer); case ReadInputRegisters: return encodeReadInputRegisters((ReadInputRegistersRequest) modbusPdu, buffer); case WriteSingleCoil: return encodeWriteSingleCoil((WriteSingleCoilRequest) modbusPdu, buffer); case WriteSingleRegister: return encodeWriteSingleRegister((WriteSingleRegisterRequest) modbusPdu, buffer); case WriteMultipleCoils: return encodeWriteMultipleCoils((WriteMultipleCoilsRequest) modbusPdu, buffer); case WriteMultipleRegisters: return encodeWriteMultipleRegisters((WriteMultipleRegistersRequest) modbusPdu, buffer); case MaskWriteRegister: return encodeMaskWriteRegister((MaskWriteRegisterRequest) modbusPdu, buffer); default: throw new EncoderException("FunctionCode not supported: " + modbusPdu.getFunctionCode()); } } finally { ReferenceCountUtil.release(modbusPdu); } }
Example #29
Source File: LengthFieldPrependerTest.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Test public void testAdjustedLengthLessThanZero() throws Exception { final EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldPrepender(4, -2)); try { ch.writeOutbound(msg); fail(EncoderException.class.getSimpleName() + " must be raised."); } catch (EncoderException e) { // Expected } }
Example #30
Source File: MinecraftProtocol.java From ServerListPlus with GNU General Public License v3.0 | 5 votes |
public static void writeString(ByteBuf buf, String s) { byte[] bytes = s.getBytes(StandardCharsets.UTF_8); if (bytes.length > Short.MAX_VALUE) { throw new EncoderException("String too big (was " + bytes.length + " bytes encoded, max " + Short.MAX_VALUE + ")"); } MinecraftProtocol.writeVarInt(buf, bytes.length); buf.writeBytes(bytes); }