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:com.attribyte.relay.wp.WPSupplier.java

@Override
public void init(final Properties props, final Optional<ByteString> savedState, final Logger logger)
        throws Exception {

    if (isInit.compareAndSet(false, true)) {

        this.logger = logger;

        logger.info("Initializing WP supplier...");

        final long siteId = Long.parseLong(props.getProperty("siteId", "0"));
        if (siteId < 1L) {
            throw new Exception("A 'siteId' must be specified");
        }/*from   ww w. j av a2s  .  c om*/

        final Set<String> cachedTaxonomies = ImmutableSet.of(TAG_TAXONOMY, CATEGORY_TAXONOMY);
        final Duration taxonomyCacheTimeout = Duration.ofMinutes(30); //TODO: Configure
        final Duration userCacheTimeout = Duration.ofMinutes(30); //TODO: Configure
        initPools(props, logger);
        this.db = new DB(defaultConnectionPool, siteId, cachedTaxonomies, taxonomyCacheTimeout,
                userCacheTimeout);

        Properties siteProps = new InitUtil("site.", props, false).getProperties();
        Site overrideSite = new Site(siteProps);
        this.site = this.db.selectSite().overrideWith(overrideSite);

        logger.info(
                String.format("Initialized site %d - %s", this.site.id, Strings.nullToEmpty(this.site.title)));

        if (savedState.isPresent()) {
            startMeta = PostMeta.fromBytes(savedState.get());
        } else {
            startMeta = PostMeta.ZERO;
        }

        this.selectSleepMillis = Integer.parseInt(props.getProperty("selectSleepMillis", "30000"));

        this.selectAll = props.getProperty("selectAll", "false").equalsIgnoreCase("true");
        if (this.selectAll) {
            this.stopId = this.db.selectMaxPostId();
        } else {
            this.stopId = 0L;
        }

        String supplyIdsFileStr = props.getProperty("supplyIdsFile", "");
        if (!supplyIdsFileStr.isEmpty()) {
            this.selectAll = true;
            File supplyIdsFile = new File(supplyIdsFileStr);
            logger.info(String.format("Using 'supplyIdsFile', '%s'", supplyIdsFile.getAbsolutePath()));
            this.supplyIds = Lists.newArrayListWithExpectedSize(1024);
            List<String> lines = Files.readLines(supplyIdsFile, Charsets.UTF_8);
            for (String line : lines) {
                line = line.trim();
                if (line.isEmpty() || line.startsWith("#")) {
                    continue;
                }
                Long id = Longs.tryParse(line);
                if (id != null) {
                    this.supplyIds.add(id);
                    logger.info(String.format("Adding supplied id, '%d'", id));
                }
            }

        } else {
            this.supplyIds = null;
        }

        this.maxSelected = Integer.parseInt(props.getProperty("maxSelected", "500"));

        String allowedStatusStr = props.getProperty("allowedStatus", "").trim();
        if (!allowedStatusStr.isEmpty()) {
            if (allowedStatusStr.equalsIgnoreCase("all")) {
                this.allowedStatus = ALL_STATUS;
            } else {
                this.allowedStatus = ImmutableSet
                        .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedStatusStr).stream()
                                .map(Post.Status::fromString).collect(Collectors.toSet()));
            }
        } else {
            this.allowedStatus = DEFAULT_ALLOWED_STATUS;
        }

        String allowedTypesStr = props.getProperty("allowedTypes", "").trim();
        if (!allowedStatusStr.isEmpty()) {
            this.allowedTypes = ImmutableSet
                    .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedTypesStr)).stream()
                    .map(Post.Type::fromString).collect(Collectors.toSet());
        } else {
            this.allowedTypes = DEFAULT_ALLOWED_TYPES;
        }

        String allowedPostMetaStr = props.getProperty("allowedPostMeta", "").trim();
        if (!allowedPostMetaStr.isEmpty()) {
            this.allowedPostMeta = ImmutableSet
                    .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedPostMetaStr));
        } else {
            this.allowedPostMeta = ImmutableSet.of();
        }

        String allowedImageMetaStr = props.getProperty("allowedImageMeta", "").trim();
        if (!allowedImageMetaStr.isEmpty()) {
            this.allowedImageMeta = ImmutableSet
                    .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedImageMetaStr));
        } else {
            this.allowedImageMeta = ImmutableSet.of();
        }

        String allowedUserMetaStr = props.getProperty("allowedUserMeta", "").trim();
        if (!allowedUserMetaStr.isEmpty()) {
            this.allowedUserMeta = ImmutableSet
                    .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedUserMetaStr));
        } else {
            this.allowedUserMeta = ImmutableSet.of();
        }

        String metaNameCaseFormat = props.getProperty("metaNameCaseFormat", "").trim().toLowerCase();
        switch (metaNameCaseFormat) {
        case "lower_camel":
            this.metaNameCaseFormat = CaseFormat.LOWER_CAMEL;
            break;
        case "lower_hyphen":
            this.metaNameCaseFormat = CaseFormat.LOWER_HYPHEN;
            break;
        case "upper_camel":
            this.metaNameCaseFormat = CaseFormat.UPPER_CAMEL;
            break;
        case "upper_underscore":
            this.metaNameCaseFormat = CaseFormat.UPPER_UNDERSCORE;
            break;
        default:
            this.metaNameCaseFormat = null;
        }

        this.excerptOutputField = props.getProperty("excerptOutputField", "summary").toLowerCase().trim();

        this.stopOnLostMessage = props.getProperty("stopOnLostMessage", "false").equalsIgnoreCase("true");

        this.logReplicationMessage = props.getProperty("logReplicationMessage", "false")
                .equalsIgnoreCase("true");

        this.originId = props.getProperty("originId", "");

        Properties dusterProps = new InitUtil("duster.", props, false).getProperties();
        if (dusterProps.size() > 0) {
            this.httpClient = new JettyClient();
            this.httpClient.init("http.", props, logger);
            this.dusterClient = new DusterClient(dusterProps, httpClient, logger);
            logger.info("Duster is enabled...");
        } else {
            logger.info("Duster is disabled...");
        }

        if (!props.getProperty("contentTransformer", "").trim().isEmpty()) {
            this.contentTransformer = (ContentTransformer) (Class
                    .forName(props.getProperty("contentTransformer")).newInstance());
            this.contentTransformer.init(props);
        } else if (props.getProperty("cleanShortcodes", "true").equalsIgnoreCase("true")) {
            this.contentTransformer = new ShortcodeCleaner();
        }

        if (!props.getProperty("postTransformer", "").trim().isEmpty()) {
            this.postTransformer = (PostTransformer) (Class.forName(props.getProperty("postTransformer"))
                    .newInstance());
            this.postTransformer.init(props);
        } else {
            this.postTransformer = null;
        }

        if (!props.getProperty("postFilter", "").trim().isEmpty()) {
            this.postFilter = (PostFilter) (Class.forName(props.getProperty("postFilter")).newInstance());
            this.postFilter.init(props);
        } else {
            this.postFilter = null;
        }

        String dbDir = props.getProperty("metadb.dir", "").trim();
        if (dbDir.isEmpty()) {
            this.metaDB = null;
        } else {
            logger.info(String.format("Initializing meta db, '%s'...", dbDir));
            File metaDir = new File(dbDir);
            if (!metaDir.exists()) {
                throw new Exception(String.format("The 'metadb.dir' must exist ('%s')", dbDir));
            }
            this.metaDB = new PostMetaDB(metaDir);
        }

        Long modifiedOffsetHours = Longs.tryParse(props.getProperty("modifiedOffsetHours", "0"));
        this.modifiedOffsetMillis = modifiedOffsetHours != null ? modifiedOffsetHours * 3600 * 1000L : 0L;
        if (this.modifiedOffsetMillis != 0L) {
            logger.info(String.format("Set modified select offset to %d millis", this.modifiedOffsetMillis));
        }

        this.replicateScheduledState = props.getProperty("replicateScheduledState", "true")
                .equalsIgnoreCase("true");
        this.replicatePendingState = props.getProperty("replicatePendingState", "false")
                .equalsIgnoreCase("true");

        logger.info("Initialized WP supplier...");

    }
}

