TLV { public boolean parse(Tag tag, int offset) { if (tag == null) { throw new IllegalArgumentException("TLV parsing: tag can't be null."); } try { this.tag = new Tag(binary, offset); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("TLV parsing: index is too large."); } length = 0; if (tag.equals(this.tag)) { offset += this.tag.getTagSize(); position += this.tag.getTagSize(); if ((binary[offset] & (byte) 0x80) == (byte) 0x00) { length += binary[offset]; position++; } else { int following = (binary[offset] & (byte) 0x7F); position++; while (following > 0) { offset++; position++; length += (binary[offset] & 0xFF); if (following > 1) { length <<= 8; } following--; } } return true; } else { return false; } } TLV(byte[] binary); boolean parse(Tag tag, int offset); byte[] getValue(); int getPosition(); @Override String toString();  }
@Test public void parse() { Tag tag1 = new Tag(0x04, Tag.CONTEXT, PRIMITIVE, 1); Tag tag2 = new Tag(0x04, Tag.CONTEXT, CONSTRUCTED, 1); TLV tlv = new TLV(ByteArrayUtil.fromHex("84050011223344")); Assert.assertTrue(tlv.parse(tag1, 0)); Assert.assertTrue(tlv.parse(tag1, 0)); Assert.assertFalse(tlv.parse(tag2, 0)); }
@Test(expected = IllegalArgumentException.class) public void parse_tag_null() { TLV tlv = new TLV(ByteArrayUtil.fromHex("84050011223344")); tlv.parse(null, 0); }
@Test(expected = IllegalArgumentException.class) public void parse_too_large_index() { Tag tag = new Tag(0x04, Tag.CONTEXT, PRIMITIVE, 1); TLV tlv = new TLV(ByteArrayUtil.fromHex("84050011223344")); tlv.parse(null, 20); }