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.data.input.Rows.java

/**
 * Convert an object to a number. Nulls are treated as zeroes.
 *
 * @param name       field name of the object being converted (may be used for exception messages)
 * @param inputValue the actual object being converted
 *
 * @return a number/*from   w w w.j  a va 2 s  .  c  o m*/
 *
 * @throws NullPointerException if the string is null
 * @throws ParseException       if the column cannot be converted to a number
 */
@Nullable
public static Number objectToNumber(final String name, final Object inputValue) {
    if (inputValue == null) {
        return NullHandling.defaultLongValue();
    }

    if (inputValue instanceof Number) {
        return (Number) inputValue;
    } else if (inputValue instanceof String) {
        try {
            String metricValueString = StringUtils.removeChar(((String) inputValue).trim(), ',');
            // Longs.tryParse() doesn't support leading '+', so we need to trim it ourselves
            metricValueString = trimLeadingPlusOfLongString(metricValueString);
            Long v = Longs.tryParse(metricValueString);
            // Do NOT use ternary operator here, because it makes Java to convert Long to Double
            if (v != null) {
                return v;
            } else {
                return Double.valueOf(metricValueString);
            }
        } catch (Exception e) {
            throw new ParseException(e, "Unable to parse value[%s] for field[%s]", inputValue, name);
        }
    } else {
        throw new ParseException("Unknown type[%s] for field", inputValue.getClass(), inputValue);
    }
}

From source file:org.lbogdanov.poker.util.Settings.java

/**
 * Returns a value of a setting as <code>Long</code>. The value is returned as an instance of
 * {@link Optional} class to indicate the fact that it can be missing.
 * /*from   www. j a va 2s.  c om*/
 * @return the value of the setting
 */
public Optional<Long> asLong() {
    return Optional.fromNullable(Longs.tryParse(asString().or("")));
}

From source file:com.axelor.script.ScriptBindings.java

@SuppressWarnings("all")
private Object getSpecial(String name) throws Exception {
    switch (name) {
    case "__id__":
        if (variables.containsKey("id"))
            return Longs.tryParse(variables.get("id").toString());
        if (variables.containsKey("_id"))
            return Longs.tryParse(variables.get("_id").toString());
        return ((Context) variables).asType(Model.class).getId();
    case "__ids__":
        return variables.get("_ids");
    case "__this__":
        return ((Context) variables).asType(Model.class);
    case "__parent__":
        return ((Context) variables).getParentContext();
    case "__date__":
        return new LocalDate();
    case "__time__":
        return new LocalDateTime();
    case "__datetime__":
        return new DateTime();
    case "__config__":
        if (configContext == null) {
            configContext = new ConfigContext();
        }//from w  ww. jav a 2  s .  c  o m
        return configContext;
    case "__user__":
        return AuthUtils.getUser();
    case "__self__":
        Model bean = ((Context) variables).asType(Model.class);
        if (bean == null || bean.getId() == null)
            return null;
        return JPA.em().getReference(EntityHelper.getEntityClass(bean), bean.getId());
    case "__ref__":
        Map values = (Map) variables.get("_ref");
        Class<?> klass = Class.forName((String) values.get("_model"));
        return JPA.em().getReference(klass, Long.parseLong(values.get("id").toString()));
    }
    return null;
}

From source file:com.metamx.druid.loading.SingleSegmentLoader.java

@Inject
public SingleSegmentLoader(DataSegmentPuller dataSegmentPuller, QueryableIndexFactory factory,
        SegmentLoaderConfig config) {/* w  w w.j av a 2  s.c  om*/
    this.dataSegmentPuller = dataSegmentPuller;
    this.factory = factory;

    final ImmutableList.Builder<StorageLocation> locBuilder = ImmutableList.builder();

    // This is a really, really stupid way of getting this information.  Splitting on commas and bars is error-prone
    // We should instead switch it up to be a JSON Array of JSON Object or something and cool stuff like that
    // But, that'll have to wait for some other day.
    for (String dirSpec : config.getCacheDirectory().split(",")) {
        String[] dirSplit = dirSpec.split("\\|");
        if (dirSplit.length == 1) {
            locBuilder.add(new StorageLocation(new File(dirSplit[0]), config.getServerMaxSize()));
        } else if (dirSplit.length == 2) {
            final Long maxSize = Longs.tryParse(dirSplit[1]);
            if (maxSize == null) {
                throw new IAE("Size of a local segment storage location must be an integral number, got[%s]",
                        dirSplit[1]);
            }
            locBuilder.add(new StorageLocation(new File(dirSplit[0]), maxSize));
        } else {
            throw new ISE("Unknown segment storage location[%s]=>[%s], config[%s].", dirSplit.length, dirSpec,
                    config.getCacheDirectory());
        }
    }
    locations = locBuilder.build();

    Preconditions.checkArgument(locations.size() > 0, "Must have at least one segment cache directory.");
    log.info("Using storage locations[%s]", locations);
}

From source file:com.cinchapi.common.reflect.Types.java