From source file:org.icgc.dcc.submission.dictionary.DictionaryValidator.java

private void validateRestrictions(Set<DictionaryConstraintViolation> errors, FileSchema schema, Field field) {
    for (val restriction : field.getRestrictions()) {
        val config = restriction.getConfig();
        if (restriction.getType() == null) {
            errors.add(new DictionaryConstraintViolation("Field restriction type is blank", schema, field,
                    restriction));/* www .j av  a 2 s  . c o m*/
        }

        if (restriction.getType() == RestrictionType.CODELIST) {
            String codeListName = config.getString(CodeListRestriction.FIELD);
            if (isBlank(codeListName)) {
                errors.add(new DictionaryConstraintViolation("Field code list name is blank", schema, field,
                        restriction));
            } else if (!codeListIndex.has(codeListName)) {
                errors.add(new DictionaryConstraintViolation("Field invalid code list reference", schema, field,
                        restriction));
            }
        }

        if (restriction.getType() == RestrictionType.DISCRETE_VALUES) {
            String text = config.getString(DiscreteValuesRestriction.PARAM);
            String[] values = split(text, ",");
            for (val value : values) {
                if (isBlank(value)) {
                    errors.add(new DictionaryConstraintViolation("Blank discrete value", schema, field,
                            restriction));
                    break;
                }
            }
        }

        if (restriction.getType() == RestrictionType.RANGE) {
            String min = config.getString(RangeFieldRestriction.MIN);
            String max = config.getString(RangeFieldRestriction.MAX);
            if (!field.getValueType().isNumeric()) {
                errors.add(new DictionaryConstraintViolation("Non-numeric range field value type", schema,
                        field, restriction, field.getValueType()));
            }
            if (field.getValueType() == ValueType.INTEGER && Longs.tryParse(min) == null) {
                errors.add(new DictionaryConstraintViolation("Non INTEGER range min value", schema, field,
                        restriction, min));
            }
            if (field.getValueType() == ValueType.DECIMAL && Doubles.tryParse(min) == null) {
                errors.add(new DictionaryConstraintViolation("Non DECIMAL range min value", schema, field,
                        restriction, min));
            }
            if (field.getValueType() == ValueType.INTEGER && Longs.tryParse(max) == null) {
                errors.add(new DictionaryConstraintViolation("Non INTEGER range max value", schema, field,
                        restriction, max));
            }
            if (field.getValueType() == ValueType.DECIMAL && Doubles.tryParse(max) == null) {
                errors.add(new DictionaryConstraintViolation("Non DECIMAL range max value", schema, field,
                        restriction, max));
            }
        }

        if (restriction.getType() == RestrictionType.SCRIPT) {
            val description = config.getString(ScriptRestriction.PARAM_DESCRIPTION);
            if (isBlank(description)) {
                errors.add(new DictionaryConstraintViolation(
                        "Script restriction is missing description parameter", schema, field, restriction));
            }

            val script = config.getString(ScriptRestriction.PARAM);
            if (isBlank(script)) {
                errors.add(new DictionaryConstraintViolation("Script restriction is missing script parameter",
                        schema, field, restriction));

                continue;
            }

            try {
                val scriptContext = new ScriptRestriction.ScriptContext(script);

                val inputs = scriptContext.getInputs();
                for (val inputName : inputs.keySet()) {
                    Field inputField = dictionaryIndex.getField(schema.getName(), inputName);
                    if (inputField == null) {
                        errors.add(new DictionaryConstraintViolation(
                                "File schema is missing referenced script field", schema, field, restriction,
                                script, inputName));

                        continue;
                    }
                }
            } catch (InvalidScriptException e) {
                errors.add(
                        new DictionaryConstraintViolation(e.getMessage(), schema, field, restriction, script));
            }
        }
    }
}

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

