数据报解析，将byte数组解析为数据报

@param data     数据报的byte数组
@param allowErr 是否允许数据报错误，true表示允许，当允许该错误的时候，如果数据报实际长度大于报头的长度将采用报头的长度，该参数主要用于解析UDP数据
@return 从data中解析的数据报对象
@throws IllegalRequestException 正常情况不会抛该异常，当请求非法时可能抛出该异常
9809
public static Datagram decode(final byte[] data,
                                  boolean allowErr) throws IllegalRequestException {
        try {
            if (log.isDebugEnabled()) {
                log.debug("要解析的数据为：{}", Arrays.toString(data));
            }
            // 字符集数据
            int end = Datagram.CHARSET_OFFSET;
            for (int i = 0; i < Datagram.CHARSET_MAX; end += i, i++) {
                if (data[end] == 0) {
                    break;
                }
            }
            // 字符集
            final String charset = new String(data, Datagram.CHARSET_OFFSET,
                end - Datagram.CHARSET_OFFSET);
            // 版本号
            final byte version = data[Datagram.VERSION_INDEX];
            // 数据报数据类型
            final byte type = data[Datagram.TYPE_INDEX];
            // 长度
            final int len = readLen(data);
            log.debug("要解析的数据报的字符集为：{}，版本号为：{}，数据报类型为：{}", charset, version, type);

            byte[] buffer;
            if ((data.length - Datagram.HEADER_LEN) > len) {
                log.warn("数据报head中的长度字段为：{}，数据报body的实际长度为：{}", len,
                    data.length - Datagram.HEADER_LEN);
                if (allowErr) {
                    buffer = new byte[len + Datagram.HEADER_LEN];
                    System.arraycopy(data, 0, buffer, 0, buffer.length);
                } else {
                    throw new IllegalDataException("数据报head中的长度字段为：" + len + "，数据报body的实际长度为："
                                                   + (data.length - Datagram.HEADER_LEN));
                }
            } else if ((data.length - Datagram.HEADER_LEN) < len) {
                log.error("数据报head中的长度字段为：{}，数据报body的实际长度为：{}", len,
                    data.length - Datagram.HEADER_LEN);
                throw new IllegalDataException("数据报head中的长度字段为：" + len + "，数据报body的实际长度为："
                                               + (data.length - Datagram.HEADER_LEN));
            } else {
                buffer = data;
            }

            log.debug("获取id字段");
            byte[] idByte = new byte[40];
            System.arraycopy(data, 16, idByte, 0, idByte.length);
            String id = new String(idByte);
            log.debug("数据报ID为：{}", id);

            // 有可能是空报文的数据报
            Datagram datagram;
            if (len == 0) {
                log.debug("要解析的数据中head标志body长度为0，直接返回一个空body的datagram对象");
                datagram = new Datagram(buffer, len, null, version, charset, type, idByte);
            } else {
                // 真实的业务数据
                byte[] body = new byte[len];
                System.arraycopy(buffer, Datagram.HEADER_LEN, body, 0, body.length);
                datagram = new Datagram(buffer, len, body, version, charset, type, idByte);
            }
            if (log.isDebugEnabled()) {
                log.debug("封装好的数据报body为：{}", datagram);
            }
            return datagram;
        } catch (Exception e) {
            log.error("数据报解析错误，错误原因：{}", e);
            throw new IllegalRequestException(e);
        }
    }
1248275
private Object decodeResult(IoBuffer data) {
        log.debug("decodeResult - data limit: {}", (data != null ? data.limit() : 0));
        processHeaders(data);
        int count = data.getUnsignedShort();
        if (count != 1) {
            throw new RuntimeException("Expected exactly one result but got " + count);
        }
        Input input = new Input(data);
        String target = input.getString(); // expect "/onResult"
        log.debug("Target: {}", target);
        String nullString = input.getString(); // expect "null"
        log.debug("Null string: {}", nullString);
        // Read return value
        return Deserializer.deserialize(input, Object.class);
    }