/**
 * Coerce the {@code object} in{@code to} the provided {@link Type}, if
 * possible. If the coercion cannot be done, an
 * {@link UnsupportedOperationException} is thrown.
 * /*from  ww  w  .j  a v  a  2  s .c o m*/
 * @param object
 * @param to
 * @param converter
 * @return an instance of {@link Type} {@code to} that is coerced from the
 *         original {@code object}
 * @throws UnsupportedOperationException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T coerce(Object object, Type to, BiFunction<Type, String, T> converter)
        throws UnsupportedOperationException {
    if (to instanceof Class) {
        Class<?> type = (Class<?>) to;
        Object coerced = null;
        if (type == object.getClass() || type.isAssignableFrom(object.getClass())) {
            coerced = object;
        } else if (type.isEnum()) {
            coerced = Enums.parseIgnoreCase((Class<? extends Enum>) type, object);
        } else if (Number.class.isAssignableFrom(type)) {
            coerced = AnyStrings.tryParseNumberStrict(object.toString());
        } else if (type == int.class) {
            coerced = Ints.tryParse(object.toString());
        } else if (type == long.class) {
            coerced = Longs.tryParse(object.toString());
        } else if (type == float.class) {
            coerced = Floats.tryParse(object.toString());
        } else if (type == double.class) {
            coerced = Doubles.tryParse(object.toString());
        } else if (type == String.class) {
            coerced = object.toString();
        } else if (type == char.class || type == Character.class && object.toString().length() == 1) {
            coerced = object.toString().charAt(0);
        } else if (type == boolean.class || type == Boolean.class) {
            coerced = AnyStrings.tryParseBoolean(object.toString());
        } else if (type == Map.class || Sequences.isSequenceType(type)) {
            // Assume that the String representation contains JSON and use
            // nashorn to parse.
            try {
                coerced = nashorn.eval("Java.asJSONCompatible(" + object.toString() + ")");
                if (type.isArray()) {
                    // If the desired type is an array, we must coerce each
                    // of the elements to the array's component type.
                    Class<?> componentType = type.getComponentType();
                    Object array = Array.newInstance(componentType, ((Collection) coerced).size());
                    AtomicInteger index = new AtomicInteger(0);
                    Sequences.forEach(coerced, item -> Array.set(array, index.getAndIncrement(),
                            Types.coerce(item, componentType)));
                    coerced = array;
                } else if (Map.class.isAssignableFrom(type)) {
                    coerced = ImmutableMap.copyOf((Map) coerced);
                } else {
                    coerced = ImmutableList.copyOf((Iterable) coerced);
                }
            } catch (ScriptException e) {
            }
        } else {
            try {
                coerced = type.cast(object);
            } catch (ClassCastException e) {
            }
            if (coerced == null) {
                // As a last resort, try applying the #converter to the
                // string representation of the argument
                try {
                    Object converted = converter.apply(to, object.toString());
                    coerced = type.isAssignableFrom(converted.getClass()) ? converted : null;
                } catch (Exception e) {
                }
            }
        }
        if (coerced != null) {
            return (T) coerced;
        } else {
            throw new UnsupportedOperationException("Unable to coerce " + object + " into " + to);
        }
    } else {
        throw new UnsupportedOperationException("Unsupported type " + to);
    }
}

From source file:org.sfs.vo.XBlob.java

public XBlob merge(SfsRequest httpServerRequest) {
    MultiMap queryParams = httpServerRequest.params();
    MultiMap headers = httpServerRequest.headers();

    if (queryParams.contains(VOLUME)) {
        volume = tryParse(queryParams.get(VOLUME));
    }//ww  w.j a va2 s  .co m
    if (queryParams.contains(POSITION)) {
        position = Longs.tryParse(queryParams.get(POSITION));
    }
    if (queryParams.contains(VERSION)) {
        version = base64().decode(queryParams.get(VERSION));
    }
    if (headers.contains(CONTENT_LENGTH)) {
        length = Longs.tryParse(headers.get(CONTENT_LENGTH));
    }

    for (String queryParam : queryParams.names()) {
        Matcher matcher = COMPUTED_DIGEST.matcher(queryParam);
        if (matcher.matches()) {
            MessageDigestFactory digest = fromValueIfExists(matcher.group(1)).get();
            messageDigests.add(digest);
        }
    }

    return this;
}

From source file:com.attribyte.relay.wp.PostMeta.java

/**
 * Creates an instance from previously stored bytes.
 * @param bytes The stored bytes./*from  w  ww . j av a2s .  c  o  m*/
 * @return The metadata.
 * @throws IOException on invalid format.
 */
public static PostMeta fromBytes(final ByteString bytes) throws IOException {

    String[] components = bytes.toStringUtf8().split(",");
    if (components.length < 2) {
        throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
    }

    Long id = Longs.tryParse(components[0].trim());
    if (id == null) {
        throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
    }

    Long lastModifiedMillis = Longs.tryParse(components[1].trim());
    if (lastModifiedMillis == null) {
        throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
    }

    if (components.length >= 3) {
        return new PostMeta(id, lastModifiedMillis, HashCode.fromString(components[2].trim()));
    } else {
        return new PostMeta(id, lastModifiedMillis);
    }
}

