Example usage for com.google.common.primitives Longs tryParse

List of usage examples for com.google.common.primitives Longs tryParse

Introduction

In this page you can find the example usage for com.google.common.primitives Longs tryParse.

Prototype

@Beta
@Nullable
@CheckForNull
public static Long tryParse(String string) 

Source Link

Document

Parses the specified string as a signed decimal long value.

Usage

From source file:org.apache.druid.common.guava.GuavaUtils.java

/**
 * To fix semantic difference of Longs.tryParse() from Long.parseLong (Longs.tryParse() returns null for '+' started value)
 *///from   w ww .j  ava 2 s.  com
@Nullable
public static Long tryParseLong(@Nullable String string) {
    return Strings.isNullOrEmpty(string) ? null
            : Longs.tryParse(string.charAt(0) == '+' ? string.substring(1) : string);
}

From source file:com.cinchapi.concourse.lang.NaturalLanguage.java

/**
 * Parse the number of microseconds from the UNIX epoch that are described
 * by {@code str}./*from   w  w  w.  j  av  a  2s  . c o  m*/
 * 
 * @param str
 * @return the microseconds
 */
public static long parseMicros(String str) {
    // We should assume that the timestamp is in microseconds since
    // that is the output format used in ConcourseShell
    Long micros = Longs.tryParse(str);
    if (micros != null) {
        return micros;
    } else {
        try {
            return Timestamp.fromJoda(Timestamp.DEFAULT_FORMATTER.parseDateTime(str)).getMicros();
        } catch (Exception e) {
            List<DateGroup> groups = TIMESTAMP_PARSER.parse(str);
            Date date = null;
            for (DateGroup group : groups) {
                date = group.getDates().get(0);
                break;
            }
            if (date != null) {
                return Timestamp.fromJoda(new DateTime(date)).getMicros();
            } else {
                throw new IllegalStateException("Unrecognized date/time string '" + str + "'");
            }
        }
    }
}

From source file:com.google.appinventor.shared.rpc.component.Component.java

public static Component valueOf(String text) {
    String[] parts = text.split(DELIM);
    if (parts.length != 4) {
        throw new IllegalArgumentException("text should have 4 parts.");
    }/*from   w w w  .  j av  a2 s.c o  m*/

    Long id = Longs.tryParse(parts[0]);
    String authorId = parts[1];
    String fullyQualifiedName = parts[2];
    Long version = Longs.tryParse(parts[3]);
    if (id == null) {
        throw new IllegalArgumentException("id is not parsable.");
    }
    if (version == null) {
        throw new IllegalArgumentException("version is not parsable.");
    }

    return new Component(id, authorId, fullyQualifiedName, version);
}

From source file:org.apache.usergrid.chop.webapp.elasticsearch.Util.java

public static long getLong(Map<String, Object> json, String key) {

    long n = 0;/*  www  . j  a va2s. c  o  m*/
    Object v = json.get(key);

    if (v != null) {
        n = Longs.tryParse(v.toString());
    }

    return n;
}

From source file:org.graylog2.inputs.converters.NumericConverter.java

/**
 * Attempts to convert the provided string value to a numeric type,
 * trying Integer, Long and Double in order until successful.
 *//*  w w  w .  j a v  a2s .c om*/
@Override
public Object convert(String value) {
    if (value == null || value.isEmpty()) {
        return value;
    }

    Object result = Ints.tryParse(value);

    if (result != null) {
        return result;
    }

    result = Longs.tryParse(value);

    if (result != null) {
        return result;
    }

    result = Doubles.tryParse(value);

    if (result != null) {
        return result;
    }

    return value;
}

From source file:net.awairo.mcmod.common.v1.util.LimitedNumber.java

/**
 * ??????????Long????.//from www  . j a  v a2s.  c  o  m
 * 
 * @return Long?{@link LimitedNumber}
 */
public static Builder<Long> ofLong(final Prop prop, final long defaultValue) {
    return new Builder<Long>() {
        {
            current(Optional.fromNullable(Longs.tryParse(prop.getString())).or(defaultValue));
            min(Long.MIN_VALUE);
            max(Long.MAX_VALUE);
            step(1L);
        }

        @Override
        protected LimitedNumber<Long> newInstance(Long current, Long min, Long max, Long step) {
            return new LimitedNumber<Long>(current, min, max, step) {
                @Override
                protected Long incrementValue(Long current, Long step) {
                    // Long???????
                    return current > 0 && Long.MAX_VALUE - current < step ? Long.MAX_VALUE : current + step;
                }

                @Override
                protected Long decrementValue(Long current, Long step) {
                    // Long???????
                    return current < 0 && current - Long.MIN_VALUE < step ? Long.MIN_VALUE : current - step;
                }

                @Override
                protected void updated() {
                    prop.set(current().toString());
                }
            };
        }
    };
}

From source file:org.pentaho.caching.spi.AbstractCacheProvidingService.java

@Override
public <K, V> CompleteConfiguration<K, V> createConfiguration(Class<K> keyType, Class<V> valueType,
        Map<String, String> properties) {
    MutableConfiguration<K, V> configuration = new MutableConfiguration<K, V>();
    configuration.setTypes(keyType, valueType);

    if (properties.containsKey(CONFIG_TTL)) {
        Long ttl = Longs.tryParse(Strings.nullToEmpty(properties.get(CONFIG_TTL)));
        Preconditions.checkArgument(ttl != null, "Template config error", CONFIG_TTL);

        Optional<ExpiryFunction> expiryFunction;
        if (properties.containsKey(CONFIG_TTL_RESET)) {
            expiryFunction = Enums.getIfPresent(ExpiryFunction.class, properties.get(CONFIG_TTL_RESET));
        } else {//from   w w  w. j  a v  a  2s. com
            expiryFunction = Optional.of(CONFIG_TTL_RESET_DEFAULT);
        }
        Preconditions.checkArgument(expiryFunction.isPresent(), "Template config error", CONFIG_TTL_RESET);

        configuration.setExpiryPolicyFactory(expiryFunction.get().createFactory(ttl));
    }
    if (properties.containsKey(CONFIG_STORE_BY_VALUE)) {
        configuration.setStoreByValue(Boolean.valueOf(properties.get(CONFIG_STORE_BY_VALUE)));
    }
    return configuration;
}

From source file:com.smoketurner.notification.application.core.RangeHeader.java

/**
 * Parse a range header/*from   w w w. j a v a 2s . co m*/
 *
 * @param header
 *            Range header to parse
 * @return parsed range header
 */
public static RangeHeader parse(@Nullable final String header) {
    String field = null;
    Long fromId = null;
    Boolean fromInclusive = null;
    Long toId = null;
    Boolean toInclusive = null;
    Integer max = null;

    if (header == null) {
        return new RangeHeader(field, fromId, fromInclusive, toId, toInclusive, max);
    }

    final List<String> parts = ImmutableList.copyOf(Splitter.on(';').trimResults().split(header));

    final int count = parts.size();
    if (count > 0) {
        final Matcher first = ID_PATTERN.matcher(parts.get(0));
        if (first.matches()) {
            field = first.group("field");
            fromId = Longs.tryParse(first.group("fromId"));
            if (fromId != null) {
                fromInclusive = Strings.isNullOrEmpty(first.group("fromInclusive"));
            }
            toId = Longs.tryParse(first.group("toId"));
            if (toId != null) {
                toInclusive = Strings.isNullOrEmpty(first.group("toInclusive"));
            }
        }
    }
    if (count > 1) {
        final Matcher second = OPTIONS_PATTERN.matcher(parts.get(1));
        if (second.matches()) {
            try {
                max = Integer.parseInt(second.group("max"));
            } catch (NumberFormatException ignore) {
                // ignore
            }
        }
    }

    return new RangeHeader(field, fromId, fromInclusive, toId, toInclusive, max);
}

From source file:org.apache.druid.java.util.metrics.cgroups.Memory.java

public MemoryStat snapshot() {
    final MemoryStat memoryStat = new MemoryStat();

    try (final BufferedReader reader = Files
            .newBufferedReader(Paths.get(cgroupDiscoverer.discover(CGROUP).toString(), CGROUP_MEMORY_FILE))) {
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            final String[] parts = line.split(Pattern.quote(" "));
            if (parts.length != 2) {
                // ignore
                break;
            }//from ww w. j a v a  2 s  . c om
            final Long val = Longs.tryParse(parts[1]);
            if (val == null) {
                // Ignore
                break;
            }
            memoryStat.memoryStats.put(parts[0], val);
        }
    } catch (IOException | RuntimeException ex) {
        LOG.error(ex, "Unable to fetch memory snapshot");
    }

    try (final BufferedReader reader = Files.newBufferedReader(
            Paths.get(cgroupDiscoverer.discover(CGROUP).toString(), CGROUP_MEMORY_NUMA_FILE))) {
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            // No safety checks here. Just fail as RuntimeException and catch later
            final String[] parts = line.split(Pattern.quote(" "));
            final String[] macro = parts[0].split(Pattern.quote("="));
            final String label = macro[0];
            // Ignored
            //final long total = Long.parseLong(macro[1]);
            for (int i = 1; i < macro.length; ++i) {
                final String[] numaParts = parts[i].split(Pattern.quote("="));
                final long nodeNum = Long.parseLong(numaParts[0].substring(1));
                final long val = Long.parseLong(numaParts[1]);
                final Map<String, Long> nodeMetrics = memoryStat.numaMemoryStats.computeIfAbsent(nodeNum,
                        l -> new HashMap<>());
                nodeMetrics.put(label, val);
            }
        }
    } catch (RuntimeException | IOException e) {
        LOG.error(e, "Unable to fetch memory_numa snapshot");
    }
    return memoryStat;
}

From source file:google.registry.tools.params.DateTimeParameter.java

@Override
public DateTime convert(String value) {
    Long millis = Longs.tryParse(value);
    if (millis != null) {
        return new DateTime(millis.longValue(), UTC);
    }// w  w w . j  av a2 s . c om
    return DateTime.parse(value, STRICT_DATE_TIME_PARSER).withZone(UTC);
}