530180
private DataBuffer withDataBufferFactory(ByteBufHttpData data) {
        final byte[] dataArray = ByteBufUtil.getBytes(data.content());
        data.release();
        return delegate.wrap(dataArray);
    }
1012132
public static Object dataDeserialize(byte[] data, String type) throws IOException, ClassNotFoundException {

        // check the type of the stored data
        Class<?> clazz = Class.forName(type);

        if (isParseable(clazz)) {
            // this is parseable data
            return parse(new String(data), clazz);
        }

        // this is a serialized object
        ByteArrayInputStream bin = new ByteArrayInputStream(data);
        ObjectInputStream oin = new ObjectInputStream(bin);
        return oin.readObject();
    }
499282
public RequestResponse setResponseData(byte[] responseData) {
        this.responseData = responseData;
        try {
            responseJson = responseData != null ? SerializationUtils.readJson(responseData) : null;
        } catch (Exception e) {
            responseJson = null;
            LOGGER.error(e.getMessage(), e);
        }
        return this;
    }
560021
private Object decodeResult(IoBuffer data) {
        log.debug("decodeResult - data limit: {}", (data != null ? data.limit() : 0));
        processHeaders(data);

        Input input = new Input(data);
        String target = null;

        byte b = data.get();
        //look for SOH
        if (b == 0) {
            log.debug("NUL: {}", b); //0
            log.debug("SOH: {}", data.get()); //1
        } else if (b == 1) {
            log.debug("SOH: {}", b); //1			
        }

        int targetUriLength = data.getShort();
        log.debug("targetUri length: {}", targetUriLength);
        target = input.readString(targetUriLength);

        log.debug("NUL: {}", data.get()); //0

        //should be junk bytes ff, ff, ff, ff
        int count = data.getInt();
        if (count == -1) {
            log.debug("DC1: {}", data.get()); //17
            count = 1;
        } else {
            data.position(data.position() - 4);
            count = data.getShort();
        }

        if (count != 1) {
            throw new RuntimeException("Expected exactly one result but got " + count);
        }

        String[] targetParts = target.split("[/]");
        if (targetParts.length > 1) {
            log.debug("Result sequence number: {}", targetParts[1]);
            target = targetParts[2];
        } else {
            target = target.substring(1);
        }
        log.debug("Target: {}", target);
        if ("onResult".equals(target)) {
            //read return value
            return input.readObject();
        } else if ("onStatus".equals(target)) {
            //read return value
            return input.readObject();
        }
        //read return value
        return Deserializer.deserialize(input, Object.class);
    }
423168
private static boolean loadDataMultipartStandard(ByteBuf undecodedChunk, String delimiter, HttpData httpData) {
        final int startReaderIndex = undecodedChunk.readerIndex();
        final int delimeterLength = delimiter.length();
        int index = 0;
        int lastPosition = startReaderIndex;
        byte prevByte = HttpConstants.LF;
        boolean delimiterFound = false;
        while (undecodedChunk.isReadable()) {
            final byte nextByte = undecodedChunk.readByte();
            // Check the delimiter
            if (prevByte == HttpConstants.LF && nextByte == delimiter.codePointAt(index)) {
                index++;
                if (delimeterLength == index) {
                    delimiterFound = true;
                    break;
                }
                continue;
            }
            lastPosition = undecodedChunk.readerIndex();
            if (nextByte == HttpConstants.LF) {
                index = 0;
                lastPosition -= (prevByte == HttpConstants.CR)? 2 : 1;
            }
            prevByte = nextByte;
        }
        if (prevByte == HttpConstants.CR) {
            lastPosition--;
        }
        ByteBuf content = undecodedChunk.copy(startReaderIndex, lastPosition - startReaderIndex);
        try {
            httpData.addContent(content, delimiterFound);
        } catch (IOException e) {
            throw new ErrorDataDecoderException(e);
        }
        undecodedChunk.readerIndex(lastPosition);
        return delimiterFound;
    }
