com.google.common.primitives.Chars Java Examples

The following examples show how to use com.google.common.primitives.Chars. 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: JsonUtil.java    From mapper with Apache License 2.0 6 votes vote down vote up
static String escape(String s) {
  StringBuilder builder = new StringBuilder();
  int len = s.length();
  for (int i = 0; i < len; i++) {
    char c = s.charAt(i);

    int index = Chars.indexOf(SPECIAL_CHARS, c);
    if (index != -1) {
      builder.append(ESCAPED_SPECIAL_CHARS[index]);
    } else if (isControlChar(c)) {
      String hex = Integer.toHexString(c);
      builder.append("\\u");
      for (int j = 4; j > hex.length(); j--) {
        builder.append('0');
      }
      builder.append(hex);
    } else {
      builder.append(c);
    }
  }
  return builder.toString();
}
 
Example #2
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 #3
Source File: ListFilter.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  List<?> result;

  if (var == null) {
    return null;
  }

  if (var instanceof String) {
    result = Chars.asList(((String) var).toCharArray());
  } else if (Collection.class.isAssignableFrom(var.getClass())) {
    result = Lists.newArrayList((Collection<?>) var);
  } else {
    result = Lists.newArrayList(var);
  }

  return result;
}
 
Example #4
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 #5
Source File: CHMUseCasesTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test
public void testCharArrayValue() throws IOException {

    int valueSize = 10;

    char[] expected = new char[valueSize];
    Arrays.fill(expected, 'X');

    ChronicleMapBuilder<CharSequence, char[]> builder = ChronicleMapBuilder
            .of(CharSequence.class, char[].class)
            .averageValue(expected)
            .entries(1);

    try (ChronicleMap<CharSequence, char[]> map = newInstance(builder)) {
        map.put("Key", expected);

        assertEquals(Chars.asList(expected), Chars.asList(map.get("Key")));
        mapChecks();
    }
}
 
Example #6
Source File: BufferedBlockingQueueTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Test iterating on the queue while a producer and a consumer threads are
 * using it. The iteration should not affect the elements taken by the
 * consumer.
 */
@Test
public void testConcurrentIteration() {
    final BufferedBlockingQueue<@NonNull String> queue = new BufferedBlockingQueue<>(15, 15);
    final String poisonPill = "That's all folks!";

    /*
     * Convert the test's testBuffer into an array of String, one for each
     * character.
     */
    List<@NonNull String> strings = Chars.asList(testString.toCharArray()).stream()
        .map(Object::toString)
        .collect(Collectors.toList());

    Iterable<Iterable<String>> results =
            runConcurrencyTest(queue, strings, poisonPill, 1, 1, 1);

    assertEquals(strings, Iterables.getOnlyElement(results));
}
 
Example #7
Source File: BmdReader.java    From hprof-tools with MIT License 6 votes vote down vote up
private BmdConstantField readConstantField() throws IOException {
    int index = readInt32();
    BmdBasicType type = BmdBasicType.fromInt(readInt32());
    log("Field: " + type);
    switch (type) {
        case OBJECT:
        case INT:
            return new BmdConstantField(index, type, readInt32());
        case BOOLEAN:
            return new BmdConstantField(index, type, readBool());
        case BYTE:
            return new BmdConstantField(index, type, readRawByte());
        case CHAR:
            return new BmdConstantField(index, type, Chars.fromByteArray(readRawBytes(2)));
        case FLOAT:
            return new BmdConstantField(index, type, readFloat());
        case DOUBLE:
            return new BmdConstantField(index, type, readDouble());
        case LONG:
            return new BmdConstantField(index, type, readInt64());
        case SHORT:
            return new BmdConstantField(index, type, (short) readInt32());
        default:
            throw new IllegalArgumentException("Invalid field type: " + type);
    }
}
 
Example #8
Source File: BmdReader.java    From hprof-tools with MIT License 5 votes vote down vote up
private BmdStaticField readStaticField() throws IOException {
    int nameId = readInt32();
    BmdBasicType type = BmdBasicType.fromInt(readInt32());
    log("Field: " + type);
    Object value;
    switch (type) {
        case OBJECT:
        case INT:
            value = readInt32();
            break;
        case BOOLEAN:
            value = readBool();
            break;
        case BYTE:
            value = readRawByte();
            break;
        case CHAR:
            value = Chars.fromByteArray(readRawBytes(2));
            break;
        case FLOAT:
            value = readFloat();
            break;
        case DOUBLE:
            value = readDouble();
            break;
        case LONG:
            value = readInt64();
            break;
        case SHORT:
            value = (short) readInt32();
            break;
        default:
            throw new IllegalArgumentException("Invalid field type: " + type);
    }
    return new BmdStaticField(nameId, type, value);
}
 