From source file:org.icgc.dcc.portal.util.ElasticsearchResponseUtils.java

public static Long getLong(Object value) {
    if (null == value) {
        return null;
    }//from   ww w  . j av  a  2s .c om

    if (value instanceof Long) {
        return (Long) value;
    }

    if (value instanceof Float) {
        return ((Float) value).longValue();
    }

    if (value instanceof Integer) {
        return Long.valueOf((Integer) value);
    }

    if (value instanceof Iterable<?>) {
        val iterable = (Iterable<?>) value;
        return Iterables.isEmpty(iterable) ? null : Longs.tryParse(Iterables.get(iterable, 0).toString());
    }

    return Longs.tryParse(value.toString());
}

From source file:net.awairo.mcmod.spawnchecker.client.common.MultiServerWorldSeedConfig.java

private static ImmutableTable<String, Integer, Long> load(String[] worldSeeds) {
    final Pattern pattern = Pattern.compile("^\"([^\"]+)\"$");
    final Splitter keyValue = Splitter.on('=');
    final Splitter hostPort = Splitter.on(':');

    final ImmutableTable.Builder<String, Integer, Long> builder = ImmutableTable.builder();
    for (String seedConfig : worldSeeds) {
        final Matcher m = pattern.matcher(seedConfig);
        if (!m.matches()) {
            LOGGER.warn("removed {} from world seed configurations. (illegal format)", seedConfig);
            continue;
        }/*from  w w w  . j  a  va2s .c o m*/

        final Iterator<String> kv = keyValue.split(m.group(1)).iterator();

        if (!kv.hasNext()) {
            LOGGER.warn("removed {} from world seed configurations. (illegal address)", seedConfig);
            continue;
        }

        final Iterator<String> hp = hostPort.split(kv.next()).iterator();
        if (!kv.hasNext()) {
            LOGGER.warn("removed {} from world seed configurations. (illegal seed)", seedConfig);
            continue;
        }
        if (!hp.hasNext()) {
            LOGGER.warn("removed {} from world seed configurations. (illegal address)", seedConfig);
            continue;
        }

        final Long seed = Longs.tryParse(kv.next());
        if (seed == null) {
            LOGGER.warn("removed {} from world seed configurations. (illegal seed value)", seedConfig);
            continue;
        }

        final String host = hp.next();
        final Integer port = hp.hasNext() ? Ints.tryParse(hp.next()) : DEFAULT_PORT;

        builder.put(host, port, seed);
    }

    return builder.build();
}

From source file:com.google.errorprone.bugpatterns.time.TimeUnitConversionChecker.java

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    if (!MATCHER.matches(tree, state)) {
        return Description.NO_MATCH;
    }/*  w w  w.  j  av  a2  s . c o m*/

    Tree receiverOfConversion = ASTHelpers.getReceiver(tree);
    if (receiverOfConversion == null) {
        // Usage inside TimeUnit itself, no changes we can make here.
        return Description.NO_MATCH;
    }
    // This trips up on code like:
    // TimeUnit SECONDS = TimeUnit.MINUTES;
    // long about2500 = SECONDS.toSeconds(42);
    // but... I think that's bad enough to ignore here :)
    String timeUnitName = ASTHelpers.getSymbol(receiverOfConversion).getSimpleName().toString();
    Optional<TimeUnit> receiver = Enums.getIfPresent(TimeUnit.class, timeUnitName);
    if (!receiver.isPresent()) {
        return Description.NO_MATCH;
    }

    String methodName = ASTHelpers.getSymbol(tree).getSimpleName().toString();
    TimeUnit convertTo = methodNameToTimeUnit(methodName);
    ExpressionTree arg0 = tree.getArguments().get(0);

    // if we have a constant and can Long-parse it...
    Long constant = Longs.tryParse(String.valueOf(state.getSourceForNode(arg0)));
    if (constant != null) {
        long converted = invokeConversion(receiver.get(), methodName, constant);

        // ... and the conversion results in 0 or 1, just inline it!
        if (converted == 0 || converted == 1 || constant == converted) {
            SuggestedFix fix = replaceTreeWith(tree, convertTo, converted + "L");
            return describeMatch(tree, fix);
        }

        // otherwise we have a suspect case: SMALLER_UNIT.toLargerUnit(constantValue)
        // because: "people usually don't like to have constants like 60_000_000 and use"
        //          "libraries to turn them into smaller numbers"
        if (receiver.get().compareTo(convertTo) < 0) {
            // We can't suggest a replacement here, so we just have to error out.
            return describeMatch(tree);
        }
    }

    // if we're trying to convert the unit to itself, just return the arg
    if (receiver.get().equals(convertTo)) {
        SuggestedFix fix = replaceTreeWith(tree, convertTo, state.getSourceForNode(arg0));
        return describeMatch(tree, fix);
    }
    return Description.NO_MATCH;
}