com.google.common.primitives.Shorts Java Examples

The following examples show how to use com.google.common.primitives.Shorts. 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: BankTagsPlugin.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Subscribe
public void onGrandExchangeSearched(GrandExchangeSearched event)
{
	final String input = client.getVar(VarClientStr.INPUT_TEXT);
	if (!input.startsWith(TAG_SEARCH))
	{
		return;
	}

	event.consume();

	final String tag = input.substring(TAG_SEARCH.length()).trim();
	final Set<Integer> ids = tagManager.getItemsForTag(tag)
		.stream()
		.mapToInt(Math::abs)
		.mapToObj(ItemVariationMapping::getVariations)
		.flatMap(Collection::stream)
		.distinct()
		.filter(i -> itemManager.getItemComposition(i).isTradeable())
		.limit(MAX_RESULT_COUNT)
		.collect(Collectors.toCollection(TreeSet::new));

	client.setGeSearchResultIndex(0);
	client.setGeSearchResultCount(ids.size());
	client.setGeSearchResultIds(Shorts.toArray(ids));
}
 
Example #2
Source File: Ideas_2011_08_01.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@ExpectWarning(value="RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE", num = 9)
public static int testGuavaPrimitiveCompareCalls() {
    int count = 0;
    if (Booleans.compare(false, true) == -1)
        count++;
    if (Chars.compare('a', 'b') == -1)
        count++;
    if (Doubles.compare(1, 2) == -1)
        count++;
    if (Floats.compare(1, 2) == -1)
        count++;
    if (Ints.compare(1, 2) == -1)
        count++;
    if (Longs.compare(1, 2) == -1)
        count++;
    if (Shorts.compare((short) 1, (short) 2) == -1)
        count++;
    if (SignedBytes.compare((byte) 1, (byte) 2) == -1)
        count++;
    if (UnsignedBytes.compare((byte) 1, (byte) 2) == -1)
        count++;
    return count;

}
 
Example #3
Source File: MemcachedCache.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
protected byte[] encodeValue(byte[] key, byte[] valueB) {
    byte[] compressed = null;
    if (config.isEnableCompression() && (valueB.length + Ints.BYTES + key.length > compressThreshold)) {
        try {
            compressed = CompressionUtils.compress(ByteBuffer.allocate(Ints.BYTES + key.length + valueB.length)
                    .putInt(key.length).put(key).put(valueB).array());
        } catch (IOException e) {
            compressed = null;
            logger.warn("Compressing value bytes error.", e);
        }
    }
    if (compressed != null) {
        return ByteBuffer.allocate(Shorts.BYTES + compressed.length).putShort((short) 1).put(compressed).array();
    } else {
        return ByteBuffer.allocate(Shorts.BYTES + Ints.BYTES + key.length + valueB.length).putShort((short) 0)
                .putInt(key.length).put(key).put(valueB).array();
    }
}
 
Example #4
Source File: BankTagsPlugin.java    From plugins with GNU General Public License v3.0 6 votes vote down vote up
@Subscribe
public void onGrandExchangeSearched(GrandExchangeSearched event)
{
	final String input = client.getVar(VarClientStr.INPUT_TEXT);
	if (!input.startsWith(TAG_SEARCH))
	{
		return;
	}

	event.consume();

	final String tag = input.substring(TAG_SEARCH.length()).trim();
	final Set<Integer> ids = tagManager.getItemsForTag(tag)
		.stream()
		.mapToInt(Math::abs)
		.mapToObj(ItemVariationMapping::getVariations)
		.flatMap(Collection::stream)
		.distinct()
		.filter(i -> itemManager.getItemDefinition(i).isTradeable())
		.limit(MAX_RESULT_COUNT)
		.collect(Collectors.toCollection(TreeSet::new));

	client.setGeSearchResultIndex(0);
	client.setGeSearchResultCount(ids.size());
	client.setGeSearchResultIds(Shorts.toArray(ids));
}
 