Example #9
Source File: SafeStyleBuilderTest.java    From safe-html-types with Apache License 2.0 5 votes vote down vote up
public void testSanitizesRegularProperty() {
  // Test boundaries.
  char[] boundaryChars = {/* '/' is allowed */ ':', '@', '[', '`', '{'};
  for (Character c : Chars.asList(boundaryChars)) {
    assertBackgroundSizeStringSanitized(c.toString());
  }

  // Empty strings.
  assertBackgroundSizeStringSanitized("");
  assertBackgroundSizeStringSanitized(" ");
  assertBackgroundSizeStringSanitized("\t");
  // Unlike jslayout, comma is not allowed.
  assertBackgroundSizeStringSanitized(",");
  // Non-whitelisted characters.
  assertBackgroundSizeStringSanitized(";");
  // Function call characters.
  assertBackgroundSizeStringSanitized("(");
  assertBackgroundSizeStringSanitized(")");
  assertBackgroundSizeStringSanitized("calc()");
  // Newlines.
  assertBackgroundSizeStringSanitized("\n");
  assertBackgroundSizeStringSanitized("\r");
  // Comments.
  assertBackgroundSizeStringSanitized("foo /*");
  assertBackgroundSizeStringSanitized("foo //foo");
  // Escape sequences.
  assertBackgroundSizeStringSanitized("\\ff ");
}
 
Example #10
Source File: MailImpl.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static void detectPossibleLoop(String currentName, int loopThreshold, char separator) throws MessagingException {
    long occurrences = currentName.chars().filter(c -> Chars.saturatedCast(c) == separator).count();

    // It looks like a configuration loop. It's better to stop.
    if (occurrences > loopThreshold) {
        throw new MessagingException("Unable to create a new message name: too long. Possible loop in config.xml.");
    }
}
 
Example #11
Source File: Identifiers.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected static String mergeCharacterSets(String... s) {
    Set<Character> characters = MutableSet.of();
    for (String characterSet : s) {
        for (char c: characterSet.toCharArray()) {
            characters.add(c);
        }
    }

    return new String(Chars.toArray(characters));
}
 
Example #12
Source File: RuleReader.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private boolean isValidPatternSymbols(Pattern pattern) {
    List<Character> allow = Arrays.stream(Elements.values())
            .map(e -> e.ch())
            .collect(toList());
    allow.add(Board.ANY_CHAR);
    allow.addAll(pattern.synonyms().chars());

    return new LinkedList<>(Chars.asList(pattern.pattern().toCharArray())).stream()
            .filter(ch -> !allow.contains(ch))
            .count() == 0;
}
 
Example #13
Source File: AbstractTftpReadTransfer.java    From tftp4j with Apache License 2.0 5 votes vote down vote up
/**
 * @param blockNumber indexed from 0
 */
@Nonnull
@GuardedBy("lock")
private TftpDataPacket newPacket(@Nonnull TftpTransferContext context, int blockNumber) throws IOException {
    ByteBuffer buf = allocate(context, blockSize);
    // Note that if length is 0, we still construct a "final" zero-length packet.
    source.read(buf, blockNumber * blockSize);
    buf.flip();
    return new TftpDataPacket(Chars.checkedCast(blockNumber + 1), buf);
}
 
Example #14
Source File: AbstractTftpReadTransferTest.java    From tftp4j with Apache License 2.0 5 votes vote down vote up
private void testAck(TftpReadTransfer transfer, int ack, int first, int count) throws Exception {
    List<TftpPacket> packets = new ArrayList<TftpPacket>();
    TftpAckPacket ackPacket = new TftpAckPacket();
    ackPacket.setBlockNumber(Chars.checkedCast(ack + 1));
    LOG.info("<- " + ackPacket);
    transfer.handle(packets, ackPacket);
    assertEquals("Got wrong number of packets.", count, packets.size());
    if (count > 0) {
        if (first < 0)
            assertNull(packets.get(0));
        else
            assertEquals("Got wrong first packet", first, ((TftpDataPacket) packets.get(0)).getBlockNumber());
    }
}
 
Example #15
Source File: AbstractListDataViewTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void addSortComparator_twoComparatorsAdded_itemsSortedByCompositeComparator() {
    dataProvider = DataProvider.ofItems("b3", "a2", "a1");
    dataView = new ListDataViewImpl(() -> dataProvider, component);
    dataView.addSortComparator((s1, s2) ->
            Chars.compare(s1.charAt(0), s2.charAt(0)));
    Assert.assertEquals("Unexpected data set order (comparator 1)",
            "a2,a1,b3",
            dataView.getItems().collect(Collectors.joining(",")));
    dataView.addSortComparator((s1, s2) ->
            Chars.compare(s1.charAt(1), s2.charAt(1)));
    Assert.assertEquals("Unexpected data set order (comparator 2)",
            "a1,a2,b3",
            dataView.getItems().collect(Collectors.joining(",")));
}
 
