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:de.bussche.flink.TwitterSource.java

@Override
public void run(final SourceContext<String> ctx) throws Exception {
    LOG.info("Initializing Twitter Streaming API connection");

    StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();

    List<String> userIdListAsString = Arrays.asList(properties.getProperty(TWITTER_IDS).split(","));

    List<Long> userids = Lists.newArrayList(Lists.transform(userIdListAsString, new Function<String, Long>() {
        public Long apply(final String in) {
            return in == null ? null : Longs.tryParse(in);
        }/* ww w  .  ja  v  a  2  s.  co  m*/
    }));

    endpoint = endpoint.followings(userids);

    Authentication auth = new OAuth1(properties.getProperty(CONSUMER_KEY),
            properties.getProperty(CONSUMER_SECRET), properties.getProperty(TOKEN),
            properties.getProperty(TOKEN_SECRET));

    client = new ClientBuilder().name(properties.getProperty(CLIENT_NAME, "flink-twitter-source"))
            .hosts(properties.getProperty(CLIENT_HOSTS, Constants.STREAM_HOST)).endpoint(endpoint)
            .authentication(auth).processor(new HosebirdMessageProcessor() {
                public DelimitedStreamReader reader;

                @Override
                public void setup(InputStream input) {
                    reader = new DelimitedStreamReader(input, Constants.DEFAULT_CHARSET,
                            Integer.parseInt(properties.getProperty(CLIENT_BUFFER_SIZE, "50000")));
                }

                @Override
                public boolean process() throws IOException, InterruptedException {
                    String line = reader.readLine();
                    ctx.collect(line);
                    return true;
                }
            }).build();

    client.connect();
    running = true;

    LOG.info("Twitter Streaming API connection established successfully");

    // just wait now
    while (running) {
        synchronized (waitLock) {
            waitLock.wait(100L);
        }
    }
}

From source file:com.google.template.soy.basicfunctions.BasicFunctionsRuntime.java

public static IntegerData parseInt(String str) {
    Long l = Longs.tryParse(str);
    return (l == null) ? null : IntegerData.forValue(l);
}

From source file:com.axelor.meta.loader.ModelLoader.java

private void importSequences(Document doc, URL file, boolean update) {
    final NodeList elements = doc.getElementsByTagName("sequence");
    if (elements.getLength() == 0) {
        return;/*from   w  w w  .ja va2  s . c  o  m*/
    }

    for (int i = 0; i < elements.getLength(); i++) {

        Element element = (Element) elements.item(i);
        String name = element.getAttribute("name");

        if (isVisited(MetaSequence.class, name)) {
            continue;
        }
        if (sequences.findByName(name) != null) {
            continue;
        }

        log.debug("Loading sequence: {}", name);

        MetaSequence entity = new MetaSequence(name);

        entity.setPrefix(element.getAttribute("prefix"));
        entity.setSuffix(element.getAttribute("suffix"));

        Integer padding = Ints.tryParse(element.getAttribute("padding"));
        Integer increment = Ints.tryParse(element.getAttribute("increment"));
        Long initial = Longs.tryParse(element.getAttribute("initial"));

        if (padding != null)
            entity.setPadding(padding);
        if (increment != null)
            entity.setIncrement(increment);
        if (initial != null)
            entity.setInitial(initial);

        sequences.save(entity);
    }
}

From source file:com.indeed.imhotep.builder.tsv.EasyIndexBuilderFromTSV.java

private void detectIntFields(Iterator<String[]> iterator) throws IOException {
    final int[] intValCount = new int[indexFields.length];
    final int[] blankValCount = new int[indexFields.length];
    final boolean[] isInt = new boolean[indexFields.length];
    Arrays.fill(isInt, true);//from   w  w w  .  j a va2  s . c o m
    if (!iterator.hasNext()) {
        throw new RuntimeException(
                "No data is available in the input file. At least one line of data past the header is required");
    }
    log.info("Scanning the file to detect int fields");
    while (iterator.hasNext()) {
        final String[] values = iterator.next();
        final int valueCount = Math.min(values.length, indexFields.length);
        rowCount++;
        for (int i = 0; i < valueCount; i++) {
            if (!isInt[i]) {
                continue; // we already know this is not an integer
            }

            if (Longs.tryParse(values[i]) != null) {
                intValCount[i]++;
            } else if (values[i].isEmpty()) {
                blankValCount[i]++;
            }

            if (rowCount > 10000 && !isIntField(intValCount[i], blankValCount[i], rowCount)) {
                isInt[i] = false;
            }
        }
    }
    int intFieldCount = 0;
    List<String> intFields = Lists.newArrayList();
    for (int i = 0; i < indexFields.length; i++) {
        boolean isIntField = isInt[i] && isIntField(intValCount[i], blankValCount[i], rowCount);
        if (isIntField) {
            intFields.add(indexFields[i].getName());
        }
        indexFields[i].setIntField(isIntField);
    }
    Collections.sort(intFields);
    log.info("Int fields detected: " + Joiner.on(",").join(intFields));
}

From source file:org.apache.aurora.common.stats.TimeSeriesRepositoryImpl.java