Example #5
Source File: JavaClassProcessor.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"}) // NOTE: We assume the component type matches the list
private Object toArray(Class<?> componentType, List<Object> values) {
    if (componentType == boolean.class) {
        return Booleans.toArray((Collection) values);
    } else if (componentType == byte.class) {
        return Bytes.toArray((Collection) values);
    } else if (componentType == short.class) {
        return Shorts.toArray((Collection) values);
    } else if (componentType == int.class) {
        return Ints.toArray((Collection) values);
    } else if (componentType == long.class) {
        return Longs.toArray((Collection) values);
    } else if (componentType == float.class) {
        return Floats.toArray((Collection) values);
    } else if (componentType == double.class) {
        return Doubles.toArray((Collection) values);
    } else if (componentType == char.class) {
        return Chars.toArray((Collection) values);
    }
    return values.toArray((Object[]) Array.newInstance(componentType, values.size()));
}
 
Example #6
Source File: MetastoreHiveStatisticsProvider.java    From presto with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: PBHelper.java    From hadoop with Apache License 2.0 6 votes vote down vote up
public static CacheDirectiveInfo convert
    (CacheDirectiveInfoProto proto) {
  CacheDirectiveInfo.Builder builder =
      new CacheDirectiveInfo.Builder();
  if (proto.hasId()) {
    builder.setId(proto.getId());
  }
  if (proto.hasPath()) {
    builder.setPath(new Path(proto.getPath()));
  }
  if (proto.hasReplication()) {
    builder.setReplication(Shorts.checkedCast(
        proto.getReplication()));
  }
  if (proto.hasPool()) {
    builder.setPool(proto.getPool());
  }
  if (proto.hasExpiration()) {
    builder.setExpiration(convert(proto.getExpiration()));
  }
  return builder.build();
}
 
Example #8
Source File: DecimalCasts.java    From presto with Apache License 2.0 6 votes vote down vote up
@UsedByGeneratedCode
public static long shortDecimalToSmallint(long decimal, long precision, long scale, long tenToScale)
{
    // this rounds the decimal value to the nearest integral value
    long longResult = (decimal + tenToScale / 2) / tenToScale;
    if (decimal < 0) {
        longResult = -((-decimal + tenToScale / 2) / tenToScale);
    }

    try {
        return Shorts.checkedCast(longResult);
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to SMALLINT", longResult));
    }
}
 
Example #9
Source File: JsonUtil.java    From presto with Apache License 2.0 6 votes vote down vote up
public static Long currentTokenAsSmallint(JsonParser parser)
        throws IOException
{
    switch (parser.currentToken()) {
        case VALUE_NULL:
            return null;
        case VALUE_STRING:
        case FIELD_NAME:
            return VarcharOperators.castToSmallint(Slices.utf8Slice(parser.getText()));
        case VALUE_NUMBER_FLOAT:
            return DoubleOperators.castToSmallint(parser.getDoubleValue());
        case VALUE_NUMBER_INT:
            return (long) Shorts.checkedCast(parser.getLongValue());
        case VALUE_TRUE:
            return BooleanOperators.castToSmallint(true);
        case VALUE_FALSE:
            return BooleanOperators.castToSmallint(false);
        default:
            throw new JsonCastException(format("Unexpected token when cast to %s: %s", StandardTypes.SMALLINT, parser.getText()));
    }
}
 
Example #10
Source File: AmplitudeData.java    From bither-android with Apache License 2.0 6 votes vote down vote up
public AmplitudeData(byte[] rawData) {
    if (rawData == null) {
        amplitude = 0;
        return;
    }

    int step = rawData.length / Shorts.BYTES / sampleCount;

    int count = 0;
    double sum = 0;
    for (int i = 0;
         i < rawData.length - Shorts.BYTES;
         i += step) {
        byte[] bytes = new byte[Shorts.BYTES];
        for (int j = 0;
             j < Shorts.BYTES;
             j++) {
            bytes[j] = rawData[i + j];
        }
        short s = Shorts.fromByteArray(bytes);
        sum += s * s;
        count++;
    }
    amplitude = (int) Math.sqrt(sum / count);
}
 