Example #16
Source File: NameGenerator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Provides the array of available characters based on the specified arrays.
 * @param chars The list of characters that are legal
 * @param reservedCharacters The characters that should not be used
 * @return An array of characters to use. Will return the chars array if
 *    reservedCharacters is null or empty, otherwise creates a new array.
 */
static char[] reserveCharacters(char[] chars, char[] reservedCharacters) {
  if (reservedCharacters == null || reservedCharacters.length == 0) {
    return chars;
  }
  Set<Character> charSet = Sets.newLinkedHashSet(Chars.asList(chars));
  for (char reservedCharacter : reservedCharacters) {
    charSet.remove(reservedCharacter);
  }
  return Chars.toArray(charSet);
}
 
Example #17
Source File: DruidExpressions.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static String escape(final String s) {
  final StringBuilder escaped = new StringBuilder();
  for (int i = 0; i < s.length(); i++) {
    final char c = s.charAt(i);
    if (Character.isLetterOrDigit(c) || Arrays.binarySearch(SAFE_CHARS, c) >= 0) {
      escaped.append(c);
    } else {
      escaped.append("\\u").append(BaseEncoding.base16().encode(Chars.toByteArray(c)));
    }
  }
  return escaped.toString();
}
 
Example #18
Source File: TrimFunctions.java    From crate with Apache License 2.0 5 votes vote down vote up
private static String trimChars(String target, String charsToTrimArg, TrimMode mode) {
    HashSet<Character> charsToTrim =
        new HashSet<>(Chars.asList(charsToTrimArg.toCharArray()));

    int start = mode.getStartIdx(target, charsToTrim);
    int len = mode.getTrimmedLength(target, charsToTrim);

    return start < len ? target.substring(start, len) : "";
}
 
Example #19
Source File: MultiQpidByteBuffer.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public final char getChar()
{
    byte[] value = new byte[2];
    get(value, 0, value.length);
    return Chars.fromByteArray(value);
}
 
Example #20
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 Character) {
		return Chars.indexOf(array, ((Character) o).charValue());
	}
	return -1;
}
 
Example #21
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 Character) {
		return Chars.lastIndexOf(array, ((Character) o).charValue());
	}
	return -1;
}
 
Example #22
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 Character) {
		return Chars.contains(array, ((Character) o).charValue());
	}
	return false;
}
 
Example #23
Source File: BaseCharEncodedValue.java    From ZjDroid with Apache License 2.0 4 votes vote down vote up
@Override
public int compareTo(@Nonnull EncodedValue o) {
    int res = Ints.compare(getValueType(), o.getValueType());
    if (res != 0) return res;
    return Chars.compare(getValue(), ((CharEncodedValue)o).getValue());
}
 
Example #24
Source File: Ipmi20SessionWrapper.java    From ipmi4j with Apache License 2.0 4 votes vote down vote up
/** Sequence number handling: [IPMI2] Section 6.12.13, page 59. */
@Override
public void toWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
    try {
        @CheckForNull
        IpmiSession session = context.getIpmiSession(getIpmiSessionId());

        IpmiConfidentialityAlgorithm confidentialityAlgorithm = getConfidentialityAlgorithm(session);
        IpmiAuthenticationAlgorithm authenticationAlgorithm = getAuthenticationAlgorithm(session);
        IpmiIntegrityAlgorithm integrityAlgorithm = getIntegrityAlgorithm(session);

        boolean encrypted = !IpmiConfidentialityAlgorithm.NONE.equals(confidentialityAlgorithm);
        boolean authenticated = !IpmiAuthenticationAlgorithm.RAKP_NONE.equals(authenticationAlgorithm);

        IpmiPayload payload = getIpmiPayload();

        // Page 133
        buffer.put(AUTHENTICATION_TYPE.getCode());
        byte payloadTypeByte = payload.getPayloadType().getCode();
        payloadTypeByte = AbstractIpmiCommand.setBit(payloadTypeByte, 7, encrypted);
        payloadTypeByte = AbstractIpmiCommand.setBit(payloadTypeByte, 6, authenticated);
        buffer.put(payloadTypeByte);
        if (IpmiPayloadType.OEM_EXPLICIT.equals(payload.getPayloadType())) {
            OemExplicit oemPayload = (OemExplicit) payload;
            buffer.putInt(oemPayload.getOemEnterpriseNumber() << Byte.SIZE);
            buffer.putChar(oemPayload.getOemPayloadId());
        }
        toWireIntLE(buffer, getIpmiSessionId());
        toWireIntLE(buffer, getIpmiSessionSequenceNumber());

        ByteBuffer integrityInput = buffer.duplicate();

        // Page 134
        // 2 byte payload length
        int unencryptedLength = payload.getWireLength(context);
        int encryptedLength = confidentialityAlgorithm.getEncryptedLength(session, unencryptedLength);
        toWireCharLE(buffer, Chars.checkedCast(encryptedLength));

        ENCRYPT:
        {
            if (encrypted) {
                ByteBuffer unencryptedBuffer = ByteBuffer.allocate(unencryptedLength);
                payload.toWire(context, unencryptedBuffer);
                unencryptedBuffer.flip();
                confidentialityAlgorithm.encrypt(session, buffer, unencryptedBuffer);
            } else {
                // Avoidance of allocation optimization.
                payload.toWire(context, buffer);
            }
        }

        SIGN:
        if (!IpmiIntegrityAlgorithm.NONE.equals(integrityAlgorithm)) {
            // Integrity padding.
            byte[] pad = IntegrityPad.PAD(encryptedLength);
            buffer.put(pad);
            buffer.put((byte) pad.length);
            buffer.put((byte) 0x07); // Reserved, [IPMI2] Page 134, next-header field.

            integrityInput.limit(buffer.position());
            byte[] integrityData = integrityAlgorithm.sign(session, integrityInput);
            buffer.put(integrityData);
        }
    } catch (GeneralSecurityException e) {
        throw Throwables.propagate(e);
    }
}
 