@Override
protected void loop() {
    final InputReader reader = getInputReader();
    try {/*w w  w . j a v a  2 s .  co  m*/
        Iterator<String[]> iterator = reader.iterator();
        iterator.next(); // skip header
        while (iterator.hasNext()) {
            final String[] values = iterator.next();
            final int valueCount = Math.min(values.length, indexFields.length);
            if (valueCount != indexFields.length) {
                // inconsistent number of columns detected
                // TODO: error? log?
            }
            long docTimestamp = startTimestampMS; // default in case we don't have a time column
            for (int i = 0; i < valueCount; i++) {
                final String value = values[i];
                final IndexField field = indexFields[i];
                if (i == timeFieldIndex) {
                    long timestamp;
                    try {
                        timestamp = Long.parseLong(value);
                        if (timestamp < Integer.MAX_VALUE) {
                            timestamp *= 1000; // assume it's in seconds and convert to milliseconds
                        }
                    } catch (NumberFormatException e) {
                        // TODO
                        //                            log.warn("Illegal timestamp: " + value);
                        continue;
                    }
                    if (timestamp < startTimestampMS || timestamp > endTimestampMS) { // should this be inclusive of endTS?
                        log.warn("Timestamp outside range: " + timestamp + ". Should be between: "
                                + startTimestampMS + " and " + endTimestampMS);
                        continue;
                    }
                    docTimestamp = timestamp;
                } else {
                    if (field.isIntField()) {
                        final Long intValue = Longs.tryParse(value);
                        if (intValue != null) {
                            addTerm(field.getName(), intValue);
                        } else {
                            // don't index non-int values at all
                            if (!value.isEmpty()) {
                                field.incrementIllegalIntValue();
                            }
                        }
                    } else { // string term
                        if (field.isIdxFullField()) {
                            addTerm(field.getName(), value, false);
                        }
                        if (field.isTokenized()) {
                            /* Use the tokenized field name only 
                             * if the full name has already been used 
                             */
                            String fn = field.isIdxFullField() ? field.getNameTokenized() : field.getName();
                            addTerm(fn, value, true);
                        }
                        if (field.isBigram()) {
                            addBigramTerm(field.getNameBigram(), value);
                        }
                    }
                }
            }

            saveDocument(docTimestamp);
        }
        for (IndexField field : indexFields) {
            int badIntVals = field.getIllegalIntValues();
            if (badIntVals > 0) {
                log.warn("Column " + field.getName() + " had " + badIntVals + " (" + badIntVals * 100 / rowCount
                        + "%) illegal int values");
            }
        }
    } finally {
        Closeables2.closeQuietly(reader, log);
    }
}