Example #11
Source File: ShadowAudioRecord.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Implementation
protected int read(short[] audioData, int offsetInShorts, int sizeInShorts) {
  synchronized (audioDataLock) {
    if (ShadowAudioRecord.audioData.size() > 0) {
      System.arraycopy(
          Shorts.toArray(
              ShadowAudioRecord.audioData.subList(
                  0,
                  sizeInShorts > ShadowAudioRecord.audioData.size()
                      ? ShadowAudioRecord.audioData.size()
                      : sizeInShorts)),
          0,
          audioData,
          offsetInShorts,
          sizeInShorts);
      if (ShadowAudioRecord.audioData.size() > 10) {
        ShadowAudioRecord.audioData =
            ShadowAudioRecord.audioData.subList(sizeInShorts, ShadowAudioRecord.audioData.size());
      } else {
        ShadowAudioRecord.audioData.clear();
      }
      return sizeInShorts;
    }
    return 0;
  }
}
 
Example #12
Source File: PBHelper.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static CacheDirectiveInfo convert
    (CacheDirectiveInfoProto proto) {
  CacheDirectiveInfo.Builder builder =
      new CacheDirectiveInfo.Builder();
  if (proto.hasId()) {
    builder.setId(proto.getId());
  }
  if (proto.hasPath()) {
    builder.setPath(new Path(proto.getPath()));
  }
  if (proto.hasReplication()) {
    builder.setReplication(Shorts.checkedCast(
        proto.getReplication()));
  }
  if (proto.hasPool()) {
    builder.setPool(proto.getPool());
  }
  if (proto.hasExpiration()) {
    builder.setExpiration(convert(proto.getExpiration()));
  }
  return builder.build();
}
 
Example #13
Source File: Dhcp6MessageEncoder.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
public void encode(final @Nonnull ByteBuffer byteBuffer, @Nonnull final Dhcp6Option option) {
    short tag = option.getTag();
    byte[] data = option.getData();
    byteBuffer.putShort(tag);
    byteBuffer.putShort(Shorts.checkedCast(data.length));
    byteBuffer.put(data);
}
 
Example #14
Source File: ResultSetUtil.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private static Object convertByteArrayValue(final Object value, final Class<?> convertType) {
    byte[] bytesValue = (byte[]) value;
    switch (bytesValue.length) {
        case 1:
            return convertNumberValue(bytesValue[0], convertType);
        case Shorts.BYTES:
            return convertNumberValue(Shorts.fromByteArray(bytesValue), convertType);
        case Ints.BYTES:
            return convertNumberValue(Ints.fromByteArray(bytesValue), convertType);
        case Longs.BYTES:
            return convertNumberValue(Longs.fromByteArray(bytesValue), convertType);
        default:
            return value;
    }
}
 
Example #15
Source File: IntegerOperators.java    From presto with Apache License 2.0 5 votes vote down vote up
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.INTEGER) long value)
{
    try {
        return Shorts.checkedCast(value);
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + value, e);
    }
}
 
Example #16
Source File: BigintOperators.java    From presto with Apache License 2.0 5 votes vote down vote up
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.BIGINT) long value)
{
    try {
        return Shorts.checkedCast(value);
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Out of range for smallint: " + value, e);
    }
}
 
Example #17
Source File: Dhcp6MessageEncoder.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
public void encode(final @Nonnull ByteBuffer byteBuffer, @Nonnull final Dhcp6Option option) {
    short tag = option.getTag();
    byte[] data = option.getData();
    byteBuffer.putShort(tag);
    byteBuffer.putShort(Shorts.checkedCast(data.length));
    byteBuffer.put(data);
}
 
Example #18
Source File: SimpleExtendedCommunityRegistry.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void serializeExtendedCommunity(final ExtendedCommunities extendedCommunity, final ByteBuf byteAggregator) {
    final ExtendedCommunitySerializer serializer = this.handlers.getSerializer(extendedCommunity
        .getExtendedCommunity().implementedInterface());
    if (serializer == null) {
        return;
    }
    byteAggregator.writeByte(Shorts.checkedCast(serializer.getType(extendedCommunity.isTransitive())));
    byteAggregator.writeByte(Shorts.checkedCast(serializer.getSubType()));
    serializer.serializeExtendedCommunity(extendedCommunity.getExtendedCommunity(), byteAggregator);
}
 
