Java Code Examples for com.google.common.primitives.Ints#fromByteArray()
The following examples show how to use
com.google.common.primitives.Ints#fromByteArray() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NameSale.java From Qora with MIT License | 6 votes |
public static NameSale Parse(byte[] data) throws Exception { int position = 0; //READ NAME byte[] nameLengthBytes = Arrays.copyOfRange(data, position, position + NAME_SIZE_LENGTH); int nameLength = Ints.fromByteArray(nameLengthBytes); position += NAME_SIZE_LENGTH; if(nameLength < 1 || nameLength > 400) { throw new Exception("Invalid name length"); } byte[] nameBytes = Arrays.copyOfRange(data, position, position + nameLength); String nameName = new String(nameBytes, StandardCharsets.UTF_8); position += nameLength; //READ AMOUNT byte[] amountBytes = Arrays.copyOfRange(data, position, position + AMOUNT_LENGTH); BigDecimal amount = new BigDecimal(new BigInteger(amountBytes), 8); position += AMOUNT_LENGTH; return new NameSale(nameName, amount); }
Example 2
Source File: JobWithState.java From twister2 with Apache License 2.0 | 6 votes |
public static JobWithState decode(byte[] encodedBytes) { if (encodedBytes == null) { return null; } // first 4 bytes is the length of job state int stateLength = Ints.fromByteArray(encodedBytes); String stateName = new String(encodedBytes, 4, stateLength); JobAPI.JobState state = JobAPI.JobState.valueOf(stateName); try { JobAPI.Job job = JobAPI.Job.newBuilder() .mergeFrom(encodedBytes, 4 + stateLength, encodedBytes.length - 4 - stateLength) .build(); return new JobWithState(job, state); } catch (InvalidProtocolBufferException e) { LOG.log(Level.SEVERE, "Could not decode received byte array as a JobAPI.Job object", e); return null; } }
Example 3
Source File: Decoder.java From xio with Apache License 2.0 | 6 votes |
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // uuid byte[] uuidBytes = new byte[36]; in.readBytes(uuidBytes); UUID id = UUID.fromString(new String(uuidBytes)); // op byte[] opBytes = new byte[4]; in.readBytes(opBytes); Message.Op op = Message.Op.fromBytes(opBytes); // payloadSize byte[] payloadSizeBytes = new byte[4]; in.readBytes(payloadSizeBytes); int payloadSize = Ints.fromByteArray(payloadSizeBytes); if (in.readableBytes() < payloadSize) { ctx.fireExceptionCaught(new DecoderException("Not enough bytes available to decode payload")); } out.add(in.readRetainedSlice(payloadSize)); out.add(new Message(id, op)); }
Example 4
Source File: DAGFinishedEvent.java From incubator-tez with Apache License 2.0 | 5 votes |
@Override public void fromSummaryProtoStream(SummaryEventProto proto) throws IOException { this.dagID = TezDAGID.fromString(proto.getDagId()); this.finishTime = proto.getTimestamp(); this.state = DAGState.values()[ Ints.fromByteArray(proto.getEventPayload().toByteArray())]; }
Example 5
Source File: DoubleClickCrypto.java From openrtb-doubleclick with Apache License 2.0 | 5 votes |
/** * {@code signature = hmac(integrityKey, payload || initVector)} */ private int hmacSignature(byte[] workBytes) { try { Mac integrityHmac = createMac(); integrityHmac.init(keys.getIntegrityKey()); integrityHmac.update(workBytes, PAYLOAD_BASE, workBytes.length - OVERHEAD_SIZE); integrityHmac.update(workBytes, INITV_BASE, INITV_SIZE); return Ints.fromByteArray(integrityHmac.doFinal()); } catch (InvalidKeyException e) { throw new IllegalStateException(e); } }
Example 6
Source File: VEXBlock.java From osm-lib with BSD 2-Clause "Simplified" License | 5 votes |
/** */ private void readHeader(InputStream in) { byte[] fourBytes = new byte[4]; try { int nRead = ByteStreams.read(in, fourBytes, 0, 4); if (nRead == 0) { // ByteStreams.read attempts to fully read 4 bytes and returns the number of bytes read, // which is only less than 4 if upstream.read() returned a negative value (EOF). LOG.debug("Hit end of file, no more blocks to read."); nBytes = 0; entityType = VexFormat.VEX_NONE; // indicates no more blocks return; } String s = new String(fourBytes); if (s.equals("VEXN")) { entityType = VexFormat.VEX_NODE; } else if (s.equals("VEXW")) { entityType = VexFormat.VEX_WAY; } else if (s.equals("VEXR")) { entityType = VexFormat.VEX_RELATION; } else { LOG.error("Unrecognized block type '{}', aborting VEX read.", entityType); throw new RuntimeException("Uncrecoginzed VEX block type."); } ByteStreams.readFully(in, fourBytes); nEntities = Ints.fromByteArray(fourBytes); ByteStreams.readFully(in, fourBytes); nBytes = Ints.fromByteArray(fourBytes); if (nBytes < 0 || nBytes > BUFFER_SIZE) { throw new RuntimeException("Block has impossible compressed data size, it is probably corrupted."); } if (nEntities < 0 || nEntities > BUFFER_SIZE) { throw new RuntimeException("Block contains impossible number of entities, it is probably corrupted."); } } catch (IOException e) { throw new RuntimeException(e); } }
Example 7
Source File: MultiAttemptDAG.java From incubator-tez with Apache License 2.0 | 5 votes |
public void fromUserPayload(byte[] userPayload) { int failInt = Ints.fromByteArray(userPayload); if (failInt == 0) { failOnCommit = false; } else { failOnCommit = true; } }
Example 8
Source File: WorkerWithState.java From twister2 with Apache License 2.0 | 5 votes |
public static WorkerWithState decode(byte[] encodedBytes) { if (encodedBytes == null) { return null; } // first 4 bytes is the length of worker state int stateLength = Ints.fromByteArray(encodedBytes); String stateName = new String(encodedBytes, 4, stateLength); WorkerState workerState = WorkerState.valueOf(stateName); // next 4 bytes is restartCount int rcIndex = 4 + stateLength; int restartCount = Ints.fromBytes(encodedBytes[rcIndex], encodedBytes[rcIndex + 1], encodedBytes[rcIndex + 2], encodedBytes[rcIndex + 3]); // remaining bytes are WorkerInfo object int workerInfoLength = encodedBytes.length - 4 - stateLength - 4; int workerInfoIndex = rcIndex + 4; try { WorkerInfo workerInfo = WorkerInfo.newBuilder() .mergeFrom(encodedBytes, workerInfoIndex, workerInfoLength) .build(); return new WorkerWithState(workerInfo, workerState, restartCount); } catch (InvalidProtocolBufferException e) { LOG.log(Level.SEVERE, "Could not decode received byte array as a WorkerInfo object", e); return null; } }
Example 9
Source File: ProtobufHandler.java From ja-micro with Apache License 2.0 | 5 votes |
private RpcEnvelope.Request readRpcEnvelope(ServletInputStream in) throws Exception { byte chunkSize[] = new byte[4]; in.read(chunkSize); int size = Ints.fromByteArray(chunkSize); if (size <= 0 || size > ProtobufUtil.MAX_HEADER_CHUNK_SIZE) { String message = "Invalid header chunk size: " + size; throw new RpcReadException(chunkSize, in, message); } byte headerData[] = readyFully(in, size); RpcEnvelope.Request rpcRequest = RpcEnvelope.Request.parseFrom(headerData); return rpcRequest; }
Example 10
Source File: ProtobufRpcResponse.java From ja-micro with Apache License 2.0 | 5 votes |
public ProtobufRpcResponse(byte[] data) throws RpcCallException { //we may get a json error even though we make a protobuf call if (data[0] == '{' && data[data.length - 1] == '}') { readRpcError(new String(data)); return; } int headerLength = Ints.fromByteArray(data); if (headerLength < 0 || headerLength > MAX_HEADER_SIZE) { StringBuilder sb = new StringBuilder(); sb.append("Unexpected header length: ").append(headerLength). append(", data: ").append(ensurePrintable(data, 256)); String message = sb.toString(); logger.warn(message); throw new RpcCallException(RpcCallException.Category.InternalServerError, message); } logger.debug("headerLength = {}", headerLength); int offset = 4; byte headerData[] = Arrays.copyOfRange(data, offset, offset + headerLength); offset += headerLength; byte payloadLengthBuffer[] = Arrays.copyOfRange(data, offset, offset + 4); offset += 4; int payloadLength = Ints.fromByteArray(payloadLengthBuffer); payloadData = Arrays.copyOfRange(data, offset, offset + payloadLength); RpcEnvelope.Response responseHeader = ProtobufUtil. byteArrayToProtobuf(headerData, RpcEnvelope.Response.class); serviceMethod = responseHeader.getServiceMethod(); sequenceNumber = responseHeader.getSequenceNumber(); errorMessage = responseHeader.getError(); }
Example 11
Source File: AppSharedPreference.java From bither-android with Apache License 2.0 | 5 votes |
public void setPinCode(CharSequence code) { if (code == null || code.length() == 0) { deletePinCode(); return; } int salt = Ints.fromByteArray(new URandom().nextBytes(Ints.BYTES)); String hash = Integer.toString(salt) + ";" + Integer.toString((code.toString() + Integer .toString(salt)).hashCode()); mPreferences.edit().putString(PIN_CODE, hash).commit(); }
Example 12
Source File: PeersMessage.java From Qora with MIT License | 5 votes |
public static PeersMessage parse(byte[] data) throws Exception { //READ LENGTH byte[] lengthBytes = Arrays.copyOfRange(data, 0, DATA_LENGTH); int length = Ints.fromByteArray(lengthBytes); //CHECK IF DATA MATCHES LENGTH if(data.length != DATA_LENGTH + (length * ADDRESS_LENGTH)) { throw new Exception("Data does not match length"); } //CREATE PEER LIST List<Peer> peers = new ArrayList<Peer>(); for(int i=0; i<length; i++) { //CALCULATE POSITION int position = lengthBytes.length + (i * ADDRESS_LENGTH); //READ ADDRESS byte[] addressBytes = Arrays.copyOfRange(data, position, position + ADDRESS_LENGTH); InetAddress address = InetAddress.getByAddress(addressBytes); //CREATE PEER Peer peer = new Peer(address); //ADD TO LIST peers.add(peer); } return new PeersMessage(peers); }
Example 13
Source File: TestRocksDbKeyValueStoreJava.java From samza with Apache License 2.0 | 5 votes |
@Test public void testIterate() throws Exception { Config config = new MapConfig(); Options options = new Options(); options.setCreateIfMissing(true); File dbDir = new File(System.getProperty("java.io.tmpdir") + "/dbStore" + System.currentTimeMillis()); RocksDbKeyValueStore store = new RocksDbKeyValueStore(dbDir, options, config, false, "dbStore", new WriteOptions(), new FlushOptions(), new KeyValueStoreMetrics("dbStore", new MetricsRegistryMap())); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String prefix = "prefix"; for (int i = 0; i < 100; i++) { store.put(genKey(outputStream, prefix, i), genValue()); } byte[] firstKey = genKey(outputStream, prefix, 0); byte[] lastKey = genKey(outputStream, prefix, 1000); KeyValueSnapshot<byte[], byte[]> snapshot = store.snapshot(firstKey, lastKey); // Make sure the cached Iterable won't change when new elements are added store.put(genKey(outputStream, prefix, 200), genValue()); KeyValueIterator<byte[], byte[]> iterator = snapshot.iterator(); assertTrue(Iterators.size(iterator) == 100); iterator.close(); List<Integer> keys = new ArrayList<>(); KeyValueIterator<byte[], byte[]> iterator2 = snapshot.iterator(); while (iterator2.hasNext()) { Entry<byte[], byte[]> entry = iterator2.next(); int key = Ints.fromByteArray(Arrays.copyOfRange(entry.getKey(), prefix.getBytes().length, entry.getKey().length)); keys.add(key); } assertEquals(keys, IntStream.rangeClosed(0, 99).boxed().collect(Collectors.toList())); iterator2.close(); outputStream.close(); snapshot.close(); store.close(); }
Example 14
Source File: BlockMessage.java From Qora with MIT License | 5 votes |
public static BlockMessage parse(byte[] data) throws Exception { //PARSE HEIGHT byte[] heightBytes = Arrays.copyOfRange(data, 0, HEIGHT_LENGTH); int height = Ints.fromByteArray(heightBytes); //PARSE BLOCK Block block = Block.parse(Arrays.copyOfRange(data, HEIGHT_LENGTH, data.length + 1)); //CREATE MESSAGE BlockMessage message = new BlockMessage(block); message.height = height; return message; }
Example 15
Source File: BytesUtilsTest.java From pinpoint with Apache License 2.0 | 5 votes |
private void checkInt(int i) { byte[] bytes = Ints.toByteArray(i); int i2 = BytesUtils.bytesToInt(bytes, 0); Assert.assertEquals(i, i2); int i3 = Ints.fromByteArray(bytes); Assert.assertEquals(i, i3); }
Example 16
Source File: DAGFinishedEvent.java From tez with Apache License 2.0 | 5 votes |
@Override public void fromSummaryProtoStream(SummaryEventProto proto) throws IOException { this.dagID = TezDAGID.fromString(proto.getDagId()); this.finishTime = proto.getTimestamp(); this.state = DAGState.values()[ Ints.fromByteArray(proto.getEventPayload().toByteArray())]; }
Example 17
Source File: CommitMarkerCodec.java From phoenix-tephra with Apache License 2.0 | 5 votes |
public int readMarker(SequenceFile.Reader reader) throws IOException { if (valueBytes == null) { valueBytes = reader.createValueBytes(); } rawKey.reset(); rawValue.reset(); // valueBytes need not be reset since nextRaw call does it (and it is a private method) int status = reader.nextRaw(rawKey, valueBytes); // if we reach EOF, return -1 if (status == -1) { return -1; } // Check if the marker key is valid and return the count if (isMarkerValid()) { valueBytes.writeUncompressedBytes(rawValue); rawValue.flush(); // rawValue.getData() may return a larger byte array but Ints.fromByteArray will only read the first four bytes return Ints.fromByteArray(rawValue.getData()); } // EOF not reached and marker is not valid, then thrown an IOException since we can't make progress throw new IOException(String.format("Invalid key for num entries appended found %s, expected : %s", new String(rawKey.getData()), TxConstants.TransactionLog.NUM_ENTRIES_APPENDED)); }
Example 18
Source File: MultiPaymentTransaction.java From Qora with MIT License | 4 votes |
public static Transaction Parse(byte[] data) throws Exception{ //CHECK IF WE MATCH BLOCK LENGTH if(data.length < BASE_LENGTH) { throw new Exception("Data does not match block length"); } int position = 0; //READ TIMESTAMP byte[] timestampBytes = Arrays.copyOfRange(data, position, position + TIMESTAMP_LENGTH); long timestamp = Longs.fromByteArray(timestampBytes); position += TIMESTAMP_LENGTH; //READ REFERENCE byte[] reference = Arrays.copyOfRange(data, position, position + REFERENCE_LENGTH); position += REFERENCE_LENGTH; //READ SENDER byte[] senderBytes = Arrays.copyOfRange(data, position, position + SENDER_LENGTH); PublicKeyAccount sender = new PublicKeyAccount(senderBytes); position += SENDER_LENGTH; //READ PAYMENTS SIZE byte[] paymentsLengthBytes = Arrays.copyOfRange(data, position, position + PAYMENTS_SIZE_LENGTH); int paymentsLength = Ints.fromByteArray(paymentsLengthBytes); position += PAYMENTS_SIZE_LENGTH; if(paymentsLength < 1 || paymentsLength > 400) { throw new Exception("Invalid payments length"); } //READ PAYMENTS List<Payment> payments = new ArrayList<Payment>(); for(int i=0; i<paymentsLength; i++) { Payment payment = Payment.parse(Arrays.copyOfRange(data, position, position + Payment.BASE_LENGTH)); payments.add(payment); position += Payment.BASE_LENGTH; } //READ FEE byte[] feeBytes = Arrays.copyOfRange(data, position, position + FEE_LENGTH); BigDecimal fee = new BigDecimal(new BigInteger(feeBytes), 8); position += FEE_LENGTH; //READ SIGNATURE byte[] signatureBytes = Arrays.copyOfRange(data, position, position + SIGNATURE_LENGTH); return new MultiPaymentTransaction(sender, payments, fee, timestamp, reference, signatureBytes); }
Example 19
Source File: Poll.java From Qora with MIT License | 4 votes |
public static Poll parse(byte[] data) throws Exception { int position = 0; //READ CREATOR byte[] creatorBytes = Arrays.copyOfRange(data, position, position + CREATOR_LENGTH); Account creator = new Account(Base58.encode(creatorBytes)); position += CREATOR_LENGTH; //READ NAME SIZE byte[] nameLengthBytes = Arrays.copyOfRange(data, position, position + NAME_SIZE_LENGTH); int nameLength = Ints.fromByteArray(nameLengthBytes); position += NAME_SIZE_LENGTH; if(nameLength < 1 || nameLength > 400) { throw new Exception("Invalid name length"); } //READ NAME byte[] nameBytes = Arrays.copyOfRange(data, position, position + nameLength); String name = new String(nameBytes, StandardCharsets.UTF_8); position += nameLength; //READ DESCRIPTION byte[] descriptionLengthBytes = Arrays.copyOfRange(data, position, position + DESCRIPTION_SIZE_LENGTH); int descriptionLength = Ints.fromByteArray(descriptionLengthBytes); position += DESCRIPTION_SIZE_LENGTH; if(descriptionLength < 1 || descriptionLength > 4000) { throw new Exception("Invalid description length"); } byte[] descriptionBytes = Arrays.copyOfRange(data, position, position + descriptionLength); String description = new String(descriptionBytes, StandardCharsets.UTF_8); position += descriptionLength; //READ OPTIONS SIZE byte[] optionsLengthBytes = Arrays.copyOfRange(data, position, position + OPTIONS_SIZE_LENGTH); int optionsLength = Ints.fromByteArray(optionsLengthBytes); position += OPTIONS_SIZE_LENGTH; if(optionsLength < 1 || optionsLength > 100) { throw new Exception("Invalid options length"); } //READ OPTIONS List<PollOption> options = new ArrayList<PollOption>(); for(int i=0; i<optionsLength; i++) { PollOption option = PollOption.parse(Arrays.copyOfRange(data, position, data.length)); position += option.getDataLength(); options.add(option); } return new Poll(creator, name, description, options); }
Example 20
Source File: IntOption.java From dhcp4j with Apache License 2.0 | 4 votes |
public int getValue() { return Ints.fromByteArray(getData()); }