本文将分享javax.websocket.DecodeException的实例源码的详细内容,并且还将对javasocketwriteerror进行详尽解释,此外,我们还将为大家带来关于com.dat
本文将分享javax.websocket.DecodeException的实例源码的详细内容,并且还将对java socket write error进行详尽解释,此外,我们还将为大家带来关于com.datastax.driver.core.exceptions.CodecNotFoundException的实例源码、io.netty.handler.codec.CodecException的实例源码、io.netty.handler.codec.DecoderException的实例源码、io.netty.handler.codec.EncoderException的实例源码的相关知识,希望对你有所帮助。
本文目录一览:- javax.websocket.DecodeException的实例源码(java socket write error)
- com.datastax.driver.core.exceptions.CodecNotFoundException的实例源码
- io.netty.handler.codec.CodecException的实例源码
- io.netty.handler.codec.DecoderException的实例源码
- io.netty.handler.codec.EncoderException的实例源码
javax.websocket.DecodeException的实例源码(java socket write error)
@Override protected Object decode(ByteBuffer message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Binary) { if (((Binary<?>) decoder).willDecode(message)) { return ((Binary<?>) decoder).decode(message); } } else { byte[] array = new byte[message.limit() - message.position()]; message.get(array); ByteArrayInputStream bais = new ByteArrayInputStream(array); try { return ((BinaryStream<?>) decoder).decode(bais); } catch (IOException ioe) { throw new DecodeException(message,sm.getString( "pojoMessageHandlerWhole.decodeIoFail"),ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,message); } // Handle full decoders for (Decoder decoder : decoders) { if (decoder instanceof Text) { if (((Text<?>) decoder).willDecode(message)) { return ((Text<?>) decoder).decode(message); } } else { StringReader r = new StringReader(message); try { return ((TextStream<?>) decoder).decode(r); } catch (IOException ioe) { throw new DecodeException(message,ioe); } } } return null; }
@Override protected Object decode(ByteBuffer message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Binary) { if (((Binary<?>) decoder).willDecode(message)) { return ((Binary<?>) decoder).decode(message); } } else { byte[] array = new byte[message.limit() - message.position()]; message.get(array); ByteArrayInputStream bais = new ByteArrayInputStream(array); try { return ((BinaryStream<?>) decoder).decode(bais); } catch (IOException ioe) { throw new DecodeException(message,ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,ioe); } } } return null; }
@Override protected Object decode(ByteBuffer message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Binary) { if (((Binary<?>) decoder).willDecode(message)) { return ((Binary<?>) decoder).decode(message); } } else { byte[] array = new byte[message.limit() - message.position()]; message.get(array); ByteArrayInputStream bais = new ByteArrayInputStream(array); try { return ((BinaryStream<?>) decoder).decode(bais); } catch (IOException ioe) { throw new DecodeException(message,sm.getString("pojoMessageHandlerWhole.decodeIoFail"),ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,ioe); } } } return null; }
private static Object[] buildArgs(PojoPathParam[] pathParams,Map<String,String> pathParameters,Session session,EndpointConfig config,Throwable throwable,CloseReason closeReason) throws DecodeException { Object[] result = new Object[pathParams.length]; for (int i = 0; i < pathParams.length; i++) { Class<?> type = pathParams[i].getType(); if (type.equals(Session.class)) { result[i] = session; } else if (type.equals(EndpointConfig.class)) { result[i] = config; } else if (type.equals(Throwable.class)) { result[i] = throwable; } else if (type.equals(CloseReason.class)) { result[i] = closeReason; } else { String name = pathParams[i].getName(); String value = pathParameters.get(name); try { result[i] = Util.coercetoType(type,value); } catch (Exception e) { throw new DecodeException(value,sm.getString("pojoMethodMapping.decodePathParamFail",value,type),e); } } } return result; }
@Test public void from_byteBuffer() throws IOException,DecodeException { final String input = "MESSAGE\ndestination:wonderland\nsubscription:a\ncontent-length:4\n\nbody\u0000"; final Frame frame; try (InputStream is = new ByteArrayInputStream(input.getBytes())) { frame = Encoding.from(ByteBuffer.wrap(input.getBytes(UTF_8))); } assertEquals(Command.MESSAGE,frame.command()); assertEquals(4,frame.headers().size()); // ensure header order is maintained final Iterator<Entry<Header,List<String>>> itr = frame.headers().entrySet().iterator(); final Entry<Header,List<String>> header2 = itr.next(); assertEquals("destination",header2.getKey().value()); assertEquals(1,header2.getValue().size()); assertEquals("wonderland",header2.getValue().get(0)); final Entry<Header,List<String>> header1 = itr.next(); assertEquals("subscription",header1.getKey().value()); assertEquals(1,header1.getValue().size()); assertEquals("a",header1.getValue().get(0)); assertEquals(ByteBuffer.wrap("body".getBytes(StandardCharsets.UTF_8)),frame.body().get()); }
/** * @see javax.websocket.Decoder.Text#decode(String) * @see javax.websocket.Decoder.Binary#decode(ByteBuffer) */ @SuppressWarnings("unchecked") public T decode(M message) throws DecodeException { try { return (T) getConversionService().convert(message,getMessageType(),getType()); } catch (ConversionException ex) { if (message instanceof String) { throw new DecodeException((String) message,"Unable to decode websocket message using ConversionService",ex); } if (message instanceof ByteBuffer) { throw new DecodeException((ByteBuffer) message,ex); } throw ex; } }
@Override public Message decode(String textMessage) throws DecodeException { Message msg = null; JsonObject obj = Json.createReader(new StringReader(textMessage)). readobject(); try { DecoderHelper helper = new DecoderHelper(obj); msg = helper.getMessage(); msg.init(obj); } catch (ApplicationException e) { logger.log(Level.SEVERE,e.getMessage(),e); } return msg; }
/** * Decodes the message * @param message * @return * @throws DecodeException */ @Override public AbstractCommand decode(String message) throws DecodeException { logger.log(Level.INFO,"Decoding: {0}",message); JsonObject struct; try (JsonReader rdr = Json.createReader(new StringReader(message))) { struct = rdr.readobject(); } String type = struct.getString("type"); CommandTypes cmdType = CommandTypes.valueOf(type); try { AbstractCommand cmd = (AbstractCommand)cmdType.getCommandClass().newInstance(); cmd.decode(struct); return cmd; } catch (InstantiationException | illegalaccessexception ex) { Logger.getLogger(CommandMessageDecoder.class.getName()).log(Level.SEVERE,null,ex); throw new DecodeException(message,"Could not be decoded - invalid type."); } }
@Test public void testReadyNoSavedRoom(@Mocked RoomMediator room) throws DecodeException { ClientMediator mediator = new ClientMediator(nexus,drain,userId,signedJwt); String msgTxt = "ready,{}"; RoutedMessage message = new RoutedMessage(msgTxt); System.out.println(message); new Expectations() {{ nexus.join(mediator,""); }}; mediator.ready(message); new Verifications() {{ nexus.join(mediator,""); times = 1; drain.send((RoutedMessage) any); times = 0; }}; }
@Test public void testReadyUserName(@Mocked RoomMediator room) throws DecodeException { ClientMediator mediator = new ClientMediator(nexus,{\"username\":\"TinyJamFilledMuffin\"}"; RoutedMessage message = new RoutedMessage(msgTxt); System.out.println(message); new Expectations() {{ nexus.join(mediator,""); times = 1; drain.send((RoutedMessage) any); times = 0; }}; }
@Test public void testReadyZeroBookmark(@Mocked RoomMediator room) throws DecodeException { ClientMediator mediator = new ClientMediator(nexus,{\"bookmark\":0}"; RoutedMessage message = new RoutedMessage(msgTxt); System.out.println(message); new Expectations() {{ nexus.join(mediator,"0"); }}; mediator.ready(message); new Verifications() {{ nexus.join(mediator,"0"); times = 1; drain.send((RoutedMessage) any); times = 0; }}; }
@Test public void testReadySavedRoom(@Mocked RoomMediator room) throws DecodeException { ClientMediator mediator = new ClientMediator(nexus,{\"roomId\": \"roomId\",\"bookmark\": \"id\"}"; RoutedMessage message = new RoutedMessage(msgTxt); System.out.println(message); new Expectations() {{ nexus.join(mediator,roomId,"id"); }}; mediator.ready(message); new Verifications() {{ nexus.join(mediator,"id"); times = 1; drain.send((RoutedMessage) any); times = 0; }}; }
@Override public WebSocketMessage decode(ByteBuffer buffer) throws DecodeException { try { MessageProtos.Message decMsg = MessageProtos.Message.parseFrom(buffer.array()); WebSocketMessage msg = new WebSocketMessage() .withEvent(decMsg.getEvent()) .withChannel(decMsg.getChannel()) .withFrom(decMsg.getFrom()) .withId(decMsg.getId()) .withPayload(decMsg.getData().toByteArray()); return msg; } catch (IOException e) { throw new DecodeException(buffer,"Error parsing buffer.",e); } }
@Test public void shouldParseBasicObject() throws DecodeException { // given String validJson = "{'from' : 'Alice',"// + "'to' : 'Bob',"// + "'signal' : 'join',"// + "'content' : 'something'}"; // when Message result = decoder.decode(validJson); // then assertNotNull(result); assertthat(result.getFrom(),is("Alice")); assertthat(result.getTo(),is("Bob")); assertthat(result.getSignal(),is("join")); assertthat(result.getContent(),is("something")); }
@Test public void shouldParseAlmostemptyObject() throws DecodeException { // given String validJson = "{'signal' : 'join',is(EMPTY)); assertthat(result.getTo(),is(EMPTY)); assertthat(result.getSignal(),is("something")); }
@Test public void shouldParseRequestWithDoubleQuotes() throws DecodeException { // given String validJson = "{'from' : 'Alice',"// + "'content' : 'something',"// + "'parameters' : {'param1' : 'value1'}}".replace("'","\""); // when Message result = decoder.decode(validJson); // then assertNotNull(result); assertthat(result.getFrom(),is("something")); }
@Override protected Object decode(ByteBuffer message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Binary) { if (((Binary<?>) decoder).willDecode(message)) { return ((Binary<?>) decoder).decode(message); } } else { byte[] array = new byte[message.limit() - message.position()]; message.get(array); ByteArrayInputStream bais = new ByteArrayInputStream(array); try { return ((BinaryStream<?>) decoder).decode(bais); } catch (IOException ioe) { throw new DecodeException(message,ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,ioe); } } } return null; }
@Override protected Object decode(ByteBuffer message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Binary) { if (((Binary<?>) decoder).willDecode(message)) { return ((Binary<?>) decoder).decode(message); } } else { byte[] array = new byte[message.limit() - message.position()]; message.get(array); ByteArrayInputStream bais = new ByteArrayInputStream(array); try { return ((BinaryStream<?>) decoder).decode(bais); } catch (IOException ioe) { throw new DecodeException(message,ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coercetoType(primitiveType,ioe); } } } return null; }
@Override public Message decode(String string) throws DecodeException { Message msg = null; if (willDecode(string)) { switch (messageMap.get("type")) { case "join": msg = new JoinMessage(messageMap.get("name")); break; case "chat": msg = new ChatMessage(messageMap.get("name"),messageMap.get("target"),messageMap.get("message")); } } else { throw new DecodeException(string,"[Message] Can't decode."); } return msg; }
private static Object[] buildArgs(PojoPathParam[] pathParams,CloseReason closeReason) throws DecodeException { Object[] result = new Object[pathParams.length]; for (int i = 0; i < pathParams.length; i++) { Class<?> type = pathParams[i].getType(); if (type.equals(Session.class)) { result[i] = session; } else if (type.equals(EndpointConfig.class)) { result[i] = config; } else if (type.equals(Throwable.class)) { result[i] = throwable; } else if (type.equals(CloseReason.class)) { result[i] = closeReason; } else { String name = pathParams[i].getName(); String value = pathParameters.get(name); try { result[i] = Util.coercetoType(type,sm.getString( "pojoMethodMapping.decodePathParamFail",e); } } } return result; }
@Override public MsgByte decode(ByteBuffer bb) throws DecodeException { MsgByte result = new MsgByte(); byte[] data = new byte[bb.limit() - bb.position()]; bb.get(data); result.setData(data); return result; }
@Override public List<String> decode(String str) throws DecodeException { List<String> lst = new ArrayList<String>(1); str = str.substring(1,str.length()-1); String[] strings = str.split(","); for (String t : strings){ lst.add(t); } return lst; }
public Message decode(String incomingMessage) throws DecodeException { System.out.println("\n=============== Check the received string from client ===============\n" + incomingMessage + "\n---------------------------------------------------"); Message message = new Message().setJson(incomingMessage); // message.setJson(incommingMessage); return message; }
private static Object[] buildArgs(PojoPathParam[] pathParams,e); } } } return result; }
@Override public MsgByte decode(ByteBuffer bb) throws DecodeException { MsgByte result = new MsgByte(); byte[] data = new byte[bb.limit() - bb.position()]; bb.get(data); result.setData(data); return result; }
@Override public List<String> decode(String str) throws DecodeException { List<String> lst = new ArrayList<String>(1); str = str.substring(1,"); for (String t : strings){ lst.add(t); } return lst; }
@Override public JsonType decode(ByteBuffer bytes) throws DecodeException { try { return objectMapper.readValue(bytes.array(),JsonType.class); } catch (IOException e) { throw new DecodeException(bytes,"Could not parse input string. Expected a Json message.",e); } }
@Override public MeetupRSVP decode(String s) throws DecodeException { MeetupRSVP meetupRSVP = null; try { meetupRSVP = mapper.readValue(s,MeetupRSVP.class); } catch (IOException ex) { Logger.getLogger(MeetupRSVPJSONDecoder.class.getName()).log(Level.SEVERE,ex); } return meetupRSVP; }
@Override public Frame decode(ByteBuffer bytes) throws DecodeException { try { return from(bytes); } catch (IOException | AssertionError e) { throw new DecodeException(bytes,e); } }
@Override public Frame decode(String s) throws DecodeException { try { return from(UTF_8.encode(s)); } catch (IOException | AssertionError e) { throw new DecodeException(s,"Unable to decode. \"" + s + "\" : " + e.getMessage(),e); } }
@Test public void decode_byteBuffer() throws DecodeException,IOException { final String input = "MESSAGE\ndestination:wonderland\nsubscription:a\ncontent-length:4\n\nbody\u0000"; final Frame frame; try (InputStream is = new ByteArrayInputStream(input.getBytes())) { frame = binary.decode(ByteBuffer.wrap(input.getBytes(UTF_8))); } assertEquals(Command.MESSAGE,frame.command()); }
@Test public void from_byteBuffer_leadingEoL() throws IOException,DecodeException { final String input = "\nMESSAGE\ndestination:wonderland\nsubscription:a\ncontent-length:4\n\nbody\u0000"; final Frame frame; try (InputStream is = new ByteArrayInputStream(input.getBytes())) { frame = Encoding.from(ByteBuffer.wrap(input.getBytes(UTF_8))); } assertEquals(Command.MESSAGE,frame.headers().size()); }
@Test public void Encoding_windowSEOL() throws IOException,DecodeException { final String input = "MESSAGE\r\ndestination:wonderland\r\nsubscription:a\r\ncontent-length:4\r\n\r\nbody\u0000"; final Frame frame; try (InputStream is = new ByteArrayInputStream(input.getBytes())) { frame = Encoding.from(ByteBuffer.wrap(input.getBytes(UTF_8))); } assertEquals(Command.MESSAGE,frame.headers().size()); }
com.datastax.driver.core.exceptions.CodecNotFoundException的实例源码
private void registerCodecIfNotFound(CodecRegistry registry,TypeCodec<?> codec) { try { registry.codecFor(codec.getCqlType(),codec.getJavaType()); } catch (CodecNotFoundException e) { registry.register(codec); } }
private void registerCodecIfNotFound(CodecRegistry registry,codec.getJavaType()); } catch (CodecNotFoundException e) { registry.register(codec); } }
@SuppressWarnings("cast") public void setInt(int parameterIndex,int integer) throws sqlException { checkNotClosed(); checkIndex(parameterIndex); //bindValues.put(parameterIndex,JdbcInt32.instance.decompose(integer)); try{ this.statement.setInt(parameterIndex-1,integer); }catch(CodecNotFoundException e){ if(e.getMessage().contains("Codec not found for requested operation: [varint <-> java.lang.Integer]")){ this.statement.setvarint(parameterIndex-1,BigInteger.valueOf((long)integer)); } } }
/** * Convert a Record into a fully-bound statement. */ @SuppressWarnings("unchecked") private BoundStatement recordToBoundStatement(Record record) throws StageException { ImmutableList.Builder<Object> values = new ImmutableList.Builder<>(); SortedSet<String> columnspresent = Sets.newTreeSet(columnmappings.keySet()); for (Map.Entry<String,String> mapping : columnmappings.entrySet()) { String columnName = mapping.getKey(); String fieldpath = mapping.getValue(); // If we're missing fields,skip them. // If a field is present,but null,also remove it from columnspresent since we can't write nulls. if (!record.has(fieldpath) || record.get(fieldpath).getValue() == null) { columnspresent.remove(columnName); continue; } final Object value = record.get(fieldpath).getValue(); // Special cases for handling SDC Lists and Maps,// basically unpacking them into raw types. if (value instanceof List) { List<Object> unpackedList = new ArrayList<>(); for (Field item : (List<Field>) value) { unpackedList.add(item.getValue()); } values.add(unpackedList); } else if (value instanceof Map) { Map<Object,Object> unpackedMap = new HashMap<>(); for (Map.Entry<String,Field> entry : ((Map<String,Field>) value).entrySet()) { unpackedMap.put(entry.getKey(),entry.getValue().getValue()); } values.add(unpackedMap); } else { values.add(value); } } PreparedStatement stmt = statementCache.getUnchecked(columnspresent); // .toArray required to pass in a list to a varargs method. Object[] valuesArray = values.build().toArray(); BoundStatement boundStmt = null; try { boundStmt = stmt.bind(valuesArray); } catch (CodecNotFoundException | InvalidTypeException | NullPointerException e) { // NPE can occur if one of the values is a collection type with a null value inside it. Thus,it's a record // error. Note that this runs the risk of mistakenly treating a bug as a record error. // CodecNotFound is caused when there is no type conversion deFinition available from the provided type // to the target type. errorRecordHandler.onError( new OnRecordErrorException( record,Errors.CASSANDRA_06,record.getHeader().getSourceId(),e.toString(),e ) ); } return boundStmt; }
io.netty.handler.codec.CodecException的实例源码
private void processtRAILER ( final ChannelHandlerContext ctx,final byte b,final ByteBuf msg ) { if ( b != Constants.LF ) { throw new CodecException ( String.format ( "Expected trailer byte (LF) but found 0x%02X: Remaining buffer: %s",b,ByteBufUtil.hexDump ( msg,msg.readerIndex (),msg.readableBytes () ) ) ); } final int length = ctx.attr ( ATTR_EXPECTED_LENGTH ).get (); final long txnr = Long.parseLong ( ctx.attr ( ATTR_TXNR_BUFFER ).get ().toString ( TXNR_CHARSET ) ); final String command = ctx.attr ( ATTR_COMMAND_BUFFER ).get ().toString ( COMMAND_CHARSET ); final ByteBuf data = ctx.attr ( ATTR_DATA_BUFFER ).get ().readSlice ( length ); final Frame frame = new Frame ( txnr,command,data ); ctx.fireChannelRead ( frame ); ctx.attr ( ATTR_STATE ).set ( State.TXNR ); ctx.attr ( ATTR_TXNR_BUFFER ).get ().clear (); ctx.attr ( ATTR_COMMAND_BUFFER ).get ().clear (); ctx.attr ( ATTR_LENGTH_BUFFER ).get ().clear (); ctx.attr ( ATTR_DATA_BUFFER ).get ().clear (); }
protected void processMessage ( final ChannelHandlerContext ctx,final ByteBuf msg ) { if ( msg.readByte () != PRI_START ) { throw new CodecException ( "PRI start not found" ); } final int prival = decodePrival ( msg ); final Severity severity = Severity.values ()[prival % 8]; final Facility facility = Facility.values ()[prival / 8]; final Calendar timestamp = this.timestampParser.parseTimestamp ( msg ); final String hostname = decodeHostname ( msg ); final String[] process = decodeProcess ( msg ); final String processName = process[0]; final Long processId = process.length > 1 ? Long.parseLong ( process[1] ) : null; final String message = decodeMessage ( msg ); ctx.fireChannelRead ( new SyslogMessage ( facility,severity,timestamp,hostname,processName,processId,message ) ); }
private String[] decodeProcess ( final ByteBuf msg ) { // split by colon final int spaceIndex = msg.bytesBefore ( COLON ); if ( spaceIndex < 0 ) { throw new CodecException ( "Unable to find process name" ); } final String process = msg.readSlice ( spaceIndex ).toString ( StandardCharsets.US_ASCII ); msg.skipBytes ( 1 ); // COLON if ( msg.isReadable () ) { msg.skipBytes ( 1 ); // SPACE } final Matcher m = PROCESS_PATTERN.matcher ( process ); if ( m.matches () ) { return new String[] { m.group ( 1 ),m.group ( 2 ) }; } return new String[] { process }; }
private int decodePrival ( final ByteBuf msg ) { final ByteBuffer privalBuffer = ByteBuffer.wrap ( new byte[3] ); byte b; do { b = msg.readByte (); if ( b == PRI_END ) { break; } if ( !privalBuffer.hasRemaining () ) { throw new CodecException ( "PRI value must be <=3 bytes" ); } privalBuffer.put ( b ); } while ( true ); privalBuffer.flip (); final int prival = Integer.parseInt ( StandardCharsets.US_ASCII.decode ( privalBuffer ).toString () ); return prival; }
private static void printAggregatedRedisResponse(RedisMessage msg) { if (msg instanceof SimpleStringRedisMessage) { System.out.println(((SimpleStringRedisMessage) msg).content()); } else if (msg instanceof ErrorRedisMessage) { System.out.println(((ErrorRedisMessage) msg).content()); } else if (msg instanceof IntegerRedisMessage) { System.out.println(((IntegerRedisMessage) msg).value()); } else if (msg instanceof FullBulkStringRedisMessage) { System.out.println(getString((FullBulkStringRedisMessage) msg)); } else if (msg instanceof ArrayRedisMessage) { for (RedisMessage child : ((ArrayRedisMessage) msg).children()) { printAggregatedRedisResponse(child); } } else { throw new CodecException("unkNown message type: " + msg); } }
@Override public ByteBuffer encode(CodecContext context,Message message) throws CodecException { final ByteBuffer buf = context.byteBufAlloc().buffer(); final String channel; final ByteBuffer content; if (message instanceof MessagePlayInOutChannelPayload) { final MessagePlayInOutChannelPayload message1 = (MessagePlayInOutChannelPayload) message; content = message1.getContent(); channel = message1.getChannel(); } else if (message instanceof MessagePlayInOutRegisterChannels) { content = encodeChannels(((MessagePlayInOutRegisterChannels) message).getChannels()); channel = "REGISTER"; } else if (message instanceof MessagePlayInOutUnregisterChannels) { content = encodeChannels(((MessagePlayInOutUnregisterChannels) message).getChannels()); channel = "UNREGISTER"; } else { final MessageResult result = encode0(context,message); channel = result.channel; content = result.byteBuf; } buf.writeString(channel); buf.writeBytes(content); return buf; }
@Override public void process(CodecContext context,MessageForgeHandshakeOutRegistryData message,List<Message> output) throws CodecException { final Iterator<Entry> it = message.getEntries().iterator(); if (!it.hasNext()) { throw new CodecException("There must be at least one entry present!"); } while (it.hasNext()) { final Entry entry = it.next(); final ByteBuffer buf = context.byteBufAlloc().buffer(); buf.writeByte((byte) CodecPlayInOutCustomPayload.FML_HANDSHAKE_REGISTRY_DATA); buf.writeBoolean(it.hasNext()); buf.writeString(entry.getName()); final Map<String,Integer> ids = entry.getIds(); buf.writeVarInt(ids.size()); for (Map.Entry<String,Integer> en : ids.entrySet()) { buf.writeString(en.getKey()); buf.writeVarInt(en.getValue()); } final List<String> substitutions = entry.getSubstitutions(); buf.writeVarInt(substitutions.size()); substitutions.forEach(buf::writeString); output.add(new MessagePlayInOutChannelPayload("FML|HS",buf)); } }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutSpawnParticle message) throws CodecException { Vector3f position = message.getPosition(); Vector3f offset = message.getoffset(); int[] extra = message.getExtra(); ByteBuffer buf = context.byteBufAlloc().buffer(BASE_LENGTH); buf.writeInteger(message.getParticleId()); buf.writeBoolean(message.isLongdistance()); buf.writeFloat(position.getX()); buf.writeFloat(position.getY()); buf.writeFloat(position.getZ()); buf.writeFloat(offset.getX()); buf.writeFloat(offset.getY()); buf.writeFloat(offset.getZ()); buf.writeFloat(message.getData()); buf.writeInteger(message.getCount()); for (int value : extra) { buf.writeVarInt(value); } return buf; }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutPlayerJoinGame message) throws CodecException { context.getChannel().attr(PLAYER_ENTITY_ID).set(message.getEntityId()); final ByteBuffer buf = context.byteBufAlloc().buffer(); buf.writeInteger(message.getEntityId()); byte gameMode = (byte) message.getGameMode().getInternalId(); if (message.isHardcore()) { gameMode |= 0x8; } buf.writeByte(gameMode); buf.writeInteger(message.getDimensionType().getInternalId()); buf.writeByte((byte) message.getDifficulty().getInternalId()); buf.writeByte((byte) Math.min(message.getPlayerListSize(),255)); buf.writeString(message.isLowHorizon() ? "flat" : "default"); buf.writeBoolean(message.getReducedDebug()); return buf; }
@Nullable @Override public DataView readLimitedDataView(int maximumDepth,int maxBytes) { final int index = this.buf.readerIndex(); if (this.buf.readByte() == 0) { return null; } this.buf.readerIndex(index); try { try (NbtDataContainerInputStream input = new NbtDataContainerInputStream( new LimitInputStream(new ByteBufInputStream(this.buf),maxBytes),false,maximumDepth)) { return input.read(); } } catch (IOException e) { throw new CodecException(e); } }
@Override public void process(CodecContext context,MessagePlayOutTabListEntries message,List<Message> output) throws CodecException { final Multimap<Class<?>,Entry> entriesByType = HashMultimap.create(); for (Entry entry : message.getEntries()) { entriesByType.put(entry.getClass(),entry); } if (entriesByType.isEmpty()) { return; } if (entriesByType.keySet().size() == 1) { output.add(message); } else { for (java.util.Map.Entry<Class<?>,Collection<Entry>> en : entriesByType.asMap().entrySet()) { output.add(new MessagePlayOutTabListEntries(en.getValue())); } } }
@Override public ByteBuffer encode(CodecContext context,MessageLoginoutEncryptionRequest message) throws CodecException { ByteBuffer buf = context.byteBufAlloc().buffer(); byte[] publicKey = message.getPublicKey(); byte[] verifyToken = message.getVerifyToken(); buf.writeString(message.getSessionId()); // Write the public key buf.writeByteArray(publicKey); // Write the verify token buf.writeByteArray(verifyToken); return buf; }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutTitle message) throws CodecException { final ByteBuffer buf = context.byteBufAlloc().buffer(); if (message instanceof MessagePlayOutTitle.Clear) { buf.writeVarInt(CLEAR); } else if (message instanceof MessagePlayOutTitle.Reset) { buf.writeVarInt(RESET); } else if (message instanceof MessagePlayOutTitle.SetTitle) { buf.writeVarInt(SET_TITLE); buf.write(Types.LOCALIZED_TEXT,((MessagePlayOutTitle.SetTitle) message).getTitle()); } else if (message instanceof MessagePlayOutTitle.SetSubtitle) { buf.writeVarInt(SET_SUBTITLE); buf.write(Types.LOCALIZED_TEXT,((MessagePlayOutTitle.SetSubtitle) message).getTitle()); } else if (message instanceof MessagePlayOutTitle.SetActionbarTitle) { buf.writeVarInt(SET_ACTIONBAR_TITLE); buf.write(Types.LOCALIZED_TEXT,((MessagePlayOutTitle.SetActionbarTitle) message).getTitle()); } else { final MessagePlayOutTitle.SetTimes message0 = (MessagePlayOutTitle.SetTimes) message; buf.writeVarInt(SET_TIMES); buf.writeInteger(message0.getFadeIn()); buf.writeInteger(message0.getStay()); buf.writeInteger(message0.getFadeOut()); } return buf; }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutUnlockRecipes message) throws CodecException { final ByteBuffer buf = context.byteBufAlloc().buffer(); if (message instanceof MessagePlayOutUnlockRecipes.Remove) { buf.writeVarInt((short) 2); } else if (message instanceof MessagePlayOutUnlockRecipes.Add) { buf.writeVarInt((short) 1); } else if (message instanceof MessagePlayOutUnlockRecipes.Init) { buf.writeVarInt((short) 0); } else { throw new EncoderException(); } buf.writeBoolean(message.hasOpenCraftingBook()); buf.writeBoolean(message.hasCraftingFilter()); IntList recipeIds = message.getRecipeIds(); buf.writeVarInt(recipeIds.size()); recipeIds.forEach(buf::writeVarInt); if (message instanceof MessagePlayOutUnlockRecipes.Init) { recipeIds = ((MessagePlayOutUnlockRecipes.Init) message).getRecipeIdsToBedisplayed(); buf.writeVarInt(recipeIds.size()); recipeIds.forEach(buf::writeVarInt); } return buf; }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutTabListHeaderAndFooter message) throws CodecException { ByteBuffer buf = context.byteBufAlloc().buffer(); Text header = message.getHeader(); Text footer = message.getFooter(); if (header != null) { buf.write(Types.TEXT,header); } else { buf.writeString(EMPTY_TEXT); } if (footer != null) { buf.write(Types.TEXT,footer); } else { buf.writeString(EMPTY_TEXT); } return buf; }
@Override public ByteBuffer encode(CodecContext context,Message message) throws CodecException { final int entityId; final int action; if (message instanceof MessagePlayOutSetReducedDebug) { entityId = context.getChannel().attr(CodecPlayOutPlayerJoinGame.PLAYER_ENTITY_ID).get(); action = ((MessagePlayOutSetReducedDebug) message).isReduced() ? 22 : 23; } else if (message instanceof MessagePlayOutSetopLevel) { entityId = context.getChannel().attr(CodecPlayOutPlayerJoinGame.PLAYER_ENTITY_ID).get(); action = 24 + Math.max(0,Math.min(4,((MessagePlayOutSetopLevel) message).getopLevel())); } else if (message instanceof MessagePlayOutEntityStatus) { entityId = ((MessagePlayOutEntityStatus) message).getEntityId(); action = ((MessagePlayOutEntityStatus) message).getStatus(); } else if (message instanceof MessagePlayInOutFinishUsingItem) { entityId = context.getChannel().attr(CodecPlayOutPlayerJoinGame.PLAYER_ENTITY_ID).get(); action = 9; } else { throw new CodecException("Unsupported message type: " + message.getClass().getName()); } return context.byteBufAlloc().buffer(LENGTH).writeInteger(entityId).writeByte((byte) action); }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutWorldTime message) throws CodecException { final ByteBuffer buf = context.byteBufAlloc().buffer(LENGTH); // The time also uses a negative tag long time = message.getTime(); while (time < 0) { time += TimeUniverse.TICKS_IN_A_DAY; } time %= TimeUniverse.TICKS_IN_A_DAY; time += message.getMoonPhase().ordinal() * TimeUniverse.TICKS_IN_A_DAY; if (!message.getEnabled()) { time = time == 0 ? -1 : -time; } buf.writeLong(message.getAge()); buf.writeLong(time); return buf; }
@Override public MessagePlayInClientSettings decode(CodecContext context,ByteBuffer buf) throws CodecException { // The locale is lowercase,this is not allowed final String localeName = buf.readLimitedString(16); final String[] parts = localeName.split("_",3); Locale locale; if (parts.length == 3) { locale = new Locale(parts[0].toLowerCase(),parts[1].toupperCase(),parts[2]); } else if (parts.length == 2) { locale = new Locale(parts[0].toLowerCase(),parts[1].toupperCase()); } else { locale = new Locale(parts[0]); } final int viewdistance = buf.readByte(); final ChatVisibility visibility = ChatVisibilityRegistryModule.get().getByInternalId(buf.readByte()).get(); final boolean enableColors = buf.readBoolean(); final int skinPartsBitPattern = buf.readByte() & 0xff; final HandPreference dominantHand = buf.readVarInt() == 1 ? HandPreferences.RIGHT : HandPreferences.LEFT; return new MessagePlayInClientSettings(locale,viewdistance,visibility,dominantHand,enableColors,skinPartsBitPattern); }
@Override public Message decode(CodecContext context,ByteBuffer buf) throws CodecException { final String channel = buf.readLimitedString(LanternChannelRegistrar.MAX_NAME_LENGTH); final int length = buf.available(); if (length > Short.MAX_VALUE) { throw new DecoderException("CustomPayload messages may not be longer then " + Short.MAX_VALUE + " bytes"); } final ByteBuffer content = buf.slice(); final Message message = decode0(context,content,channel); if (content.available() > 0) { Lantern.getLogger().warn("Trailing bytes {}b after decoding with custom payload message codec {} with channel {}!\n{}",content.available(),getClass().getName(),channel,message); } // Skip all the bytes,we already processed them buf.setReadindex(buf.readerIndex() + buf.available()); return message; }
@Test public void testFailsOnIncompleteChunkedResponse() { HttpClientCodec codec = new HttpClientCodec(4096,8192,true); EmbeddedChannel ch = new EmbeddedChannel(codec); ch.writeOutbound(releaseLater( new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET,"http://localhost/"))); assertNotNull(releaseLater(ch.readOutbound())); assertNull(ch.readInbound()); ch.writeInbound(releaseLater( Unpooled.copiedBuffer(INCOMPLETE_CHUNKED_RESPONSE,CharsetUtil.ISO_8859_1))); assertthat(releaseLater(ch.readInbound()),instanceOf(HttpResponse.class)); assertthat(releaseLater(ch.readInbound()),instanceOf(HttpContent.class)); // Chunk 'first' assertthat(releaseLater(ch.readInbound()),instanceOf(HttpContent.class)); // Chunk 'second' assertNull(ch.readInbound()); try { ch.finish(); fail(); } catch (CodecException e) { assertTrue(e instanceof PrematureChannelClosureException); } }
private void processtXNR ( final ChannelHandlerContext ctx,final byte b ) { if ( b == Constants.SP ) { ctx.attr ( ATTR_STATE ).set ( State.COMMAND ); } else { if ( b < 0x30 || b > 0x39 ) { throw new CodecException ( String.format ( "Invalid character found: 0x%1$02x (%1$s)",(char)b ) ); } ctx.attr ( ATTR_TXNR_BUFFER ).get ().writeByte ( b ); } }
private String decodeHostname ( final ByteBuf msg ) { // split by first space final int spaceIndex = msg.bytesBefore ( Constants.SP ); if ( spaceIndex < 0 ) { throw new CodecException ( "Unable to find hostname" ); } final String hostname = msg.readSlice ( spaceIndex ).toString ( StandardCharsets.US_ASCII ); msg.skipBytes ( 1 ); // SPACE return hostname; }
@Override protected MessageResult encode0(CodecContext context,Message message) throws CodecException { if (message instanceof MessageForgeHandshakeInOutAck) { return new MessageResult("FML|HS",context.byteBufAlloc() .buffer(2) .writeByte((byte) FML_HANDSHAKE_ACK) // Only the server state should be send to the client .writeByte((byte) ((ForgeServerHandshakePhase) ((MessageForgeHandshakeInOutAck) message).getPhase()).ordinal())); } else if (message instanceof MessageForgeHandshakeInOutHello) { return new MessageResult("FML|HS",context.byteBufAlloc() .buffer(2) .writeByte((byte) FML_HANDSHAKE_SERVER_HELLO) .writeByte((byte) FORGE_PROTOCOL)); } else if (message instanceof MessageForgeHandshakeInOutModList) { Map<String,String> entries = ((MessageForgeHandshakeInOutModList) message).getEntries(); ByteBuffer buf = context.byteBufAlloc().buffer(); buf.writeByte((byte) FML_HANDSHAKE_MOD_LIST); buf.writeVarInt(entries.size()); for (Map.Entry<String,String> en : entries.entrySet()) { buf.writeString(en.getKey()); buf.writeString(en.getValue()); } return new MessageResult("FML|HS",buf); } else if (message instanceof MessageForgeHandshakeOutReset) { return new MessageResult("FML|HS",context.byteBufAlloc() .buffer(1).writeByte((byte) FML_HANDSHAKE_RESET)); } throw new EncoderException("Unsupported message type: " + message); }
@Override protected Message decode0(CodecContext context,String channel,ByteBuffer content) throws CodecException { if ("FML|HS".equals(channel)) { int type = content.readByte(); switch (type) { case FML_HANDSHAKE_RESET: // server -> client message: ignore break; case FML_HANDSHAKE_ACK: ForgeClientHandshakePhase phase = ForgeClientHandshakePhase.values()[content.readByte()]; return new MessageForgeHandshakeInOutAck(phase); case FML_HANDSHAKE_SERVER_HELLO: // server -> client message: ignore break; case FML_HANDSHAKE_CLIENT_HELLO: content.readByte(); // The forge protocol version on the client return new MessageForgeHandshakeInOutHello(); case FML_HANDSHAKE_MOD_LIST: int size = content.readVarInt(); Map<String,String> entries = Maps.newHashMapWithExpectedSize(size); for (int i = 0; i < size; i++) { entries.put(content.readString(),content.readString()); } return new MessageForgeHandshakeInOutModList(entries); case FML_HANDSHAKE_REGISTRY_DATA: // server -> client message: ignore break; default: throw new DecoderException("UnkNown forge handshake message with opcode: " + type); } throw new DecoderException("Received an unexpected forge message with opcode: " + type); } else { throw new DecoderException("Received an unexpected message with channel: " + channel); } }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutSelectAdvancementTree message) throws CodecException { final ByteBuffer buf = context.byteBufAlloc().buffer(); final String id = message.getId(); buf.writeBoolean(id != null); if (id != null) { buf.writeString(id); } return buf; }
@Override public void write(ByteBuffer buf,Vector3i object) throws CodecException { long x = object.getX(); long y = object.getY(); long z = object.getZ(); buf.writeLong((x & 0x3ffffff) << 38 | (y & 0xfff) << 26 | (z & 0x3ffffff)); }
@Override public Vector3i read(ByteBuffer buf) throws CodecException { long value = buf.readLong(); int x = (int) (value >> 38); int y = (int) (value << 26 >> 52); int z = (int) (value << 38 >> 38); return new Vector3i(x,y,z); }
@Override public void write(ByteBuffer buf,Vector3f object) throws CodecException { buf.ensureWritable(VECTOR_3_F_LENGTH); buf.writeFloat(object.getX()); buf.writeFloat(object.getY()); buf.writeFloat(object.getZ()); }
@Override public Vector3f read(ByteBuffer buf) throws CodecException { float x = buf.readFloat(); float y = buf.readFloat(); float z = buf.readFloat(); return new Vector3f(x,z); }
@Override public LocalizedText read(ByteBuffer buf) throws CodecException { try { return new LocalizedText(TEXT_GSON.fromJson(buf.readString(),Text.class),JsonTextTranslatableSerializer.getCurrentLocale()); } catch (JsonSyntaxException e) { throw new DecoderException(e); } }
@Override public void write(ByteBuffer buf,@Nullable ItemStack object) throws CodecException { if (object == null) { buf.write(Types.RAW_ITEM_STACK,null); } else { final DataView dataView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED); this.store.serialize((LanternItemStack) object,dataView); buf.write(Types.RAW_ITEM_STACK,new RawItemStack(ItemRegistryModule.get().getInternalId(object.getType()),dataView.getShort(ItemStackStore.DATA).orElse((short) 0),object.getQuantity(),dataView.getView(ItemStackStore.TAG).orElse(null))); } }
@Override public void write(ByteBuffer buf,RawItemStack object) throws CodecException { if (object == null) { buf.writeShort((short) -1); } else { buf.writeShort((short) object.getItemType()); buf.writeByte((byte) object.getAmount()); buf.writeShort((short) object.getData()); buf.writeDataView(object.getDataView()); } }
@Override public MessagePlayInPlayerAbilities decode(CodecContext context,ByteBuffer buf) throws CodecException { boolean flying = (buf.readByte() & 0x02) != 0; buf.readFloat(); buf.readFloat(); return new MessagePlayInPlayerAbilities(flying); }
@Override protected void onTooBigFrame(EmbeddedChannel ch,ByteBuf input) { try { ch.writeInbound(input); fail(); } catch (CodecException e) { assertEquals(TooLongFrameException.class,e.getClass()); } }
@Override public MessagePlayInClickRecipe decode(CodecContext context,ByteBuffer buf) throws CodecException { final int windowId = buf.readByte() & 0xff; final int recipe = buf.readVarInt(); final boolean shift = buf.readBoolean(); return new MessagePlayInClickRecipe(windowId,recipe,shift); }
@Override public ByteBuffer encode(CodecContext context,MessageLoginoutSuccess message) throws CodecException { ByteBuffer buf = context.byteBufAlloc().buffer(); buf.writeString(message.getUniqueId().toString()); buf.writeString(message.getUsername()); return buf; }
@Override public MessageHandshakeIn decode(CodecContext context,ByteBuffer buf) throws CodecException { int protocol = buf.readVarInt(); String hostname; if (Lantern.getGame().getGlobalConfig().getProxyType() != ProxyType.NONE) { hostname = buf.readString(); } else { hostname = buf.readLimitedString(255); } short port = buf.readShort(); int state = buf.readVarInt(); return new MessageHandshakeIn(state,port,protocol); }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutEntityCollectItem message) throws CodecException { ByteBuffer buf = context.byteBufAlloc().buffer(); buf.writeVarInt(message.getCollectedId()); buf.writeVarInt(message.getCollectorId()); buf.writeVarInt(message.getCollectItemCount()); return buf; }
@Override public boolean acceptInboundMessage(Object msg) throws Exception { if (msg instanceof SctpMessage) { SctpMessage sctpMsg = (SctpMessage) msg; if (sctpMsg.isComplete()) { return true; } throw new CodecException(String.format("Received SctpMessage is not complete,please add %s in " + "the pipeline before this handler",SctpMessageCompletionHandler.class.getSimpleName())); } else { return false; } }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutTeams message) throws CodecException { final ByteBuffer buf = context.byteBufAlloc().buffer(); buf.writeString(message.getTeamName()); if (message instanceof MessagePlayOutTeams.CreateOrUpdate) { buf.writeByte((byte) (message instanceof MessagePlayOutTeams.Create ? 0 : 2)); final MessagePlayOutTeams.CreateOrUpdate message1 = (MessagePlayOutTeams.CreateOrUpdate) message; buf.writeString(message1.getdisplayName()); buf.writeString(message1.getPrefix()); buf.writeString(message1.getSuffix()); int flags = 0; if (message1.getFriendlyFire()) { flags |= 0x01; } if (message1.getSeeFriendlyInvisibles()) { flags |= 0x02; } buf.writeByte((byte) flags); buf.writeString(message1.getNaMetagVisibility().getId()); buf.writeString(message1.getCollisionRule().getName()); final TextColor c = message1.getColor(); buf.writeByte((byte) (c == TextColors.NONE || c == TextColors.RESET ? -1 : FormattingCodeTextSerializer.FORMATS_TO_CODE.getChar(c))); } else { buf.writeByte((byte) (message instanceof MessagePlayOutTeams.Remove ? 1 : message instanceof MessagePlayOutTeams.Addplayers ? 3 : 4)); } if (message instanceof MessagePlayOutTeams.Players) { final List<String> players = ((MessagePlayOutTeams.Players) message).getPlayers(); buf.writeVarInt(players.size()); players.forEach(buf::writeString); } return buf; }
io.netty.handler.codec.DecoderException的实例源码
@Override protected void decode(ChannelHandlerContext ctx,ByteBuf in,List<Object> out) throws Exception { if (in.readableBytes() <= 0) return; Packet packet = null; byte packetId = in.readByte(); if (packetId < 0) { in.clear(); throw new DecoderException("WTF,why is the packet id lower than zero?!?! Id: " + packetId); } Class<? extends Packet> clazz = PacketManager.getInstance().getPacketClass(packetId); if (clazz != null) packet = clazz.newInstance(); if (packet == null) { throw new DecoderException("Cannot find packet id: " + packetId); } packet.decode(in); out.add(packet); }
private Function convertFunction ( final int functions ) { switch ( functions ) { case 0x03 | 4: return Function.STARTDT_ACT; case 0x03 | 8: return Function.STARTDT_CONFIRM; case 0x03 | 16: return Function.STOPDT_ACT; case 0x03 | 32: return Function.STOPDT_CONFIRM; case 0x03 | 64: return Function.TESTFR_ACT; case 0x03 | 128: return Function.TESTFR_CONFIRM; default: throw new DecoderException ( String.format ( "Invalid function codes for U-format (%02x)",functions ) ); } }
/** * Read string from buffer * * @param maxLength The slots length * @return The successful */ public String readString(int maxLength) { int i = this.readVarInt(); if(i > maxLength * 4 || i < 0) { throw new DecoderException("The received encoded string buffer length is not allowed!"); } else { ByteBuf part = buf.readBytes(i); String s = part.toString(Charsets.UTF_8); if(s.length() > maxLength) { throw new DecoderException("The received string length is longer than maximum allowed (" + i + " > " + maxLength + ")"); } else { return s; } } }
/** * Decodes the fixed header. It's one byte for the flags and then variable bytes for the remaining length. * * @param buffer the buffer to decode from * @return the fixed header */ private static MqttFixedHeader decodeFixedHeader(ByteBuf buffer) { short b1 = buffer.readUnsignedByte(); MqttMessageType messageType = MqttMessageType.valueOf(b1 >> 4); boolean dupFlag = (b1 & 0x08) == 0x08; int qosLevel = (b1 & 0x06) >> 1; boolean retain = (b1 & 0x01) != 0; int remainingLength = 0; int multiplier = 1; short digit; int loops = 0; do { digit = buffer.readUnsignedByte(); remainingLength += (digit & 127) * multiplier; multiplier *= 128; loops++; } while ((digit & 128) != 0 && loops < 4); // MQTT protocol limits Remaining Length to 4 bytes if (loops == 4 && (digit & 128) != 0) { throw new DecoderException("remaining length exceeds 4 digits (" + messageType + ')'); } return new MqttFixedHeader(messageType,dupFlag,MqttQoS.valueOf(qosLevel),retain,remainingLength); }
private static Result<MqttPublishVariableHeader> decodePublishVariableHeader( ByteBuf buffer,MqttFixedHeader mqttFixedHeader) { final Result<String> decodedTopic = decodeString(buffer); if (!isValidPublishTopicName(decodedTopic.value)) { throw new DecoderException("invalid publish topic name: " + decodedTopic.value + " (contains wildcards)"); } int numberOfBytesConsumed = decodedTopic.numberOfBytesConsumed; int messageId = -1; if (mqttFixedHeader.qosLevel().value() > 0) { final Result<Integer> decodedMessageId = decodeMessageId(buffer); messageId = decodedMessageId.value; numberOfBytesConsumed += decodedMessageId.numberOfBytesConsumed; } final MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(decodedTopic.value,messageId); return new Result<MqttPublishVariableHeader>(mqttPublishVariableHeader,numberOfBytesConsumed); }
/** * Decodes the specified region of the buffer into an unadjusted frame length. The default implementation is * capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer. Override this method to * decode the length field encoded differently. Note that this method must not modify the state of the specified * buffer (e.g. {@code readerIndex},{@code writerIndex},and the content of the buffer.) * * @throws DecoderException * if Failed to decode the specified region */ protected long getUnadjustedFrameLength(ByteBuf buf,int offset,int length,ByteOrder order) { buf = buf.order(order); long frameLength; switch (length) { case 1: frameLength = buf.getUnsignedByte(offset); break; case 2: frameLength = buf.getUnsignedShort(offset); break; case 3: frameLength = buf.getUnsignedMedium(offset); break; case 4: frameLength = buf.getUnsignedInt(offset); break; case 8: frameLength = buf.getLong(offset); break; default: throw new DecoderException( "unsupported lengthFieldLength: " + lengthFieldLength + " (expected: 1,2,3,4,or 8)"); } return frameLength; }
void initiateProtocolORSSl(String username,String password,String database,Handler<? super CommandResponse<Connection>> completionHandler) { ChannelPipeline pipeline = socket.channelHandlerContext().pipeline(); if (ssl) { Future<Void> upgradeFuture = Future.future(); upgradeFuture.setHandler(ar -> { if (ar.succeeded()) { initiateProtocol(username,password,database,completionHandler); } else { Throwable cause = ar.cause(); if (cause instanceof DecoderException) { DecoderException err = (DecoderException) cause; cause = err.getCause(); } completionHandler.handle(CommandResponse.failure(cause)); } }); pipeline.addBefore("handler","initiate-ssl-handler",new InitiateSslHandler(this,upgradeFuture)); } else { initiateProtocol(username,completionHandler); } }
public int[] readVarIntArray(int maxLength) { int i = this.readVarIntFromBuffer(); if (i > maxLength) { throw new DecoderException("VarIntArray with size " + i + " is bigger than allowed " + maxLength); } else { int[] aint = new int[i]; for (int j = 0; j < aint.length; ++j) { aint[j] = this.readVarIntFromBuffer(); } return aint; } }
public long[] readLongArray(@Nullable long[] p_189423_1_,int p_189423_2_) { int i = this.readVarIntFromBuffer(); if (p_189423_1_ == null || p_189423_1_.length != i) { if (i > p_189423_2_) { throw new DecoderException("LongArray with size " + i + " is bigger than allowed " + p_189423_2_); } p_189423_1_ = new long[i]; } for (int j = 0; j < p_189423_1_.length; ++j) { p_189423_1_[j] = this.readLong(); } return p_189423_1_; }
@Nullable public static List < EntityDataManager.DataEntry<? >> readEntries(PacketBuffer buf) throws IOException { List < EntityDataManager.DataEntry<? >> list = null; int i; while ((i = buf.readUnsignedByte()) != 255) { if (list == null) { list = Lists. < EntityDataManager.DataEntry<? >> newArrayList(); } int j = buf.readVarIntFromBuffer(); DataSerializer<?> dataserializer = DataSerializers.getSerializer(j); if (dataserializer == null) { throw new DecoderException("UnkNown serializer type " + j); } list.add(new EntityDataManager.DataEntry(dataserializer.createKey(i),dataserializer.read(buf))); } return list; }
public int[] readVarIntArray(int maxLength) { int i = this.readVarIntFromBuffer(); if (i > maxLength) { throw new DecoderException("VarIntArray with size " + i + " is bigger than allowed " + maxLength); } else { int[] aint = new int[i]; for (int j = 0; j < aint.length; ++j) { aint[j] = this.readVarIntFromBuffer(); } return aint; } }
@SideOnly(Side.CLIENT) public long[] readLongArray(@Nullable long[] p_189423_1_,int p_189423_2_) { int i = this.readVarIntFromBuffer(); if (p_189423_1_ == null || p_189423_1_.length != i) { if (i > p_189423_2_) { throw new DecoderException("LongArray with size " + i + " is bigger than allowed " + p_189423_2_); } p_189423_1_ = new long[i]; } for (int j = 0; j < p_189423_1_.length; ++j) { p_189423_1_[j] = this.readLong(); } return p_189423_1_; }
@Nullable public static List < EntityDataManager.DataEntry<? >> readEntries(PacketBuffer buf) throws IOException { List < EntityDataManager.DataEntry<? >> list = null; int i; while ((i = buf.readUnsignedByte()) != 255) { if (list == null) { list = Lists. < EntityDataManager.DataEntry<? >> newArrayList(); } int j = buf.readVarIntFromBuffer(); DataSerializer<?> dataserializer = DataSerializers.getSerializer(j); if (dataserializer == null) { throw new DecoderException("UnkNown serializer type " + j); } list.add(new EntityDataManager.DataEntry(dataserializer.createKey(i),dataserializer.read(buf))); } return list; }
public String readText(final int i) { final int j = this.readVarInt(); if (j > (i << 2)) { throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + j + " > " + (i << 2) + ")"); } if (j < 0) { throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); } final String s = new String(this.readBytes(j).array(),StandardCharsets.UTF_8); if (s.length() > i) { throw new DecoderException("The received string length is longer than maximum allowed (" + j + " > " + i + ")"); } return s; }
@Override protected Object decode(ChannelHandlerContext ctx,ByteBuf buffer) throws Exception { ByteBuf buf = (ByteBuf) super.decode(ctx,buffer); if (buf != null) { try { int pos = buf.bytesBefore((byte) config.getStartByte()); if (pos >= 0) { ByteBuf msg = buf.readerIndex(pos + 1).slice(); LOG.debug("Message ends with length {}",msg.readableBytes()); return config.isProduceString() ? asstring(msg) : asByteArray(msg); } else { throw new DecoderException("Did not find start byte " + (int) config.getStartByte()); } } finally { // We need to release the buf here to avoid the memory leak buf.release(); } } // Message not complete yet - return null to be called again LOG.debug("No complete messages yet at position {}",buffer.readableBytes()); return null; }
@Override public final void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception { if(cause instanceof DecoderException && cause != null) { cause = cause.getCause(); } errorHandler.logError(cause,false); if(cause instanceof NotSslRecordException) { log.warn("Someone ({}) speaks transport plaintext instead of ssl,will close the channel",ctx.channel().remoteAddress()); ctx.channel().close(); return; } else if (cause instanceof SSLException) { log.error("SSL Problem "+cause.getMessage(),cause); ctx.channel().close(); return; } else if (cause instanceof SSLHandshakeException) { log.error("Problem during handshake "+cause.getMessage()); ctx.channel().close(); return; } super.exceptionCaught(ctx,cause); }
@Override public Message decode(CodecContext context,ByteBuffer buf) throws CodecException { int action = buf.readByte(); Vector3i position = buf.read(Types.VECTOR_3_I); int face = buf.readByte(); switch (action) { case 0: case 1: case 2: return new MessagePlayInPlayerDigging(MessagePlayInPlayerDigging.Action.values()[action],position,fromFace(face)); case 3: case 4: return new MessagePlayInDropHeldItem(action == 3); case 5: return new MessagePlayInOutFinishUsingItem(); case 6: return new MessagePlayInSwapHandItems(); default: throw new DecoderException("UnkNown player digging message action: " + action); } }
@Override public Message decode(CodecContext context,ByteBuffer buf) throws CodecException { final String channel = buf.readLimitedString(LanternChannelRegistrar.MAX_NAME_LENGTH); final int length = buf.available(); if (length > Short.MAX_VALUE) { throw new DecoderException("CustomPayload messages may not be longer then " + Short.MAX_VALUE + " bytes"); } final ByteBuffer content = buf.slice(); final Message message = decode0(context,content,channel); if (content.available() > 0) { Lantern.getLogger().warn("Trailing bytes {}b after decoding with custom payload message codec {} with channel {}!\n{}",content.available(),getClass().getName(),channel,message); } // Skip all the bytes,we already processed them buf.setReadindex(buf.readerIndex() + buf.available()); return message; }
@Override public MessagePlayInUseEntity decode(CodecContext context,ByteBuffer buf) throws CodecException { final int entityId = buf.readVarInt(); final int action = buf.readVarInt(); if (action == 1) { return new MessagePlayInUseEntity.Attack(entityId); } else if (action == 0 || action == 2) { Vector3d position = null; if (action == 2) { final double x = buf.readFloat(); final double y = buf.readFloat(); final double z = buf.readFloat(); position = new Vector3d(x,y,z); } final HandType hand = buf.readVarInt() == 0 ? HandTypes.MAIN_HAND : HandTypes.OFF_HAND; return new MessagePlayInUseEntity.Interact(entityId,hand,position); } else { throw new DecoderException("Received a UseEntity message with a unkNown action: " + action); } }
@Test(expected = DecoderException.class) public void failIfv1NotSupported() { EmbeddedChannel channel = new EmbeddedChannel(new VotifierProtocolDifferentiator(true,false)); VotifierSession session = new VotifierSession(); channel.attr(VotifierSession.KEY).set(session); ByteBuf test = Unpooled.buffer(256); for (int i = 0; i < 256; i++) { test.writeByte(0); } channel.writeInbound(test); assertEquals(VotifierSession.ProtocolVersion.ONE,session.getVersion()); channel.close(); }
@Test(expected = DecoderException.class) public void testFailureDecodeBadPacket() throws Exception { // Create a well-formed request EmbeddedChannel channel = createChannel(); Vote Vote = new Vote("Test","test","0"); JSONObject object = new JSONObject(); JSONObject payload = Vote.serialize(); payload.put("challenge",SESSION.getChallenge()); object.put("payload",payload.toString()); // We "forget" the signature. try { channel.writeInbound(object.toString()); } finally { channel.close(); } }
@Test(expected = DecoderException.class) public void testFailureDecodeBadVoteField() throws Exception { // Create a well-formed request EmbeddedChannel channel = createChannel(); Vote Vote = new Vote("Test","0"); JSONObject object = new JSONObject(); JSONObject payload = Vote.serialize(); // We "forget" the challenge. object.put("payload",payload.toString()); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(TestVotifierPlugin.getI().getTokens().get("default")); object.put("signature",Base64.getEncoder().encodetoString(mac.doFinal(payload.toString().getBytes(StandardCharsets.UTF_8)))); try { channel.writeInbound(object.toString()); } finally { channel.close(); } }
@Test(expected = DecoderException.class) public void testFailureDecodeBadChallenge() throws Exception { // Create a well-formed request EmbeddedChannel channel = createChannel(); Vote Vote = new Vote("Test","0"); JSONObject object = new JSONObject(); JSONObject payload = Vote.serialize(); // We provide the wrong challenge. payload.put("challenge","not a challenge for me"); object.put("payload",Base64.getEncoder().encode(mac.doFinal(payload.toString().getBytes(StandardCharsets.UTF_8)))); try { channel.writeInbound(object.toString()); } finally { channel.close(); } }
@Test public void testTruncatedPacket() throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(false); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); // Push the first part of a 5-byte handshake message. ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{22,1,5})); // Should decode nothing yet. assertthat(ch.readInbound(),is(nullValue())); try { // Push the second part of the 5-byte handshake message. ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{2,0})); fail(); } catch (DecoderException e) { // The pushed message is invalid,so it should raise an exception if it decoded the message correctly. assertthat(e.getCause(),is(instanceOf(SSLProtocolException.class))); } }
@Test public void testFailSlowTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new DelimiterBasedFrameDecoder(1,true,false,Delimiters.nulDelimiter())); for (int i = 0; i < 2; i ++) { ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1,2 })); try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 'A',0 })); ByteBuf buf = releaseLater((ByteBuf) ch.readInbound()); assertEquals("A",buf.toString(CharsetUtil.ISO_8859_1)); } }
@Test public void testFailFastTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new DelimiterBasedFrameDecoder(1,Delimiters.nulDelimiter())); for (int i = 0; i < 2; i ++) { try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1,2 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0,'A',buf.toString(CharsetUtil.ISO_8859_1)); } }
@Test public void testFailSlowTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new LengthFieldBasedFrameDecoder(5,false)); for (int i = 0; i < 2; i ++) { assertFalse(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0,2 }))); try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0,0 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0,'A' })); ByteBuf buf = releaseLater((ByteBuf) ch.readInbound()); assertEquals("A",buf.toString(CharsetUtil.ISO_8859_1)); buf.release(); } }
@Test public void testFailFastTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new LengthFieldBasedFrameDecoder(5,4)); for (int i = 0; i < 2; i ++) { try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0,buf.toString(CharsetUtil.ISO_8859_1)); buf.release(); } }
@Override protected void decode(ChannelHandlerContext ctx,ByteBuf buf,List<Object> packets) throws Exception { if (!buf.isReadable()) { return; } buf.markReaderIndex(); ReadableMiddlePacket transformer = registry.getTransformer(Protocol.GAME,buf.readUnsignedByte(),false); if (transformer != null) { transformer.read(buf); if (buf.isReadable()) { throw new DecoderException("Did not read all data from packet " + transformer.getClass().getName() + ",bytes left: " + buf.readableBytes()); } packets.addAll(transformer.toNative()); } else { buf.resetReaderIndex(); packets.add(new PacketWrapper(null,buf.copy())); } }
@Override protected void decode(ChannelHandlerContext ctx,readPacketId(buf),false); if (transformer == null) { buf.resetReaderIndex(); packets.add(new PacketWrapper(null,buf.copy())); } else { transformer.read(buf); if (buf.isReadable()) { throw new DecoderException("Did not read all data from packet " + transformer.getClass().getName() + ",bytes left: " + buf.readableBytes()); } packets.addAll(transformer.toNative()); } }
@Override protected void decode(ChannelHandlerContext ctx,List<Object> packets) throws Exception { if (!buf.isReadable()) { return; } buf.markReaderIndex(); ReadableMiddlePacket transformer = registry.getTransformer(protocol,bytes left: " + buf.readableBytes()); } packets.addAll(transformer.toNative()); } }
public static EncapsulatedProtocolInfo readInfo(ByteBuf from) { int encapVersion = VarNumberSerializer.readVarInt(from); if (encapVersion > CURRENT_VERSION) { throw new DecoderException(messageformat.format("Unsupported encapsulation protocol verrsion {}",encapVersion)); } InetSocketAddress remoteaddress = null; if (from.readBoolean()) { try { InetAddress address = InetAddress.getByAddress(MiscSerializer.readBytes(from,VarNumberSerializer.readVarInt(from))); remoteaddress = new InetSocketAddress(address,VarNumberSerializer.readVarInt(from)); } catch (UnkNownHostException e) { throw new DecoderException("Invalid ip address"); } } boolean hasCompression = from.readBoolean(); if (encapVersion == 0) { VarNumberSerializer.readVarInt(from); VarNumberSerializer.readVarInt(from); } return new EncapsulatedProtocolInfo(remoteaddress,hasCompression); }
private static Any<Key,JsonObject> extractChainData(Map<String,List<String>> maindata) throws ParseException { List<String> chain = maindata.get("chain"); try { PublicKey key = parseKey(MOJANG_KEY); boolean foundMojangKey = false; boolean signatureValid = false; for (String element : chain) { JWSObject jwsobject = JWSObject.parse(element); if (!foundMojangKey && jwsobject.getHeader().getX509CertURL().toString().equals(MOJANG_KEY)) { foundMojangKey = true; signatureValid = true; } if (foundMojangKey && !verify(jwsobject,key)) { signatureValid = false; } JsonObject jsonobject = Utils.GSON.fromJson(jwsobject.getPayload().toString(),JsonObject.class); key = parseKey(JsonUtils.getString(jsonobject,"identityPublicKey")); if (jsonobject.has("exTradata")) { return new Any<Key,JsonObject>(signatureValid ? key : null,JsonUtils.getJsonObject(jsonobject,"exTradata")); } } } catch (InvalidKeySpecException | JOSEException e) { throw new DecoderException("Unable to decode login chain",e); } throw new DecoderException("Unable to find exTradata"); }
@Override protected void decode(ChannelHandlerContext ctx,List<Object> list) throws Exception { try { inflater.setInput(MiscSerializer.readAllBytes(buf)); int decompressedlength = inflater.inflate(decompressionbuffer); if (!inflater.finished()) { throw new DecoderException(messageformat.format("Badly compressed packet - size is larger than protocol maximum of {0}",maxPacketLength)); } ByteBuf uncompresseddata = Unpooled.wrappedBuffer(decompressionbuffer,decompressedlength); while (uncompresseddata.isReadable()) { list.add(Unpooled.wrappedBuffer(MiscSerializer.readBytes(uncompresseddata,VarNumberSerializer.readVarInt(uncompresseddata)))); } } finally { inflater.reset(); } }
@Override protected void decode(ChannelHandlerContext context,ByteBuf buffer,List<Object> out) throws Exception { buffer.markReaderIndex(); try { final String command = nextString(buffer); // Extract event type switch (command) { case "LOG": decodeLogEvent(context,buffer,out); break; default: throw new IllegalStateException("UnkNown command " + command); } } catch (Exception e) { buffer.resetReaderIndex(); throw new DecoderException("Invalid line event: " + buffer.toString(StandardCharsets.UTF_8),e); } }
@Override public void decodeResponseData(ByteBuf data,ModbusResponse response) { if (data.readableBytes() < getResponseDataLength()) { throw new DecoderException(); } ReadWordRegistersResponse readWordRegistersResponse = (ReadWordRegistersResponse) response; readWordRegistersResponse.setStartingAddress(startingAddress); int dataContentBytes = data.readUnsignedByte(); if (dataContentBytes != getResponseDataLength() - 1) { throw new DecoderException(); } readWordRegistersResponse.setQuantityAndAllocate(quantity); for (int i = 0; i < quantity; i++) { readWordRegistersResponse.setValue(i,data.readUnsignedShort()); } }
/** * Decodes the fixed header. It's one byte for the flags and then variable bytes for the remaining length. * * @param buffer the buffer to decode from * @return the fixed header */ private static MqttFixedHeader decodeFixedHeader(ByteBuf buffer) { short b1 = buffer.readUnsignedByte(); MqttMessageType messageType = MqttMessageType.valueOf(b1 >> 4); boolean dupFlag = (b1 & 0x08) == 0x08; int qosLevel = (b1 & 0x06) >> 1; boolean retain = (b1 & 0x01) != 0; int remainingLength = 0; int multiplier = 1; short digit; int loops = 0; do { digit = buffer.readUnsignedByte(); remainingLength += (digit & 127) * multiplier; multiplier *= 128; loops++; } while ((digit & 128) != 0 && loops < 4); // MQTT protocol limits Remaining Length to 4 bytes if (loops == 4 && (digit & 128) != 0) { throw new DecoderException("remaining length exceeds 4 digits (" + messageType + ')'); } return new MqttFixedHeader(messageType,remainingLength); }
public static ListIdentity decode(ByteBuf buffer) { if (buffer.readableBytes() > 0) { CpfPacket packet = CpfPacket.decode(buffer); CpfItem[] items = packet.getItems(); if (items.length > 0) { if (items[0] instanceof CipIdentityItem) { return new ListIdentity((CipIdentityItem) items[0]); } else { throw new DecoderException( String.format("expected CipIdentityItem; received %s instead",items[0].getClass().getSimpleName())); } } else { return new ListIdentity(); } } return new ListIdentity(); }
@Test public void testTruncatedPacket() throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(false); EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); // Push the first part of a 5-byte handshake message. ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{22,is(instanceOf(SSLProtocolException.class))); } }
@Test public void testFailSlowTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new DelimiterBasedFrameDecoder(1,buf.toString(CharsetUtil.ISO_8859_1)); } }
io.netty.handler.codec.EncoderException的实例源码
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 () ); } }
/** * Writes a compressed NBTTagCompound to this buffer */ public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt,new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
/** * Writes a compressed NBTTagCompound to this buffer */ public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt,new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
/** * Writes a compressed NBTTagCompound to this buffer */ public PacketBuffer writeNBTTagCompoundToBuffer(@Nullable NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt,new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } return this; }
private static <T> void writeEntry(PacketBuffer buf,EntityDataManager.DataEntry<T> entry) throws IOException { DataParameter<T> dataparameter = entry.getKey(); int i = DataSerializers.getSerializerId(dataparameter.getSerializer()); if (i < 0) { throw new EncoderException("UnkNown serializer type " + dataparameter.getSerializer()); } else { buf.writeByte(dataparameter.getId()); buf.writeVarIntToBuffer(i); dataparameter.getSerializer().write(buf,entry.getValue()); } }
/** * Writes a compressed NBTTagCompound to this buffer */ public PacketBuffer writeNBTTagCompoundToBuffer(@Nullable NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt,new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } return this; }
/** * Reads a compressed NBTTagCompound from this buffer */ @Nullable public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException { int i = this.readerIndex(); byte b0 = this.readByte(); if (b0 == 0) { return null; } else { this.readerIndex(i); try { return CompressedStreamTools.read(new ByteBufInputStream(this),new NBTSizeTracker(2097152L)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
private static <T> void writeEntry(PacketBuffer buf,entry.getValue()); } }
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) { ModLogger.error("IOException while trying to write a NBTTagCompound to ByteBuf"); throw new EncoderException(ioexception); } }
@Nullable public static NBTTagCompound readNBTTagCompound(MCDataInput input) { byte flag = input.readByte(); if (flag == 0) { return null; } else if (flag == 1) { try { return CompressedStreamTools.read(new DataInputStream(new MCDataInputStream(input)),new NBTSizeTracker(2097152L)); } catch (IOException e) { throw new EncoderException(e); } } else { throw new EncoderException("Invalid flag for readNBTTagCompound. Expected 0 || 1 Got: " + flag + " Possible incorrect read order?"); } }
/** * Decompresses the remaining ByteBuf (after type has been read) using Snappy */ private void decompress() { Inflater inflater = new Inflater(); try { int len = readVarInt(); byte[] out = new byte[len]; inflater.setInput(array(),readerIndex(),readableBytes()); inflater.inflate(out); clear(); writeArray(out); } catch (Exception e) { throw new EncoderException(e); } finally { inflater.end(); } }
/** * 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(),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); writeArray(out); } catch (Exception e) { throw new EncoderException(e); } finally { readerIndex(0); deflater.end(); } }
@Override public ByteBuffer encode(CodecContext context,MessagePlayOutUnlockRecipes message) throws CodecException { final ByteBuffer buf = context.byteBufAlloc().buffer(); if (message instanceof MessagePlayOutUnlockRecipes.Remove) { buf.writeVarInt((short) 2); } else if (message instanceof MessagePlayOutUnlockRecipes.Add) { buf.writeVarInt((short) 1); } else if (message instanceof MessagePlayOutUnlockRecipes.Init) { buf.writeVarInt((short) 0); } else { throw new EncoderException(); } buf.writeBoolean(message.hasOpenCraftingBook()); buf.writeBoolean(message.hasCraftingFilter()); IntList recipeIds = message.getRecipeIds(); buf.writeVarInt(recipeIds.size()); recipeIds.forEach(buf::writeVarInt); if (message instanceof MessagePlayOutUnlockRecipes.Init) { recipeIds = ((MessagePlayOutUnlockRecipes.Init) message).getRecipeIdsToBedisplayed(); buf.writeVarInt(recipeIds.size()); recipeIds.forEach(buf::writeVarInt); } return buf; }
@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); } }
@Override protected void encode(ChannelHandlerContext channelHandlerContext,Packet packet,List<Object> list) throws Exception { Class<? extends Packet> packetClass = packet.getClass(); CodecRegistrationEntry registrationEntry = this.networkHandler.getSession().getProtocol().getCodecRegistration(this.side,packetClass); if (registrationEntry == null) { throw new EncoderException("Failed to find a CodecRegistrationEntry for packet: " + packetClass.getName()); } ByteBuf header = channelHandlerContext.alloc().buffer(8); ByteBufUtils.writeVarInt(header,registrationEntry.getopcode()); ByteBuf contents = channelHandlerContext.alloc().buffer(); contents = registrationEntry.getCodec().encode(contents,packet); list.add(Unpooled.wrappedBuffer(header,contents)); }
@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[]{}))); }
public static void writeNBTTagCompoundToBuffer(ByteBuf buf,new ByteBufOutputStream(buf)); } catch (IOException ioexception) { EnderUtilities.logger.error("IOException while trying to write a NBTTagCompound to ByteBuf"); throw new EncoderException(ioexception); } }
/** * Writes a compressed NBTTagCompound to this buffer */ public PacketBuffer writeNBTTagCompoundToBuffer(@Nullable NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt,new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } return this; }
/** * Reads a compressed NBTTagCompound from this buffer */ @Nullable public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException { int i = this.readerIndex(); byte b0 = this.readByte(); if (b0 == 0) { return null; } else { this.readerIndex(i); try { return CompressedStreamTools.read(new ByteBufInputStream(this),new NBTSizeTracker(2097152L)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
public static void writeTag(ByteBuf to,ProtocolVersion version,NBTTagCompoundWrapper tag) { try { if (isUsingShortLengthNBT(version)) { if (tag.isNull()) { to.writeShort(-1); } else { int writerIndex = to.writerIndex(); //fake length to.writeShort(0); //actual nbt try (OutputStream outputstream = new GZIPOutputStream(new ByteBufOutputStream(to))) { NBTTagCompoundSerializer.writeTag(new DataOutputStream(outputstream),tag); } //Now replace fake length with real length to.setShort(writerIndex,to.writerIndex() - writerIndex - Short.BYTES); } } else if (isUsingDirectNBT(version)) { NBTTagCompoundSerializer.writeTag(new ByteBufOutputStream(to),tag); } else { throw new IllegalArgumentException(messageformat.format("Dont kNow how to write nbt of version {0}",version)); } } catch (Throwable ioexception) { throw new EncoderException(ioexception); } }
/** * Decode the variable remaining length as defined in MQTT v3.1 specification * (section 2.1). * * @return the decoded length or -1 if needed more data to decode the length field. */ public static int decodeRemainingLength(ByteBuf in) throws EncoderException { int multiplier = 1; int value = 0; byte digit; do { if (in.readableBytes() < 1) { return -1; } digit = in.readByte(); value += (digit & 0x7F) * multiplier; multiplier *= 128; } while ((digit & 0x80) != 0); if (value > MAX_LENGTH_LIMIT || value < 0) { in.resetReaderIndex(); throw new DecoderException("Remaining Length should in range 0.." + MAX_LENGTH_LIMIT + " found " + value); } return value; }
/** * Encode the value in the format defined in specification as variable length * array. * * @throws EncoderException if the value is not in the specification bounds * [0..268435455]. */ public static ByteBuf encodeRemainingLength(int value) throws EncoderException { if (value > MAX_LENGTH_LIMIT || value < 0) { throw new EncoderException("Remaining Length should in range 0.." + MAX_LENGTH_LIMIT + " found " + value); } ByteBuf encoded = Unpooled.buffer(4); byte digit; do { digit = (byte) (value % 128); value = value / 128; // if there are more digits to encode,set the top bit of this digit if (value > 0) { digit = (byte) (digit | 0x80); } encoded.writeByte(digit); } while (value > 0); return encoded; }
private void encode(ChannelHandlerContext ctx,ByteBuf out,RedisCommand<?,?,?> command) { try { out.markWriterIndex(); command.encode(out); } catch (RuntimeException e) { out.resetWriterIndex(); command.completeExceptionally(new EncoderException( "Cannot encode command. Please close the connection as the connection state may be out of sync.",e)); } if (debugEnabled) { logger.debug("{} writing command {}",logPrefix(ctx.channel()),command); if (traceEnabled) { logger.trace("{} Sent: {}",out.toString(Charset.defaultCharset()).trim()); } } }
@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); }
@Nullable public NBTTagCompound j() { int i = this.readerIndex(); byte b0 = this.readByte(); if (b0 == 0) { return null; } else { this.readerIndex(i); try { return NBTCompressedStreamTools.a((DataInput) (new ByteBufInputStream(this)),new NBTReadLimiter(2097152L)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
@Override public void write ( final ChannelHandlerContext ctx,final Object msg,final ChannelPromise promise ) throws Exception { logger.trace ( "Write {}",msg ); synchronized ( this ) { if ( msg instanceof DataTransmissionMessage ) { switch ( (DataTransmissionMessage)msg ) { case REQUEST_START: ctx.write ( new UnnumberedControl ( Function.STARTDT_ACT ),promise ); break; case CONFIRM_START: ctx.write ( new UnnumberedControl ( Function.STARTDT_CONFIRM ),promise ); break; case REQUEST_STOP: ctx.write ( new UnnumberedControl ( Function.STOPDT_ACT ),promise ); break; case CONFIRM_STOP: ctx.write ( new UnnumberedControl ( Function.STOPDT_CONFIRM ),promise ); break; default: throw new EncoderException ( String.format ( "UnkNown data transmission message: %s",msg ) ); } } else if ( msg == MessageSource.NOTIFY_TOKEN ) { handleMessageSourceUpdates ( ctx ); } else { handleMessageWrite ( ctx,promise ); } } }
/** * Writes a string into the packets buffer * * @param string The string * @return The buffer */ public PacketBuffer writeString(String string) { if(string == null) string = ""; byte[] abyte = string.getBytes(Charsets.UTF_8); if(abyte.length > 32767) { throw new EncoderException("String too big (was " + string.length() + " bytes encoded,slots " + 32767 + ")"); } else { this.writeVarInt(abyte.length); buf.writeBytes(abyte); return this; } }
public PacketBuffer writeString(String string) { byte[] abyte = string.getBytes(Charsets.UTF_8); if (abyte.length > 32767) { throw new EncoderException("String too big (was " + string.length() + " bytes encoded,max " + 32767 + ")"); } else { this.writeVarIntToBuffer(abyte.length); this.writeBytes(abyte); return this; } }
public PacketBuffer writeString(String string) { byte[] abyte = string.getBytes(Charsets.UTF_8); if (abyte.length > 32767) { throw new EncoderException("String too big (was " + string.length() + " bytes encoded,max " + 32767 + ")"); } else { this.writeVarIntToBuffer(abyte.length); this.writeBytes(abyte); return this; } }
@Nullable /** * Reads a compressed NBTTagCompound from this buffer */ public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException { int i = this.readerIndex(); byte b0 = this.readByte(); if (b0 == 0) { return null; } else { this.readerIndex(i); try { return CompressedStreamTools.read(new ByteBufInputStream(this),new NBTSizeTracker(2097152L)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
public PacketBuffer writeString(String string) { byte[] abyte = string.getBytes(Charsets.UTF_8); if (abyte.length > 32767) { throw new EncoderException("String too big (was " + abyte.length + " bytes encoded,max " + 32767 + ")"); } else { this.writeVarIntToBuffer(abyte.length); this.writeBytes(abyte); return this; } }
public PacketBuffer writeString(String string) { byte[] abyte = string.getBytes(Charsets.UTF_8); if (abyte.length > 32767) { throw new EncoderException("String too big (was " + string.length() + " bytes encoded,max " + 32767 + ")"); } else { this.writeVarIntToBuffer(abyte.length); this.writeBytes(abyte); return this; } }
public void toBytes(CompressedDataOutput cdo) throws IOException { if (stack == null || ItemStackTools.isNullStack(stack)) { cdo.writeShort(-1); } else { cdo.writeShort(Item.getIdFromItem(stack.getItem())); cdo.writeVariable(ItemStackTools.getStackSize(stack)); cdo.writeShort(stack.getMetadata()); NBTTagCompound nbttagcompound = null; if (stack.getItem().isdamageable() || stack.getItem().getShareTag()) { nbttagcompound = stack.getTagCompound(); } if (nbttagcompound == null) { cdo.writeByte(0); } else { cdo.writeByte(1); try { CompressedStreamTools.write(nbttagcompound,cdo); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } } cdo.writeBoolean(isCrafting); }
public void toBytes(CompressedDataOutput cdo) throws IOException { if (stack == null) { cdo.writeShort(-1); } else { cdo.writeShort(1); NBTTagCompound nbttagcompound = stack.writetoNBT(new NBTTagCompound()); cdo.writeByte(1); try { CompressedStreamTools.write(nbttagcompound,cdo); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
public PacketDataSerializer writeText(final String s) { final byte[] abyte = s.getBytes(StandardCharsets.UTF_8); if (abyte.length > Short.MAX_VALUE) { throw new EncoderException("String too big (was " + s.length() + " bytes encoded,max " + Short.MAX_VALUE + ")"); } this.writeVarInt(abyte.length); this.writeBytes(abyte); return this; }
public MCDataOutputWrapper writeBoolean(boolean b) { try { dataout.writeBoolean(b); } catch (IOException e) { throw new EncoderException(e); } return this; }
今天关于javax.websocket.DecodeException的实例源码和java socket write error的介绍到此结束,谢谢您的阅读,有关com.datastax.driver.core.exceptions.CodecNotFoundException的实例源码、io.netty.handler.codec.CodecException的实例源码、io.netty.handler.codec.DecoderException的实例源码、io.netty.handler.codec.EncoderException的实例源码等更多相关知识的信息可以在本站进行查询。
本文标签: