Java Code Examples for com.google.common.primitives.Longs#tryParse()

The following examples show how to use com.google.common.primitives.Longs#tryParse() . These examples are extracted from open source projects. 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
public static Component valueOf(String text) {
  String[] parts = text.split(DELIM);
  if (parts.length != 4) {
    throw new IllegalArgumentException("text should have 4 parts.");
  }

  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);
}
 
Example 2
Source Project: rs-api   File: Skill.java    License: ISC License 6 votes vote down vote up
/**
 * Creates a {@link Skill} from a {@link CSVRecord}.
 * @param record The record.
 * @return The {@link Skill} or {@link Optional#empty()} if the record was invalid.
 */
public static Optional<Skill> fromCsv(CSVRecord record) {
	if (record.size() < 3) {
		return Optional.empty();
	}

	Integer rank = Ints.tryParse(record.get(0));
	if (rank == null) {
		return Optional.empty();
	}

	Integer level = Ints.tryParse(record.get(1));
	if (level == null) {
		return Optional.empty();
	}

	Long experience = Longs.tryParse(record.get(2));
	if (experience == null) {
		return Optional.empty();
	}

	return Optional.of(new Skill(rank, level, experience));
}
 
Example 3
Source Project: rs-api   File: ClanMate.java    License: ISC License 6 votes vote down vote up
/**
 * Creates a {@link ClanMate} from a {@link CSVRecord}.
 * @param record The record.
 * @return The {@link ClanMate} or {@link Optional#empty()} if the record was invalid.
 */
public static Optional<ClanMate> fromCsv(CSVRecord record) {
	if (record.size() < 4) {
		return Optional.empty();
	}

	String name = record.get(0);
	String rank = record.get(1);

	Long experience = Longs.tryParse(record.get(2));
	if (experience == null) {
		return Optional.empty();
	}

	Integer kills = Ints.tryParse(record.get(3));
	if (kills == null) {
		return Optional.empty();
	}

	return Optional.of(new ClanMate(name, rank, experience, kills));
}
 
Example 4
Source Project: intercom-java   File: HttpClient.java    License: Apache License 2.0 6 votes vote down vote up
private <T> T throwException(int responseCode, ErrorCollection errors, HttpURLConnection conn) {
    // bind some well known response codes to exceptions
    if (responseCode == 403 || responseCode == 401) {
        throw new AuthorizationException(errors);
    } else if (responseCode == 429) {
        throw new RateLimitException(errors, Ints.tryParse(conn.getHeaderField(RATE_LIMIT_HEADER)),
                Ints.tryParse(conn.getHeaderField(RATE_LIMIT_REMAINING_HEADER)),
                Longs.tryParse(conn.getHeaderField(RATE_LIMIT_RESET_HEADER)));
    } else if (responseCode == 404) {
        throw new NotFoundException(errors);
    } else if (responseCode == 422) {
        throw new InvalidException(errors);
    } else if (responseCode == 400 || responseCode == 405 || responseCode == 406) {
        throw new ClientException(errors);
    } else if (responseCode == 500 || responseCode == 503) {
        throw new ServerException(errors);
    } else {
        throw new IntercomException(errors);
    }
}
 
Example 5
Source Project: jinjava   File: BaseDateFilter.java    License: Apache License 2.0 6 votes vote down vote up
protected long parseDiffAmount(JinjavaInterpreter interpreter, Object... args) {
  if (args.length < 2) {
    throw new TemplateSyntaxException(
      interpreter,
      getName(),
      "requires 1 number (diff amount) and 1 string (diff unit) argument"
    );
  }

  Object firstArg = args[0];
  if (firstArg == null) {
    firstArg = 0;
  }

  Long diff = Longs.tryParse(firstArg.toString());
  if (diff == null) {
    throw new InvalidArgumentException(
      interpreter,
      this,
      InvalidReason.NUMBER_FORMAT,
      0,
      firstArg.toString()
    );
  }
  return diff;
}
 
Example 6
Source Project: rya   File: SmartUriAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private static IRI determineType(final String data) {
    if (Ints.tryParse(data) != null) {
        return XMLSchema.INTEGER;
    } else if (Doubles.tryParse(data) != null) {
        return XMLSchema.DOUBLE;
    } else if (Floats.tryParse(data) != null) {
        return XMLSchema.FLOAT;
    } else if (isShort(data)) {
        return XMLSchema.SHORT;
    } else if (Longs.tryParse(data) != null) {
        return XMLSchema.LONG;
    } if (Boolean.parseBoolean(data)) {
        return XMLSchema.BOOLEAN;
    } else if (isByte(data)) {
        return XMLSchema.BYTE;
    } else if (isDate(data)) {
        return XMLSchema.DATETIME;
    } else if (isUri(data)) {
        return XMLSchema.ANYURI;
    }

    return XMLSchema.STRING;
}
 
Example 7
Source Project: batfish   File: RouteDistinguisher.java    License: Apache License 2.0 6 votes vote down vote up
/** Attempt to create a route distinguisher from a given string value */
@Nonnull
public static RouteDistinguisher parse(String value) {
  String[] arr = value.split(":");
  checkArgument(arr.length == 2, "At most one occurrence of ':' is allowed. Input was %s", value);
  // First element will dictate type of the route distinguisher
  Integer asn1 = Ints.tryParse(arr[0]);
  // If first element is a valid 2-byte int, it's a type 0
  if (asn1 != null && asn1 <= 0xFFFF) {
    return from(asn1, Long.parseUnsignedLong(arr[1]));
  }
  // If first element is a valid 4-byte int, it's a type 2
  Long asn1Long = Longs.tryParse(arr[0]);
  if (asn1Long != null) {
    return from(asn1Long, Integer.parseUnsignedInt(arr[1]));
  }
  // Finally fall back to trying to parse an IP address for type 1
  return from(Ip.parse(arr[0]), Integer.parseUnsignedInt(arr[1]));
}
 
Example 8
private static OptionalLong tryParse(String value)
{
    Long number = Longs.tryParse(value);
    if (number != null) {
        return OptionalLong.of(number);
    }
    return OptionalLong.empty();
}
 
Example 9
Source Project: presto   File: ThriftMetastoreUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static OptionalLong parse(@Nullable String parameterValue)
{
    if (parameterValue == null) {
        return OptionalLong.empty();
    }
    Long longValue = Longs.tryParse(parameterValue);
    if (longValue == null || longValue < 0) {
        return OptionalLong.empty();
    }
    return OptionalLong.of(longValue);
}
 
Example 10
Source Project: lumongo   File: LumongoQueryParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Query newTermQuery(org.apache.lucene.index.Term term) {
	String field = term.field();
	String text = term.text();

	FieldConfig.FieldType fieldType = indexConfig.getFieldTypeForIndexField(field);
	if (IndexConfigUtil.isNumericOrDateFieldType(fieldType)) {
		if (IndexConfigUtil.isDateFieldType(fieldType)) {
			return getNumericOrDateRange(field, text, text, true, true);
		}
		else {
			if (IndexConfigUtil.isNumericIntFieldType(fieldType) && Ints.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericLongFieldType(fieldType) && Longs.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericFloatFieldType(fieldType) && Floats.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericDoubleFieldType(fieldType) && Doubles.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
		}
		return new MatchNoDocsQuery(field + " expects numeric");
	}

	return super.newTermQuery(term);
}
 
Example 11
/** Interpret an Object as a Long, returning null if it cannot do it.  Checks if it's a Number or a String */
public static Long interpretLong(Object v) {
    if (v == null) {
        return null;
    } else if (v instanceof Number) {
        return ((Number) v).longValue();
    } else if (v instanceof String) {
        return Longs.tryParse((String) v);
    } else {
        return null;
    }
}
 
Example 12
Source Project: nomulus   File: RdapEntitySearchAction.java    License: Apache License 2.0 5 votes vote down vote up
/** Looks up registrars by handle (i.e. IANA identifier). */
private ImmutableList<Registrar> getMatchingRegistrars(final String ianaIdentifierString) {
  Long ianaIdentifier = Longs.tryParse(ianaIdentifierString);
  if (ianaIdentifier == null) {
    return ImmutableList.of();
  }
  Optional<Registrar> registrar = getRegistrarByIanaIdentifier(ianaIdentifier);
  return (registrar.isPresent() && shouldBeVisible(registrar.get()))
      ? ImmutableList.of(registrar.get())
      : ImmutableList.of();
}
 
Example 13
Source Project: nomulus   File: DateTimeParameter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DateTime convert(String value) {
  Long millis = Longs.tryParse(value);
  if (millis != null) {
    return new DateTime(millis.longValue(), UTC);
  }
  return DateTime.parse(value, STRICT_DATE_TIME_PARSER).withZone(UTC);
}
 
Example 14
/**
 * Converts values to an instant in milliseconds.
 */
@Nullable
private static Long asMillis(@Nullable final Object value) {
  Long time = null;
  if (value instanceof Date) {
    time = ((Date) value).getTime();
  }
  else if (value instanceof Number) {
    time = ((Number) value).longValue();
  }
  else if (value instanceof String) {
    time = Longs.tryParse((String) value); // timestamp string
  }
  return time;
}
 
Example 15
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
    TmfTreeViewerEntry entry1 = (TmfTreeViewerEntry) e1;
    TmfTreeViewerEntry entry2 = (TmfTreeViewerEntry) e2;
    String name1 = entry1.getName();
    String name2 = entry2.getName();
    Long longValue1 = Longs.tryParse(name1);
    Long longValue2 = Longs.tryParse(name2);

    return (longValue1 == null || longValue2 == null) ? name1.compareTo(name2) : longValue1.compareTo(longValue2);
}
 