Example #25
Source File: AbstractWireable.java    From ipmi4j with Apache License 2.0 4 votes vote down vote up
public static char fromWireCharLE(@Nonnull ByteBuffer buffer) {
    byte b0 = buffer.get();
    byte b1 = buffer.get();
    return Chars.fromBytes(b1, b0);
}
 
Example #26
Source File: MethodCallable.java    From Intake with GNU Lesser General Public License v3.0 4 votes vote down vote up
static MethodCallable create(ParametricBuilder builder, Object object, Method method) throws IllegalParameterException {
    checkNotNull(builder, "builder");
    checkNotNull(object, "object");
    checkNotNull(method, "method");

    Set<Annotation> commandAnnotations = ImmutableSet.copyOf(method.getAnnotations());

    Command definition = method.getAnnotation(Command.class);
    checkNotNull(definition, "Method lacks a @Command annotation");

    boolean ignoreUnusedFlags = definition.anyFlags();
    Set<Character> unusedFlags = ImmutableSet.copyOf(Chars.asList(definition.flags().toCharArray()));

    Annotation[][] annotations = method.getParameterAnnotations();
    Type[] types = method.getGenericParameterTypes();

    ArgumentParser.Builder parserBuilder = new ArgumentParser.Builder(builder.getInjector());
    for (int i = 0; i < types.length; i++) {
        parserBuilder.addParameter(types[i], Arrays.asList(annotations[i]));
    }
    ArgumentParser parser = parserBuilder.build();

    ImmutableDescription.Builder descBuilder = new ImmutableDescription.Builder()
            .setParameters(parser.getUserParameters())
            .setShortDescription(!definition.desc().isEmpty() ? definition.desc() : null)
            .setHelp(!definition.help().isEmpty() ? definition.help() : null)
            .setUsageOverride(!definition.usage().isEmpty() ? definition.usage() : null);

    Require permHint = method.getAnnotation(Require.class);
    List<String> permissions = null;
    if (permHint != null) {
        descBuilder.setPermissions(Arrays.asList(permHint.value()));
        permissions = Arrays.asList(permHint.value());
    }

    for (InvokeListener listener : builder.getInvokeListeners()) {
        listener.updateDescription(commandAnnotations, parser, descBuilder);
    }

    Description description = descBuilder.build();

    MethodCallable callable = new MethodCallable(builder, parser, object, method, description, permissions);
    callable.setCommandAnnotations(ImmutableList.copyOf(method.getAnnotations()));
    callable.setIgnoreUnusedFlags(ignoreUnusedFlags);
    callable.setUnusedFlags(unusedFlags);
    return callable;
}
 
Example #27
Source File: AbstractByteHasher.java    From exonum-java-binding with Apache License 2.0 4 votes vote down vote up
@Override
public Hasher putChar(char c) {
  scratch.putChar(c);
  return update(Chars.BYTES);
}
 
Example #28
Source File: MultiQpidByteBuffer.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
public char getChar(final int index)
{
    final byte[] byteArray = getByteArray(index, 2);
    return Chars.fromByteArray(byteArray);
}
 
Example #29
Source File: StringFromPrimitiveArrayUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() {
    assertThat(Joiner.on(separator).join(Chars.asList(charArray))).isEqualTo(expectedCharString);
}
 
Example #30
Source File: JsonUtil.java    From mapper with Apache License 2.0 4 votes vote down vote up
static List<Character> getSpecialChars() {
  return Chars.asList(SPECIAL_CHARS);
}