983913
def _parse_allow(allow):
    '''
    
    '''
    # input=> tcp:53,tcp:80,tcp:443,icmp,tcp:4201,udp:53
    # output<= [
    #     {"IPProtocol": "tcp", "ports": ["53","80","443","4201"]},
    #     {"IPProtocol": "icmp"},
    #     {"IPProtocol": "udp", "ports": ["53"]},
    # ]
    seen_protos = {}
    allow_dict = []
    protocols = allow.split(',')
    for p in protocols:
        pairs = p.split(':')
        if pairs[0].lower() not in ['tcp', 'udp', 'icmp']:
            raise SaltCloudSystemExit(
                'Unsupported protocol {0}. Must be tcp, udp, or icmp.'.format(
                    pairs[0]
                )
            )
        if len(pairs) == 1 or pairs[0].lower() == 'icmp':
            seen_protos[pairs[0]] = []
        else:
            if pairs[0] not in seen_protos:
                seen_protos[pairs[0]] = [pairs[1]]
            else:
                seen_protos[pairs[0]].append(pairs[1])
    for k in seen_protos:
        d = {'IPProtocol': k}
        if seen_protos[k]:
            d['ports'] = seen_protos[k]
        allow_dict.append(d)
    log.debug("firewall allowed protocols/ports: %s", allow_dict)
    return allow_dict
1124000
@Override
    public String loadDataFromNetwork() throws Exception {
        try {
            Ln.d("Call web service " + url);
            return IOUtils.toString(new InputStreamReader(new URL(url).openStream(), CharEncoding.UTF_8));
        } catch (final MalformedURLException e) {
            Ln.e(e, "Unable to create URL");
            throw e;
        } catch (final IOException e) {
            Ln.e(e, "Unable to download content");
            throw e;
        }
    }
1213459
@CheckForNull
    public static Secret decrypt(@CheckForNull String data) {
        if(!isValidData(data))      return null;

        if (data.startsWith("{") && data.endsWith("}")) { //likely CBC encrypted/containing metadata but could be plain text
            byte[] payload;
            try {
                payload = Base64.getDecoder().decode(data.substring(1, data.length()-1));
            } catch (IllegalArgumentException e) {
                return null;
            }
            switch (payload[0]) {
                case PAYLOAD_V1:
                    // For PAYLOAD_V1 we use this byte shifting model, V2 probably will need DataOutput
                    int ivLength = ((payload[1] & 0xff) << 24)
                            | ((payload[2] & 0xff) << 16)
                            | ((payload[3] & 0xff) << 8)
                            | (payload[4] & 0xff);
                    int dataLength = ((payload[5] & 0xff) << 24)
                            | ((payload[6] & 0xff) << 16)
                            | ((payload[7] & 0xff) << 8)
                            | (payload[8] & 0xff);
                    if (payload.length != 1 + 8 + ivLength + dataLength) {
                        // not valid v1
                        return null;
                    }
                    byte[] iv = Arrays.copyOfRange(payload, 9, 9 + ivLength);
                    byte[] code = Arrays.copyOfRange(payload, 9+ivLength, payload.length);
                    String text;
                    try {
                        text = new String(KEY.decrypt(iv).doFinal(code), UTF_8);
                    } catch (GeneralSecurityException e) {
                        // it's v1 which cannot be historical, but not decrypting
                        return null;
                    }
                    return new Secret(text, iv);
                default:
                    return null;
            }
        } else {
            try {
                return HistoricalSecrets.decrypt(data, KEY);
            } catch (UnsupportedEncodingException e) {
                throw new Error(e); // impossible
            } catch (GeneralSecurityException | IOException e) {
                return null;
            }
        }
    }
946016
@Nullable protected byte[] decode(@Nullable String data) {
    return data == null ? null : Base64.getUrlDecoder().decode(data);
  }