Example 16
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
    TmfTreeViewerEntry entry1 = (TmfTreeViewerEntry) e1;
    TmfTreeViewerEntry entry2 = (TmfTreeViewerEntry) e2;
    String name1 = entry1.getName();
    String name2 = entry2.getName();
    Long longValue1 = Longs.tryParse(name1);
    Long longValue2 = Longs.tryParse(name2);

    return (longValue1 == null || longValue2 == null) ? name1.compareTo(name2) : longValue1.compareTo(longValue2);
}
 
Example 17
/**
 * Read the free and the total diskspace for the given instance
 * @param instance
 * @throws ZookeeperNotFoundException
 * @throws ZookeeperException 
 */
private void readDiskSpaceForInstance(final BBoxDBInstance instance) 
		throws ZookeeperNotFoundException, ZookeeperException {
	
	final String diskspacePath = pathHelper.getInstancesDiskspacePath(instance);
	
	final List<String> diskspaceChilds = zookeeperClient.getChildren(diskspacePath);
	
	for(final String path : diskspaceChilds) {
		final String unquotedPath = ZookeeperInstancePathHelper.unquotePath(path);
		final String totalDiskspacePath = pathHelper.getInstancesDiskspaceTotalPath(instance, unquotedPath);
		final String freeDiskspacePath = pathHelper.getInstancesDiskspaceFreePath(instance, unquotedPath);
		
		final String totalDiskspaceString = zookeeperClient.readPathAndReturnString(totalDiskspacePath);
		final String freeDiskspaceString = zookeeperClient.readPathAndReturnString(freeDiskspacePath);
		
		final Long totalDiskspace = Longs.tryParse(totalDiskspaceString);
		final Long freeDiskspace = Longs.tryParse(freeDiskspaceString);
						
		if(totalDiskspace == null) {
			logger.error("Unable to parse {} as total diskspace", totalDiskspaceString);
		} else {
			instance.addTotalSpace(unquotedPath, totalDiskspace);
		}
		
		if(freeDiskspace == null) {
			logger.error("Unable to parse {} as free diskspace", freeDiskspaceString);
		} else {
			instance.addFreeSpace(unquotedPath, freeDiskspace);
		}
	}
}
 
Example 18
@Override
protected void startUp() throws Exception {
  JvmStats.export();

  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;
        }
      });
    }
  }
}
 
Example 19
@Override
public Long parseFrom(String value) {
  return Longs.tryParse(value);
}
 
Example 20
Source Project: tracecompass   File: BtfTrace.java    License: Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Parse a line of text and make an event using it.
 *
 * @param rank
 *            the rank of the event
 * @param line
 *            the raw string of the event
 * @return the event, or null if the line is not a valid format
 */
private ITmfEvent parseLine(long rank, String line) {
    if (line == null) {
        return null;
    }
    String[] tokens = line.split(",", MAX_FIELDS); //$NON-NLS-1$
    if (tokens.length < MIN_FIELDS) {
        return null;
    }
    Iterator<String> token = Iterators.forArray(tokens);
    Long timestamp = Longs.tryParse(token.next());
    if (timestamp == null) {
        return null;
    }
    String source = token.next();
    Long sourceInstance = Longs.tryParse(token.next());
    if (sourceInstance == null) {
        sourceInstance = -1L;
    }
    BtfEventType type = BtfEventTypeFactory.parse(token.next());
    if (type == null) {
        return null;
    }
    String target = token.next();
    Long targetInstance = Longs.tryParse(token.next());
    if (targetInstance == null) {
        targetInstance = -1L;
    }
    String event = token.next();

    String notes = null;
    if (token.hasNext()) {
        notes = token.next();
    }

    ITmfEventField content = type.generateContent(event, sourceInstance, targetInstance, notes);

    return new BtfEvent(this, rank,
            getTimestampTransform().transform(fTsFormat.createTimestamp(timestamp + fTsOffset)),
            source,
            type,
            type.getDescription(),
            content,
            target);
}