com.google.common.primitives.Ints Java Examples
The following examples show how to use
com.google.common.primitives.Ints.
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: MetastoreHiveStatisticsProvider.java From presto with Apache License 2.0 | 6 votes |
private static long normalizeIntegerValue(Type type, long value) { if (type.equals(BIGINT)) { return value; } if (type.equals(INTEGER)) { return Ints.saturatedCast(value); } if (type.equals(SMALLINT)) { return Shorts.saturatedCast(value); } if (type.equals(TINYINT)) { return SignedBytes.saturatedCast(value); } throw new IllegalArgumentException("Unexpected type: " + type); }
Example #2
Source File: Shape.java From nd4j with Apache License 2.0 | 6 votes |
/** * Compute the broadcast rules according to: * https://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html * * Note that the array can be null if the arrays are already equal * in shape. * * This function should be used in conjunction with * the shape ops. * * @param left the left array * @param right the right array (the array to be broadcasted * @return the broadcast dimensions if any */ public static int[] getBroadcastDimensions(int[] left,int[] right) { if(Arrays.equals(left,right)) return null; int n = Math.min(left.length,right.length); List<Integer> dims = new ArrayList<>(); int leftIdx = left.length - 1; int rightIdx = right.length - 1; for(int i = n - 1; i >= 0; i--) { if(left[leftIdx] != right[rightIdx] && right[rightIdx] == 1 || left[leftIdx] == 1) { dims.add(i); } else if(left[leftIdx] != right[rightIdx]) { throw new IllegalArgumentException("Unable to broadcast dimension " + i + " due to shape mismatch. Right shape must be 1. " + "Left array shape: " + Arrays.toString(left) + ", right array shape: " + Arrays.toString(right)); } leftIdx--; rightIdx--; } Collections.reverse(dims); return Ints.toArray(dims); }
Example #3
Source File: ObjectStoreDeleteConverter.java From incubator-gobblin with Apache License 2.0 | 6 votes |
@Override public Iterable<ObjectStoreDeleteOperation> convertRecord(Class<?> outputSchema, GenericRecord inputRecord, WorkUnitState workUnit) throws DataConversionException { Optional<Object> fieldValue = AvroUtils.getFieldValue(inputRecord, this.objectIdField); byte[] objectId; if (fieldValue.isPresent()) { if (fieldValue.get() instanceof Utf8) { objectId = ((Utf8) fieldValue.get()).getBytes(); } else if (fieldValue.get() instanceof String) { objectId = ((String) fieldValue.get()).getBytes(Charsets.UTF_8); } else if (fieldValue.get() instanceof Long) { objectId = Longs.toByteArray((Long) fieldValue.get()); } else if (fieldValue.get() instanceof Integer) { objectId = Ints.toByteArray((Integer) fieldValue.get()); } else { objectId = (byte[]) fieldValue.get(); } return new SingleRecordIterable<ObjectStoreDeleteOperation>(ObjectStoreOperationBuilder.deleteBuilder() .withObjectId(objectId).build()); } else { throw new DataConversionException(String.format("Object Id field %s not found in record %s", this.objectIdField, inputRecord)); } }
Example #4
Source File: InetAddresses.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Returns the string representation of an {@link InetAddress}. * * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6 * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section * 4. The main difference is that this method uses "::" for zero compression, while Java's version * uses the uncompressed form. * * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses * such as "::c000:201". The output does not include a Scope ID. * * @param ip {@link InetAddress} to be converted to an address string * @return {@code String} containing the text-formatted IP address * @since 10.0 */ public static String toAddrString(InetAddress ip) { Preconditions.checkNotNull(ip); if (ip instanceof Inet4Address) { // For IPv4, Java's formatting is good enough. return ip.getHostAddress(); } Preconditions.checkArgument(ip instanceof Inet6Address); byte[] bytes = ip.getAddress(); int[] hextets = new int[IPV6_PART_COUNT]; for (int i = 0; i < hextets.length; i++) { hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]); } compressLongestRunOfZeroes(hextets); return hextetsToIPv6String(hextets); }
Example #5
Source File: LaunchNotice.java From nomulus with Apache License 2.0 | 6 votes |
/** * Validate the checksum of the notice against the domain label. */ public void validate(String domainLabel) throws InvalidChecksumException { // According to http://tools.ietf.org/html/draft-lozano-tmch-func-spec-08#section-6.3, a TCNID // is always 8 chars of checksum + 19 chars of a decimal notice id. Check the length before // taking substrings to avoid an IndexOutOfBoundsException. String tcnId = getNoticeId().getTcnId(); checkArgument(tcnId.length() == 27); int checksum = Ints.fromByteArray(base16().decode(Ascii.toUpperCase(tcnId.substring(0, 8)))); String noticeId = tcnId.substring(8); checkArgument(CharMatcher.inRange('0', '9').matchesAllOf(noticeId)); // The checksum in the first 8 chars must match the crc32 of label + expiration + notice id. String stringToHash = domainLabel + MILLISECONDS.toSeconds(getExpirationTime().getMillis()) + noticeId; int computedChecksum = crc32().hashString(stringToHash, UTF_8).asInt(); if (checksum != computedChecksum) { throw new InvalidChecksumException(); } }
Example #6
Source File: TargetManagementSearchTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Step private void verifyThat99TargetsWithNameOrDescriptionAreInGivenStatus(final List<TargetUpdateStatus> unknown, final List<Target> expected) { final String query = "updatestatus==unknown and (name==*targ-A* or description==*targ-A*)"; assertThat(targetManagement .findByFilters(PAGE, new FilterParams(unknown, null, "%targ-A%", null, Boolean.FALSE, new String[0])) .getContent()).as("has number of elements").hasSize(99) .as("that number is also returned by count query") .hasSize(Ints.saturatedCast(targetManagement.countByFilters(unknown, null, "%targ-A%", null, Boolean.FALSE, new String[0]))) .as("and contains the following elements").containsAll(expected) .as("and filter query returns the same result") .containsAll(targetManagement.findByRsql(PAGE, query).getContent()); }
Example #7
Source File: CTracesNodeComponent.java From binnavi with Apache License 2.0 | 6 votes |
/** * Shows a popup menu for a given mouse event. * * @param event The event that triggered the popup menu. */ private void showPopupMenu(final MouseEvent event) { final JTable traceTable = m_tracesPanel.getTracesTable(); final int mouseRow = traceTable.rowAtPoint(event.getPoint()); if (mouseRow != -1) { final int[] rows = traceTable.getSelectedRows(); if (Ints.asList(rows).indexOf(mouseRow) != -1) { traceTable.setRowSelectionInterval(mouseRow, mouseRow); } } // Make sure at least one row is selected final int minIndex = m_tracesPanel.getTracesTable().getSelectionModel().getMinSelectionIndex(); if (minIndex != -1) { final JPopupMenu popupMenu = new CEventListTableMenu( (JFrame) SwingUtilities.getWindowAncestor(CTracesNodeComponent.this), m_tracesPanel.getTracesTable(), m_container.getTraceProvider()); popupMenu.show(m_tracesPanel.getTracesTable(), event.getX(), event.getY()); } }
Example #8
Source File: PollOption.java From Qora with MIT License | 6 votes |
public byte[] toBytes() { byte[] data = new byte[0]; //WRITE NAME SIZE byte[] nameBytes = this.name.getBytes(StandardCharsets.UTF_8); int nameLength = nameBytes.length; byte[] nameLengthBytes = Ints.toByteArray(nameLength); data = Bytes.concat(data, nameLengthBytes); //WRITE NAME data = Bytes.concat(data, nameBytes); //WRITE VOTERS SIZE int votersLength = this.voters.size(); byte[] votersLengthBytes = Ints.toByteArray(votersLength); data = Bytes.concat(data, votersLengthBytes); //WRITE VOTERS for(Account voter: this.voters) { data = Bytes.concat(data, Base58.decode(voter.getAddress())); } return data; }
Example #9
Source File: Skill.java From rs-api with ISC License | 6 votes |
/** * Creates a {@link Skill} from a {@link CSVRecord}. * @param record The record. * @return The {@link Skill} or {@link Optional#empty()} if the record was invalid. */ public static Optional<Skill> fromCsv(CSVRecord record) { if (record.size() < 3) { return Optional.empty(); } Integer rank = Ints.tryParse(record.get(0)); if (rank == null) { return Optional.empty(); } Integer level = Ints.tryParse(record.get(1)); if (level == null) { return Optional.empty(); } Long experience = Longs.tryParse(record.get(2)); if (experience == null) { return Optional.empty(); } return Optional.of(new Skill(rank, level, experience)); }
Example #10
Source File: InetAddresses.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Returns the string representation of an {@link InetAddress}. * * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6 * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section * 4. The main difference is that this method uses "::" for zero compression, while Java's version * uses the uncompressed form. * * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses * such as "::c000:201". The output does not include a Scope ID. * * @param ip {@link InetAddress} to be converted to an address string * @return {@code String} containing the text-formatted IP address * @since 10.0 */ public static String toAddrString(InetAddress ip) { Preconditions.checkNotNull(ip); if (ip instanceof Inet4Address) { // For IPv4, Java's formatting is good enough. return ip.getHostAddress(); } Preconditions.checkArgument(ip instanceof Inet6Address); byte[] bytes = ip.getAddress(); int[] hextets = new int[IPV6_PART_COUNT]; for (int i = 0; i < hextets.length; i++) { hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]); } compressLongestRunOfZeroes(hextets); return hextetsToIPv6String(hextets); }
Example #11
Source File: CassandraConfiguration.java From cassandra-jdbc-driver with Apache License 2.0 | 6 votes |
private void init() { int tentativePort = config.port; Splitter splitter = Splitter.on(':').trimResults().omitEmptyStrings().limit(2); StringBuilder sb = new StringBuilder(); for (String host : Splitter.on(',').trimResults().omitEmptyStrings().split( config.hosts)) { List<String> h = splitter.splitToList(host); sb.append(h.get(0)).append(','); if (h.size() > 1 && tentativePort <= 0) { tentativePort = Ints.tryParse(h.get(1)); } } config.hosts = sb.deleteCharAt(sb.length() - 1).toString(); config.port = tentativePort; // update timeouts config.connectionTimeout = config.connectionTimeout * 1000; config.readTimeout = config.readTimeout * 1000; }
Example #12
Source File: JtableUtils.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 6 votes |
/** * deletes all selected columns if it is not present in the <code>exp</code> * List * * @param table the table to DELETE columns * @param exp columns to avoid deleting * @see #deletecol(javax.swing.JTable, int) */ static void deletecols(JTable table, int[] exp) { Integer[] selcols; try { TableColumnModel tcm = table.getColumnModel(); selcols = ArrayUtils.toObject(table.getSelectedColumns()); Arrays.sort(selcols, Collections.reverseOrder()); List<Integer> explist = Ints.asList(exp); for (int i : selcols) { if (!explist.contains(i)) { tcm.removeColumn(tcm.getColumn(i)); } } } catch (Exception e) { Logger.getLogger(JtableUtils.class.getName()).log(Level.SEVERE, null, e); } }
Example #13
Source File: BeatsFrameDecoder.java From graylog-plugin-beats with GNU General Public License v3.0 | 6 votes |
/** * @see <a href="https://github.com/logstash-plugins/logstash-input-beats/blob/master/PROTOCOL.md#data-frame-type">'data' frame type</a> */ private Collection<ByteBuf> parseDataFrame(Channel channel, ByteBuf channelBuffer) throws IOException { sequenceNum = channelBuffer.readUnsignedInt(); LOG.trace("Received sequence number {}", sequenceNum); final int pairs = Ints.saturatedCast(channelBuffer.readUnsignedInt()); final JsonFactory jsonFactory = new JsonFactory(); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (final JsonGenerator jg = jsonFactory.createGenerator(outputStream)) { jg.writeStartObject(); for (int i = 0; i < pairs; i++) { final String key = parseDataItem(channelBuffer); final String value = parseDataItem(channelBuffer); jg.writeStringField(key, value); } jg.writeEndObject(); } final ByteBuf buffer = Unpooled.wrappedBuffer(outputStream.toByteArray()); sendACK(channel); return Collections.singleton(buffer); }
Example #14
Source File: HiscoreActivity.java From rs-api with ISC License | 6 votes |
/** * Creates a {@link HiscoreActivity} from a {@link CSVRecord}. * @param record The record. * @return The {@link HiscoreActivity} or {@link Optional#empty()} if the record was invalid. */ public static Optional<HiscoreActivity> fromCsv(CSVRecord record) { if (record.size() < 2) { return Optional.empty(); } Integer rank = Ints.tryParse(record.get(0)); if (rank == null) { return Optional.empty(); } Integer score = Ints.tryParse(record.get(1)); if (score == null) { return Optional.empty(); } return Optional.of(new HiscoreActivity(rank, score)); }
Example #15
Source File: TargetManagementSearchTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Step private void verfiyThat1TargetAIsInStatusPendingAndHasDSInstalled(final DistributionSet installedSet, final List<TargetUpdateStatus> pending, final Target expected) { final String query = "updatestatus==pending and installedds.name==" + installedSet.getName(); assertThat(targetManagement .findByFilters(PAGE, new FilterParams(pending, null, null, installedSet.getId(), Boolean.FALSE, new String[0])) .getContent()) .as("has number of elements").hasSize(1).as("that number is also returned by count query") .hasSize(Ints.saturatedCast(targetManagement.countByFilters(pending, null, null, installedSet.getId(), Boolean.FALSE, new String[0]))) .as("and contains the following elements").containsExactly(expected) .as("and filter query returns the same result") .containsAll(targetManagement.findByRsql(PAGE, query).getContent()); }
Example #16
Source File: TotpAuthenticator.java From AuthMeReloaded with GNU General Public License v3.0 | 5 votes |
/** * Returns whether the given input code matches for the provided TOTP key. * * @param playerName the player name * @param totpKey the key to check with * @param inputCode the input code to verify * @return true if code is valid, false otherwise */ public boolean checkCode(String playerName, String totpKey, String inputCode) { String nameLower = playerName.toLowerCase(); Integer totpCode = Ints.tryParse(inputCode); if (totpCode != null && !usedCodes.contains(nameLower, totpCode) && authenticator.authorize(totpKey, totpCode)) { usedCodes.put(nameLower, totpCode, System.currentTimeMillis()); return true; } return false; }
Example #17
Source File: ShuffleUtils.java From tez with Apache License 2.0 | 5 votes |
/** * Detailed partition stats * * @param sizes actual partition sizes */ public static DetailedPartitionStatsProto getDetailedPartitionStatsForPhysicalOutput(long[] sizes) { DetailedPartitionStatsProto.Builder builder = DetailedPartitionStatsProto.newBuilder(); for (int i=0; i<sizes.length; i++) { // Round the size up. So 1 byte -> the value of sizeInMB == 1 // Throws IllegalArgumentException if value is greater than // Integer.MAX_VALUE. That should be ok given Integer.MAX_VALUE * MB // means PB. int sizeInMb = Ints.checkedCast(ceil(sizes[i], MB)); builder.addSizeInMb(sizeInMb); } return builder.build(); }
Example #18
Source File: DS1.java From riiablo with Apache License 2.0 | 5 votes |
Path read(int version, Object[] objects, InputStream in) throws IOException { numPoints = EndianUtils.readSwappedInteger(in); points = new Point[numPoints]; x = EndianUtils.readSwappedInteger(in); y = EndianUtils.readSwappedInteger(in); Object object = null; for (int i = 0; i < objects.length; i++) { Object tmp = objects[i]; if (tmp == null) continue; if (tmp.x != x || tmp.y != y) continue; if (object != null) Gdx.app.error(TAG, "More than one object is located at path position: " + this); object = tmp; } if (object == null) { Gdx.app.error(TAG, "No object associated with path: " + this); int skip = (version >= 15 ? 3 : 2) * Ints.BYTES; for (int p = 0; p < numPoints; p++) { in.skip(skip); } return this; } for (int p = 0; p < numPoints; p++) points[p] = new Point().read(version, in); object.path = this; return this; }
Example #19
Source File: CartesianProductVertexManagerPartitioned.java From tez with Apache License 2.0 | 5 votes |
@Override public void initialize(CartesianProductConfigProto config) throws TezReflectionException { this.sourceVertices = config.getSourcesList(); this.numPartitions = Ints.toArray(config.getNumPartitionsList()); this.minFraction = config.hasMinFraction() ? config.getMinFraction() : CartesianProductVertexManager.TEZ_CARTESIAN_PRODUCT_SLOW_START_MIN_FRACTION_DEFAULT; this.maxFraction = config.hasMaxFraction() ? config.getMaxFraction() : CartesianProductVertexManager.TEZ_CARTESIAN_PRODUCT_SLOW_START_MAX_FRACTION_DEFAULT; if (config.hasFilterClassName()) { UserPayload userPayload = config.hasFilterUserPayload() ? UserPayload.create(ByteBuffer.wrap(config.getFilterUserPayload().toByteArray())) : null; try { filter = ReflectionUtils.createClazzInstance(config.getFilterClassName(), new Class[]{UserPayload.class}, new UserPayload[]{userPayload}); } catch (TezReflectionException e) { LOG.error("Creating filter failed"); throw e; } } for (String sourceVertex : sourceVertices) { sourceTaskCompleted.put(sourceVertex, new BitSet()); } for (String vertex : getContext().getInputVertexEdgeProperties().keySet()) { if (sourceVertices.indexOf(vertex) != -1) { getContext().registerForVertexStateUpdates(vertex, EnumSet.of(VertexState.CONFIGURED)); numCPSrcNotInConfiguredState++; } else { getContext().registerForVertexStateUpdates(vertex, EnumSet.of(VertexState.RUNNING)); numBroadcastSrcNotInRunningState++; } } getContext().vertexReconfigurationPlanned(); }
Example #20
Source File: Mappings.java From calcite with Apache License 2.0 | 5 votes |
/** Creates a bijection. * * <p>Throws if sources and targets are not one to one. */ public static Mapping bijection(Map<Integer, Integer> targets) { final List<Integer> targetList = new ArrayList<>(); for (int i = 0; i < targets.size(); i++) { targetList.add(targets.get(i)); } return new Permutation(Ints.toArray(targetList)); }
Example #21
Source File: DecoderUnitTest.java From xio with Apache License 2.0 | 5 votes |
@Test public void testReadSucceeds() throws Exception { UUID id = UUID.fromString("3f127172-0245-4018-b52d-a8967bd94e7d"); Message.Op op = Message.Op.Response; int payloadSize = 4; Integer payload = new Integer(1); ByteBuf buf = Unpooled.buffer(); buf.writeBytes(id.toString().getBytes()); buf.writeBytes(Ints.toByteArray(op.ordinal())); buf.writeBytes(Ints.toByteArray(payloadSize)); buf.writeBytes(Ints.toByteArray(payload)); channel.writeInbound(buf); channel.runPendingTasks(); ByteBuf decoded = (ByteBuf) channel.inboundMessages().poll(); Message message = (Message) channel.inboundMessages().poll(); String expectedDecoded = new StringBuilder() .append(" +-------------------------------------------------+\n") .append(" | 0 1 2 3 4 5 6 7 8 9 a b c d e f |\n") .append( "+--------+-------------------------------------------------+----------------+\n") .append( "|00000000| 00 00 00 01 |.... |\n") .append("+--------+-------------------------------------------------+----------------+") .toString(); assertEquals( "Expected:\n" + expectedDecoded, expectedDecoded, ByteBufUtil.prettyHexDump(decoded)); assertEquals(id, message.id); assertEquals(op, message.op); }
Example #22
Source File: MapMakerInternalMap.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override public int size() { Segment<K, V>[] segments = this.segments; long sum = 0; for (int i = 0; i < segments.length; ++i) { sum += segments[i].count; } return Ints.saturatedCast(sum); }
Example #23
Source File: RaindropListener.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
private int calculateRaindrops(MatchPlayerState player, int count, boolean scaled, double percent) { if(scaled) { final Match match = player.getMatch(); count += (int) ((double) match.getParticipatingPlayers().size() / match.getMaxPlayers() * RaindropConstants.MATCH_FULLNESS_BONUS); if(player.getParty() instanceof Team) { count += Ints.min((int) (Math.sqrt(((Team) player.getParty()).getCumulativeParticipation(player.getPlayerId()).getSeconds()) / RaindropConstants.PLAY_TIME_BONUS), RaindropConstants.PLAY_TIME_BONUS_CUTOFF); } } return RaindropUtil.calculateRaindrops(player.getPlayerId(), (int) (count * percent), true); }
Example #24
Source File: TestMultimapAggAggregation.java From presto with Apache License 2.0 | 5 votes |
@Test public void testEmptyStateOutputIsNull() { InternalAggregationFunction aggregationFunction = getInternalAggregationFunction(BIGINT, BIGINT); GroupedAccumulator groupedAccumulator = aggregationFunction.bind(Ints.asList(), Optional.empty()).createGroupedAccumulator(); BlockBuilder blockBuilder = groupedAccumulator.getFinalType().createBlockBuilder(null, 1); groupedAccumulator.evaluateFinal(0, blockBuilder); assertTrue(blockBuilder.isNull(0)); }
Example #25
Source File: SegmentUtils.java From druid-api with Apache License 2.0 | 5 votes |
public static int getVersionFromDir(File inDir) throws IOException { File versionFile = new File(inDir, "version.bin"); if (versionFile.exists()) { return Ints.fromByteArray(Files.toByteArray(versionFile)); } final File indexFile = new File(inDir, "index.drd"); int version; try (InputStream in = new FileInputStream(indexFile)) { version = in.read(); } return version; }
Example #26
Source File: CollectionUtils.java From HeyGirl with Apache License 2.0 | 5 votes |
public static <T extends Comparable<T>> int compareAsSet(@Nonnull Collection<? extends T> set1, @Nonnull Collection<? extends T> set2) { int res = Ints.compare(set1.size(), set2.size()); if (res != 0) return res; SortedSet<? extends T> sortedSet1 = toNaturalSortedSet(set1); SortedSet<? extends T> sortedSet2 = toNaturalSortedSet(set2); Iterator<? extends T> elements2 = set2.iterator(); for (T element1: set1) { res = element1.compareTo(elements2.next()); if (res != 0) return res; } return 0; }
Example #27
Source File: Block.java From Qora with MIT License | 5 votes |
public synchronized List<Transaction> getTransactions() { if(this.transactions == null) { //LOAD TRANSACTIONS this.transactions = new ArrayList<Transaction>(); try { int position = 0; for(int i=0; i<transactionCount; i++) { //GET TRANSACTION SIZE byte[] transactionLengthBytes = Arrays.copyOfRange(this.rawTransactions, position, position + TRANSACTION_SIZE_LENGTH); int transactionLength = Ints.fromByteArray(transactionLengthBytes); //PARSE TRANSACTION byte[] transactionBytes = Arrays.copyOfRange(this.rawTransactions, position + TRANSACTION_SIZE_LENGTH, position + TRANSACTION_SIZE_LENGTH + transactionLength); Transaction transaction = TransactionFactory.getInstance().parse(transactionBytes); //ADD TO TRANSACTIONS this.transactions.add(transaction); //ADD TO POSITION position += TRANSACTION_SIZE_LENGTH + transactionLength; } } catch(Exception e) { //FAILED TO LOAD TRANSACTIONS } } return this.transactions; }
Example #28
Source File: IssueAssetTransaction.java From Qora with MIT License | 5 votes |
public static byte[] generateSignature(DBSet db, PrivateKeyAccount creator, Asset asset, BigDecimal fee, long timestamp) { byte[] data = new byte[0]; //WRITE TYPE byte[] typeBytes = Ints.toByteArray(ISSUE_ASSET_TRANSACTION); typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0); data = Bytes.concat(data, typeBytes); //WRITE TIMESTAMP byte[] timestampBytes = Longs.toByteArray(timestamp); timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0); data = Bytes.concat(data, timestampBytes); //WRITE REFERENCE data = Bytes.concat(data, creator.getLastReference(db)); //WRITE CREATOR data = Bytes.concat(data, creator.getPublicKey()); //WRITE ASSET data = Bytes.concat(data , asset.toBytes(false)); //WRITE FEE byte[] feeBytes = fee.unscaledValue().toByteArray(); byte[] fill = new byte[FEE_LENGTH - feeBytes.length]; feeBytes = Bytes.concat(fill, feeBytes); data = Bytes.concat(data, feeBytes); return Crypto.getInstance().sign(creator, data); }
Example #29
Source File: CompressedInputStream.java From stratio-cassandra with Apache License 2.0 | 5 votes |
private void decompress(byte[] compressed) throws IOException { // uncompress validBufferBytes = info.parameters.sstableCompressor.uncompress(compressed, 0, compressed.length - checksumBytes.length, buffer, 0); totalCompressedBytesRead += compressed.length; // validate crc randomly if (info.parameters.getCrcCheckChance() > ThreadLocalRandom.current().nextDouble()) { if (hasPostCompressionAdlerChecksums) { checksum.update(compressed, 0, compressed.length - checksumBytes.length); } else { checksum.update(buffer, 0, validBufferBytes); } System.arraycopy(compressed, compressed.length - checksumBytes.length, checksumBytes, 0, checksumBytes.length); if (Ints.fromByteArray(checksumBytes) != (int) checksum.getValue()) throw new IOException("CRC unmatched"); // reset checksum object back to the original (blank) state checksum.reset(); } // buffer offset is always aligned bufferOffset = current & ~(buffer.length - 1); }
Example #30
Source File: Utils.java From azure-libraries-for-java with MIT License | 5 votes |
/** * Converts an object Long to a primitive int. * * @param value the Long value * @return 0 if the given Long value is null else integer value */ public static int toPrimitiveInt(Long value) { if (value == null) { return 0; } // throws IllegalArgumentException - if value is greater than Integer.MAX_VALUE // or less than Integer.MIN_VALUE return Ints.checkedCast(value); }