Example #19
Source File: AbstractTestParquetReader.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Short intToShort(Integer input)
{
    if (input == null) {
        return null;
    }
    return Shorts.checkedCast(input);
}
 
Example #20
Source File: MemcachedChunkingCache.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
protected static int getValueSplit(MemcachedCacheConfig config, String keyS, int valueBLen) {
    // the number 6 means the chunk number size never exceeds 6 bytes
    final int valueSize = config.getMaxObjectSize() - Shorts.BYTES - Ints.BYTES
            - keyS.getBytes(Charsets.UTF_8).length - 6;
    final int maxValueSize = config.getMaxChunkSize() * valueSize;
    Preconditions.checkArgument(valueBLen <= maxValueSize,
            "the value bytes length [%d] exceeds maximum value size [%d]", valueBLen, maxValueSize);
    return (valueBLen - 1) / valueSize + 1;
}
 
Example #21
Source File: CreatePartitionGroupHandler.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
private void commit(PartitionGroup group) throws Exception {
    if(logger.isDebugEnabled())logger.debug("topic[{}] add partitionGroup[{}]",group.getTopic(),group.getGroup());
    //if (!storeService.partitionGroupExists(group.getTopic(),group.getGroup())) {
        storeService.createPartitionGroup(group.getTopic().getFullName(), group.getGroup(), Shorts.toArray(group.getPartitions()));
        //}
        Set<Integer> replicas = group.getReplicas();
        List<Broker> list = new ArrayList<>(replicas.size());
        replicas.forEach(brokerId->{
            list.add(clusterManager.getBrokerById(brokerId));
        });
        electionService.onPartitionGroupCreate(group.getElectType(),group.getTopic(),group.getGroup(),list,group.getLearners(),clusterManager.getBrokerId(),group.getLeader());
}
 
Example #22
Source File: StoreInitializer.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
protected void onAddPartitionGroup(TopicName topicName, PartitionGroup partitionGroup) throws Exception {
    logger.info("onAddPartitionGroup, topic: {}, partitionGroup: {}", topicName, partitionGroup);

    Set<Integer> replicas = partitionGroup.getReplicas();
    List<Broker> brokers = new ArrayList<>(replicas.size());
    replicas.forEach(brokerId -> {
        brokers.add(clusterManager.getBrokerById(brokerId));
    });
    storeService.createPartitionGroup(topicName.getFullName(), partitionGroup.getGroup(), Shorts.toArray(partitionGroup.getPartitions()));
    electionService.onPartitionGroupCreate(partitionGroup.getElectType(), partitionGroup.getTopic(), partitionGroup.getGroup(),
            brokers, partitionGroup.getLearners(), clusterManager.getBrokerId(), partitionGroup.getLeader());
}
 
Example #23
Source File: ParserTest.java    From elastic-load-balancing-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadAddresses_ip6() throws IOException {
    AddressFamily addressFamily = AddressFamily.AF_INET6;
    TransportProtocol transportProtocol = TransportProtocol.STREAM;
    Command command = Command.PROXY;
    int ipSize = addressFamily.getAddressSize();
    int portSize = 2;

    byte[] srcAddress = InetAddress.getByName("1:2:3:4:5:6:7:8").getAddress();
    byte[] dstAddress = InetAddress.getByName("9:A:B:C:D:E:F:1").getAddress();
    short srcPort = 501;
    short dstPort = 601;

    assertEquals(ipSize, srcAddress.length);
    assertEquals(ipSize, dstAddress.length);

    byte[] stream = Bytes.concat(srcAddress, dstAddress,
            Shorts.toByteArray(srcPort), Shorts.toByteArray(dstPort));
    assertEquals(ipSize * 2 + portSize * 2, stream.length);

    Parser parser = newParser(stream);
    Header header = new Header();
    header.setCommand(command);
    header.setAddressFamily(addressFamily);
    header.setTransportProtocol(transportProtocol);
    parser.readAddresses(header);

    assertArrayEquals(srcAddress, header.getSrcAddress());
    assertArrayEquals(dstAddress, header.getDstAddress());
    assertEquals(srcPort, header.getSrcPort());
    assertEquals(dstPort, header.getDstPort());
}
 