@Override
protected void startUp() throws Exception {
    JvmStats.export();/*from w w  w.ja v a  2s .  co  m*/

    for (String name : buildInfo.getProperties().keySet()) {
        final String stringValue = buildInfo.getProperties().get(name);
        LOG.info("Build Info key: " + name + " has value " + stringValue);
        if (stringValue == null) {
            continue;
        }
        final Long longValue = Longs.tryParse(stringValue);
        if (longValue != null) {
            Stats.exportStatic(new StatImpl<Long>(Stats.normalizeName("build." + name)) {
                @Override
                public Long read() {
                    return longValue;
                }
            });
        } else {
            Stats.exportString(new StatImpl<String>(Stats.normalizeName("build." + name)) {
                @Override
                public String read() {
                    return stringValue;
                }
            });
        }
    }
}

From source file:com.cinchapi.concourse.server.http.HttpServer.java

/**
 * Initialize a {@link EndpointContainer container} by registering all of
 * its//from  w ww .j a v  a2s. c  o m
 * endpoints.
 * 
 * @param container the {@link EndpointContainer} to initialize
 */
private static void initialize(EndpointContainer container) {
    for (final Endpoint endpoint : container.endpoints()) {
        String action = endpoint.getAction();
        Route route = new Route(endpoint.getPath()) {

            @Override
            public Object handle(Request request, Response response) {
                response.type(endpoint.getContentType().toString());
                // The HttpRequests preprocessor assigns attributes to the
                // request in order for the Endpoint to make calls into
                // ConcourseServer.
                AccessToken creds = (AccessToken) request.attribute(GlobalState.HTTP_ACCESS_TOKEN_ATTRIBUTE);
                String environment = MoreObjects.firstNonNull(
                        (String) request.attribute(GlobalState.HTTP_ENVIRONMENT_ATTRIBUTE),
                        GlobalState.DEFAULT_ENVIRONMENT);
                String fingerprint = (String) request.attribute(GlobalState.HTTP_FINGERPRINT_ATTRIBUTE);

                // Check basic authentication: is an AccessToken present and
                // does the fingerprint match?
                if ((boolean) request.attribute(GlobalState.HTTP_REQUIRE_AUTH_ATTRIBUTE) && creds == null) {
                    halt(401);
                }
                if (!Strings.isNullOrEmpty(fingerprint)
                        && !fingerprint.equals(HttpRequests.getFingerprint(request))) {
                    Logger.warn("Request made with mismatching fingerprint. Expecting {} but got {}",
                            HttpRequests.getFingerprint(request), fingerprint);
                    halt(401);
                }
                TransactionToken transaction = null;
                try {
                    Long timestamp = Longs
                            .tryParse((String) request.attribute(GlobalState.HTTP_TRANSACTION_TOKEN_ATTRIBUTE));
                    transaction = creds != null && timestamp != null ? new TransactionToken(creds, timestamp)
                            : transaction;
                } catch (NullPointerException e) {
                }
                try {
                    return endpoint.serve(request, response, creds, transaction, environment);
                } catch (Exception e) {
                    if (e instanceof HttpError) {
                        response.status(((HttpError) e).getCode());
                    } else if (e instanceof SecurityException || e instanceof java.lang.SecurityException) {
                        response.removeCookie(GlobalState.HTTP_AUTH_TOKEN_COOKIE);
                        response.status(401);
                    } else if (e instanceof IllegalArgumentException) {
                        response.status(400);
                    } else {
                        response.status(500);
                        Logger.error("", e);
                    }
                    JsonObject json = new JsonObject();
                    json.addProperty("error", e.getMessage());
                    return json.toString();
                }
            }

        };
        if (action.equals("get")) {
            Spark.get(route);
        } else if (action.equals("post")) {
            Spark.post(route);
        } else if (action.equals("put")) {
            Spark.put(route);
        } else if (action.equals("delete")) {
            Spark.delete(route);
        } else if (action.equals("upsert")) {
            Spark.post(route);
            Spark.put(route);
        } else if (action.equals("options")) {
            Spark.options(route);
        }
    }
}

From source file:fr.rjoakim.android.jonetouch.util.XMLReaderUtils.java

private static Long getOptionalLongAttribute(Element parent, String name) {
    return Longs.tryParse(parent.getAttribute(name));
}

From source file:org.attribyte.api.pubsub.impl.client.NotificationEndpointServlet.java

private long timingHeader(final HttpServletRequest request, final String name) {
    Long val = Longs.tryParse(Strings.nullToEmpty(request.getHeader(name)).trim());
    return val != null ? val : 0L;
}

From source file:com.google.gerrit.server.notedb.NoteDbChangeState.java

private static Optional<Timestamp> parseReadOnlyUntil(Change.Id id, String fullStr, String first) {
    if (first.length() > 2 && first.charAt(1) == '=') {
        Long ts = Longs.tryParse(first.substring(2));
        if (ts == null) {
            throw invalidState(id, fullStr);
        }//from ww w.j  a v a2 s  .  c o  m
        return Optional.of(new Timestamp(ts));
    }
    return Optional.empty();
}

From source file:com.axelor.dms.db.repo.DMSFileRepository.java

private DMSFile findFrom(Map<String, Object> json) {
    if (json == null || json.get("id") == null) {
        return null;
    }//from w  ww  . ja v a 2  s  .  co m
    final Long id = Longs.tryParse(json.get("id").toString());
    return find(id);
}