From source file:com.android.incallui.CallerInfo.java

/**
 * getCallerInfo given a Cursor./* w ww  .  j a  v  a  2s  . co m*/
 * @param context the context used to retrieve string constants
 * @param contactRef the URI to attach to this CallerInfo object
 * @param cursor the first object in the cursor is used to build the CallerInfo object.
 * @return the CallerInfo which contains the caller id for the given
 * number. The returned CallerInfo is null if no number is supplied.
 */
public static CallerInfo getCallerInfo(Context context, Uri contactRef, Cursor cursor) {
    CallerInfo info = new CallerInfo();
    info.photoResource = 0;
    info.phoneLabel = null;
    info.numberType = 0;
    info.numberLabel = null;
    info.cachedPhoto = null;
    info.isCachedPhotoCurrent = false;
    info.contactExists = false;
    info.userType = ContactsUtils.USER_TYPE_CURRENT;

    Log.v(TAG, "getCallerInfo() based on cursor...");

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            // TODO: photo_id is always available but not taken
            // care of here. Maybe we should store it in the
            // CallerInfo object as well.

            long contactId = 0L;
            int columnIndex;

            // Look for the name
            columnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
            if (columnIndex != -1) {
                info.name = cursor.getString(columnIndex);
            }

            // Look for the number
            columnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER);
            if (columnIndex != -1) {
                info.phoneNumber = cursor.getString(columnIndex);
            }

            // Look for the normalized number
            columnIndex = cursor.getColumnIndex(PhoneLookup.NORMALIZED_NUMBER);
            if (columnIndex != -1) {
                info.normalizedNumber = cursor.getString(columnIndex);
            }

            // Look for the label/type combo
            columnIndex = cursor.getColumnIndex(PhoneLookup.LABEL);
            if (columnIndex != -1) {
                int typeColumnIndex = cursor.getColumnIndex(PhoneLookup.TYPE);
                if (typeColumnIndex != -1) {
                    info.numberType = cursor.getInt(typeColumnIndex);
                    info.numberLabel = cursor.getString(columnIndex);
                    info.phoneLabel = Phone
                            .getTypeLabel(context.getResources(), info.numberType, info.numberLabel).toString();
                }
            }

            // Look for the person_id.
            columnIndex = getColumnIndexForPersonId(contactRef, cursor);
            if (columnIndex != -1) {
                contactId = cursor.getLong(columnIndex);
                // QuickContacts in M doesn't support enterprise contact id
                if (contactId != 0
                        && (ContactsUtils.FLAG_N_FEATURE || !Contacts.isEnterpriseContactId(contactId))) {
                    info.contactIdOrZero = contactId;
                    Log.v(TAG, "==> got info.contactIdOrZero: " + info.contactIdOrZero);

                    // cache the lookup key for later use with person_id to create lookup URIs
                    columnIndex = cursor.getColumnIndex(PhoneLookup.LOOKUP_KEY);
                    if (columnIndex != -1) {
                        info.lookupKeyOrNull = cursor.getString(columnIndex);
                    }
                }
            } else {
                // No valid columnIndex, so we can't look up person_id.
                Log.v(TAG, "Couldn't find contactId column for " + contactRef);
                // Watch out: this means that anything that depends on
                // person_id will be broken (like contact photo lookups in
                // the in-call UI, for example.)
            }

            // Display photo URI.
            columnIndex = cursor.getColumnIndex(PhoneLookup.PHOTO_URI);
            if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) {
                info.contactDisplayPhotoUri = Uri.parse(cursor.getString(columnIndex));
            } else {
                info.contactDisplayPhotoUri = null;
            }

            // look for the custom ringtone, create from the string stored
            // in the database.
            columnIndex = cursor.getColumnIndex(PhoneLookup.CUSTOM_RINGTONE);
            if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) {
                if (TextUtils.isEmpty(cursor.getString(columnIndex))) {
                    // make it consistent with frameworks/base/.../CallerInfo.java
                    info.contactRingtoneUri = Uri.EMPTY;
                } else {
                    info.contactRingtoneUri = Uri.parse(cursor.getString(columnIndex));
                }
            } else {
                info.contactRingtoneUri = null;
            }

            // look for the send to voicemail flag, set it to true only
            // under certain circumstances.
            columnIndex = cursor.getColumnIndex(PhoneLookup.SEND_TO_VOICEMAIL);
            info.shouldSendToVoicemail = (columnIndex != -1) && ((cursor.getInt(columnIndex)) == 1);
            info.contactExists = true;

            // Determine userType by directoryId and contactId
            final String directory = contactRef == null ? null
                    : contactRef.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY);
            final Long directoryId = directory == null ? null : Longs.tryParse(directory);
            info.userType = ContactsUtils.determineUserType(directoryId, contactId);

            info.nameAlternative = ContactInfoHelper.lookUpDisplayNameAlternative(context, info.lookupKeyOrNull,
                    info.userType);
        }
        cursor.close();
    }

    info.needUpdate = false;
    info.name = normalize(info.name);
    info.contactRefUri = contactRef;

    return info;
}