Example #24
Source File: ArrayField.java    From drift with Apache License 2.0 5 votes vote down vote up
public Map<Short, List<Short>> getMapShortList()
{
    if (mapShortArray == null) {
        return null;
    }
    return Maps.transformValues(mapShortArray, Shorts::asList);
}
 
Example #25
Source File: MiningOverlayPlugin.java    From 07kit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onOptionsChanged() {
    RockType.CLAY.setShow(showClay);
    RockType.COPPER.setShow(showCopper);
    RockType.TIN.setShow(showTin);
    RockType.IRON.setShow(showIron);
    RockType.SILVER.setShow(showSilver);
    RockType.COAL.setShow(showCoal);
    RockType.GOLD.setShow(showGold);
    RockType.MITHRIL.setShow(showMithril);
    RockType.ADAMANTITE.setShow(showAdamntite);
    RockType.RUNITE.setShow(showRunite);

    List<Short> colors = new ArrayList<>();

    for (RockType r : RockType.values()) {
        if (r.isShow()) {
            colors.addAll(Shorts.asList(r.getColors()));
        }
    }

    filter = acceptable -> acceptable.getComposite() != null &&
            Arrays.asList(acceptable.getComposite().getOriginalModelColors())
                    .stream().anyMatch(shorts -> {
                if (shorts == null) {
                    return false;
                }
                for (short color : shorts) {
                    if (colors.contains(color)) {
                        return true;
                    }
                }
                return false;
            });
}
 
Example #26
Source File: ParserTest.java    From elastic-load-balancing-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadAddresses_ip4() throws IOException {
    AddressFamily addressFamily = AddressFamily.AF_INET;
    TransportProtocol transportProtocol = TransportProtocol.STREAM;
    Command command = Command.PROXY;
    int ipSize = addressFamily.getAddressSize();
    int portSize = 2;

    byte[] srcAddress = InetAddress.getByName("1.2.3.4").getAddress();
    byte[] dstAddress = InetAddress.getByName("5.6.7.8").getAddress();
    short srcPort = 501;
    short dstPort = 601;

    byte[] stream = Bytes.concat(srcAddress, dstAddress,
            Shorts.toByteArray(srcPort), Shorts.toByteArray(dstPort));
    assertEquals(ipSize * 2 + portSize * 2, stream.length);

    Parser parser = newParser(stream);
    Header header = new Header();
    header.setCommand(command);
    header.setAddressFamily(addressFamily);
    header.setTransportProtocol(transportProtocol);
    parser.readAddresses(header);

    assertArrayEquals(srcAddress, header.getSrcAddress());
    assertArrayEquals(dstAddress, header.getDstAddress());
    assertEquals(srcPort, header.getSrcPort());
    assertEquals(dstPort, header.getDstPort());
}
 
Example #27
Source File: MultiQpidByteBuffer.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public final short getShort()
{
    byte[] value = new byte[2];
    get(value, 0, value.length);
    return Shorts.fromByteArray(value);
}
 
Example #28
Source File: Conversions.java    From xtext-lib with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws NullPointerException
 *             if the wrapped array was <code>null</code>.
 */
@Override
public int indexOf(Object o) {
	// Will make the method fail if array is null.
	if (size() < 1) {
		return -1;
	}
	if (o instanceof Short) {
		return Shorts.indexOf(array, ((Short) o).shortValue());
	}
	return -1;
}
 
Example #29
Source File: Conversions.java    From xtext-lib with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws NullPointerException
 *             if the wrapped array was <code>null</code>.
 */
@Override
public int lastIndexOf(Object o) {
	// Will make the method fail if array is null.
	if (size() < 1) {
		return -1;
	}
	if (o instanceof Short) {
		return Shorts.lastIndexOf(array, ((Short) o).shortValue());
	}
	return -1;
}
 
Example #30
Source File: Conversions.java    From xtext-lib with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws NullPointerException
 *             if the wrapped array was <code>null</code>.
 */
@Override
public boolean contains(Object o) {
	// Will make the method fail if array is null.
	if (size() < 1) {
		return false;
	}
	if (o instanceof Short) {
		return Shorts.contains(array, ((Short) o).shortValue());
	}
	return false;
}