401820
public function makeThrowable(Data $data): ?ExceptionFormat
    {
        if (!$data->isThrowable()) {
            return null;
        }

        return ExceptionFormat::make($data->getValue());
    }
736563
function getRowBytesFromTransactionBase64(base64Data) {
  let bytesDecode = base64DecodeFromString(base64Data);
  let transaction = proto.protocol.Transaction.deserializeBinary(bytesDecode);
  let raw = transaction.getRawData();
  return raw.serializeBinary();
}
1040959
public static boolean couldBeSipMessage(final Buffer data) throws IOException {
        if (data.getReadableBytes() < 4) {
            return false;
        }

        final byte a = data.getByte(0);
        final byte b = data.getByte(1);
        final byte c = data.getByte(2);
        final byte d = data.getByte(3);
        return a == 'S' && b == 'I' && c == 'P'              || // response
               a == 'I' && b == 'N' && c == 'V' && d == 'I' || // INVITE
               a == 'A' && b == 'C' && c == 'K'             || // ACK
               a == 'B' && b == 'Y' && c == 'E'             || // BYE
               a == 'O' && b == 'P' && c == 'T' && d == 'I' || // OPTIONS
               a == 'C' && b == 'A' && c == 'N' && d == 'C' || // CANCEL
               a == 'M' && b == 'E' && c == 'S' && d == 'S' || // MESSAGE
               a == 'R' && b == 'E' && c == 'G' && d == 'I' || // REGISTER
               a == 'I' && b == 'N' && c == 'F' && d == 'O' || // INFO
               a == 'P' && b == 'R' && c == 'A' && d == 'C' || // PRACK
               a == 'S' && b == 'U' && c == 'B' && d == 'S' || // SUBSCRIBE
               a == 'N' && b == 'O' && c == 'T' && d == 'I' || // NOTIFY
               a == 'U' && b == 'P' && c == 'D' && d == 'A' || // UPDATE
               a == 'R' && b == 'E' && c == 'F' && d == 'E' || // REFER
               a == 'P' && b == 'U' && c == 'B' && d == 'L' ; // PUBLISH

    }
627973
private static Data checkData(final Data data) {
		if (Data.EMPTY.equals(data)) {
			throw new IllegalStateException("Argument 'data' must not be empty.");
		}
		return data;
	}
873790
@SuppressWarnings("unchecked")
    public static <T> T fromByteArrayKryo(byte[] data, Class<T> clazz, ClassLoader classLoader) {
        if (data == null) {
            return null;
        }
        Kryo kryo = kryoPool.obtain();
        try {
            ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
            if (classLoader != null) {
                Thread.currentThread().setContextClassLoader(classLoader);
            }
            try {
                Input input = kryoInputPool.obtain();
                try {
                    kryo.setClassLoader(classLoader != null ? classLoader : oldClassLoader);
                    input.setInputStream(new ByteArrayInputStream(data));
                    Object obj = kryo.readClassAndObject(input);
                    input.close();
                    return obj != null && clazz.isAssignableFrom(obj.getClass()) ? (T) obj : null;
                } finally {
                    kryoInputPool.free(input);
                }
            } finally {
                Thread.currentThread().setContextClassLoader(oldClassLoader);
            }
        } finally {
            kryoPool.free(kryo);
        }
    }
1351400
@Override
	protected void readDataBlock(byte[] data, int offset, int len, int blockHandle) throws DataStoreException
    {
		try
		{
	        dataRandomAccessFile.seek((long)blockHandle*blockSize);
	        if (dataRandomAccessFile.read(data,offset,len) != len)
	            throw new DataStoreException("Cannot read "+len+" bytes from store file");
		}
		catch (DataStoreException e)
		{
		    throw e;
		}
        catch (IOException e)
        {
            throw new DataStoreException("Could not read data block "+blockHandle+" : "+dataFile.getAbsolutePath(),e);
        }
    }