From source file:com.cinchapi.concourse.util.Convert.java

/**
 * Analyze {@code value} and convert it to the appropriate Java primitive or
 * Object.// w  w w .  j a v  a 2s . c om
 * <p>
 * <h1>Conversion Rules</h1>
 * <ul>
 * <li><strong>String</strong> - the value is converted to a string if it
 * starts and ends with matching single (') or double ('') quotes.
 * Alternatively, the value is converted to a string if it cannot be
 * converted to another type</li>
 * <li><strong>{@link ResolvableLink}</strong> - the value is converted to a
 * ResolvableLink if it is a properly formatted specification returned from
 * the {@link #stringToResolvableLinkSpecification(String, String)} method
 * (<strong>NOTE: </strong> this is a rare case)</li>
 * <li><strong>{@link Link}</strong> - the value is converted to a Link if
 * it is an int or long that is wrapped by '@' signs (i.e. @1234@)</li>
 * <li><strong>Boolean</strong> - the value is converted to a Boolean if it
 * is equal to 'true', or 'false' regardless of case</li>
 * <li><strong>Double</strong> - the value is converted to a double if and
 * only if it is a decimal number that is immediately followed by a single
 * capital "D" (e.g. 3.14D)</li>
 * <li><strong>Tag</strong> - the value is converted to a Tag if it starts
 * and ends with matching (`) quotes</li>
 * <li><strong>Integer, Long, Float</strong> - the value is converted to a
 * non double number depending upon whether it is a standard integer (e.g.
 * less than {@value java.lang.Integer#MAX_VALUE}), a long, or a floating
 * point decimal</li>
 * </ul>
 * </p>
 * 
 * 
 * @param value
 * @return the converted value
 */
public static Object stringToJava(String value) {
    if (value.isEmpty()) {
        return value;
    }
    char first = value.charAt(0);
    char last = value.charAt(value.length() - 1);
    Long record;
    if (Strings.isWithinQuotes(value)) {
        // keep value as string since its between single or double quotes
        return value.substring(1, value.length() - 1);
    } else if (first == '@' && (record = Longs.tryParse(value.substring(1, value.length()))) != null) {
        return Link.to(record);
    } else if (first == '@' && last == '@' && STRING_RESOLVABLE_LINK_REGEX.matcher(value).matches()) {
        String ccl = value.substring(1, value.length() - 1);
        return ResolvableLink.create(ccl);

    } else if (value.equalsIgnoreCase("true")) {
        return true;
    } else if (value.equalsIgnoreCase("false")) {
        return false;
    } else if (first == '`' && last == '`') {
        return Tag.create(value.substring(1, value.length() - 1));
    } else {
        return MoreObjects.firstNonNull(Strings.tryParseNumber(value), value);
    }
}

From source file:org.attribyte.api.pubsub.impl.server.admin.AdminServlet.java

private void renderCallbackMetricsDetail(final String hostOrId, final HttpServletResponse response)
        throws IOException {

    ST mainTemplate = getTemplate("main");
    ST metricsTemplate = getTemplate("metrics_detail");

    if (mainTemplate == null || metricsTemplate == null) {
        response.sendError(500, "Missing templates");
        return;/*from ww w . j  ava2  s  .  c o m*/
    }

    try {
        final CallbackMetrics detailMetrics;
        final String title;

        final String host;
        final long subscriptionId;
        Long maybeSubscriptionId = hostOrId == null ? null : Longs.tryParse(hostOrId);
        if (maybeSubscriptionId != null) {
            subscriptionId = maybeSubscriptionId;
            host = null;
        } else {
            subscriptionId = 0L;
            host = hostOrId;
        }

        if (subscriptionId > 0) {
            Subscription subscription = datastore.getSubscription(subscriptionId);
            if (subscription != null) {
                title = subscription.getCallbackURL();
                detailMetrics = endpoint.getSubscriptionCallbackMetrics(subscriptionId);
            } else {
                sendNotFound(response);
                return;
            }
        } else if (host == null || host.equalsIgnoreCase("[all]")) {
            title = "All Hosts";
            detailMetrics = endpoint.getGlobalCallbackMetrics();
        } else {
            title = host;
            detailMetrics = endpoint.getHostCallbackMetrics(host);
        }
        metricsTemplate.add("metrics", new DisplayCallbackMetricsDetail(title, detailMetrics));
        mainTemplate.add("content", metricsTemplate.render());
        response.setContentType("text/html");
        response.getWriter().print(mainTemplate.render());
        response.getWriter().flush();
    } catch (IOException ioe) {
        throw ioe;
    } catch (Exception se) {
        se.printStackTrace();
        response.sendError(500, "Datastore error");
    }
}

From source file:com.tinspx.util.net.Headers.java

/**
 * Returns the value of the {@code Content-Length} header, or 0 if the
 * header is missing or invalid. Will not throw a
 * {@code NumberFormatException}.//from   w ww. j  av  a  2 s . c o  m
 * 
 * @see #parseContentLength()
 */
public long contentLength() {
    final String header = last(HttpHeaders.CONTENT_LENGTH).trim();
    if (header.isEmpty()) {
        return 0;
    } else {
        final Long len = Longs.tryParse(header);
        return len != null ? Math.max(0, len) : 0;
    }
}

From source file:com.cinchapi.concourse.util.Strings.java

/**
 * This method efficiently tries to parse {@code value} into a
 * {@link Number} object if possible. If the string is not a number, then
 * the method returns {@code null} as quickly as possible.
 * /*w  w  w  .  ja  v a 2  s.  co  m*/
 * @param value
 * @return a Number object that represents the string or {@code null} if it
 *         is not possible to parse the string into a number
 */
@Nullable
public static Number tryParseNumber(String value) {
    int size = value.length();
    if (value == null || size == 0) {
        return null;
    } else if (value.charAt(0) == '0' && size > 1 && value.charAt(1) != '.') {
        // Do not parse a string as a number if it has a leading 0 that is
        // not followed by a decimal (i.e. 007)
        return null;
    }
    boolean decimal = false;
    for (int i = 0; i < size; ++i) {
        char c = value.charAt(i);
        if (!Character.isDigit(c)) {
            if (i == 0 && c == '-') {
                continue;
            } else if (c == '.') {
                if (!decimal && size > 1) {
                    decimal = true;
                } else {
                    // Since we've already seen a decimal, the appearance of
                    // another one suggests this is an IP address instead of
                    // a number
                    return null;
                }
            } else if (i == size - 1 && c == 'D' && size > 1) {
                // Respect the convention to coerce numeric strings to
                // Double objects by appending a single 'D' character.
                return Double.valueOf(value.substring(0, i));
            } else {
                return null;
            }
        }
    }
    try {
        if (decimal) {
            // Try to return a float (for space compactness) if it is
            // possible to fit the entire decimal without any loss of
            // precision. In order to do this, we have to compare the string
            // output of both the parsed double and the parsed float. This
            // is kind of inefficient, so substitute for a better way if it
            // exists.
            double d = Doubles.tryParse(value);
            float f = Floats.tryParse(value);
            if (String.valueOf(d).equals(String.valueOf(f))) {
                return f;
            } else {
                return d;
            }
        } else {
            return MoreObjects.firstNonNull(Ints.tryParse(value), Longs.tryParse(value));
        }
    } catch (NullPointerException e) {
        throw new NumberFormatException(
                Strings.format("{} appears to be a number but cannot be parsed as such", value));
    }
}

From source file:com.axelor.web.service.RestService.java

@POST
@Path("{id}/unfollow")
@SuppressWarnings("all")
public Response messageUnfollow(@PathParam("id") long id, Request request) {
    @SuppressWarnings("all")

    final Repository<?> repo = JpaRepository.of((Class) getResource().getModel());
    final Model entity = repo.find(id);
    if (entity == null) {
        return messageFollowers(id);
    }/*from w ww . j a v  a2s. c  om*/

    final List<Object> records = request.getRecords();
    if (records == null || records.isEmpty()) {
        followers.unfollow(entity, AuthUtils.getUser());
        return messageFollowers(id);
    }

    for (Object item : records) {
        final MailFollower follower = followers.find(Longs.tryParse(item.toString()));
        if (follower != null) {
            followers.unfollow(follower);
        }
    }

    return messageFollowers(id);
}

From source file:com.axelor.rpc.Resource.java

@Transactional
@SuppressWarnings("all")
public Response remove(Request request) {

    final Response response = new Response();
    final Repository repository = JpaRepository.of(model);
    final List<Object> records = request.getRecords();

    if (records == null || records.isEmpty()) {
        response.setException(new IllegalArgumentException("No records provides."));
        return response;
    }//from ww w  .ja  va  2s  .c  o m

    final List<Model> entities = Lists.newArrayList();

    for (Object record : records) {
        Map map = (Map) record;
        Long id = Longs.tryParse(map.get("id").toString());
        Integer version = null;
        try {
            version = Ints.tryParse(map.get("version").toString());
        } catch (Exception e) {
        }

        security.get().check(JpaSecurity.CAN_REMOVE, model, id);
        Model bean = JPA.find(model, id);

        if (version != null && !Objects.equal(version, bean.getVersion())) {
            throw new OptimisticLockException(new StaleObjectStateException(model.getName(), id));
        }
        entities.add(bean);
    }

    for (Model entity : entities) {
        if (JPA.em().contains(entity)) {
            if (repository == null) {
                JPA.remove(entity);
            } else {
                repository.remove(entity);
            }
        }
    }

    response.setData(records);
    response.setStatus(Response.STATUS_SUCCESS);

    return response;
}