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

The following examples show how to use com.google.common.primitives.Longs#tryParse() . 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
Source File: RouteDistinguisher.java    From batfish with 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 2
Source File: Component.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
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 3
Source File: Skill.java    From rs-api with 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 4
Source File: ClanMate.java    From rs-api with 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 5
Source File: HttpClient.java    From intercom-java with 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 6
Source File: SmartUriAdapter.java    From rya with 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 File: BaseDateFilter.java    From jinjava with 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 8
Source File: RdapEntitySearchAction.java    From nomulus with 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 9
Source File: TimeSeriesRepositoryImpl.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: ZookeeperBBoxDBInstanceAdapter.java    From bboxdb with Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
Source File: AbstractSelectTreeViewer2.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@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 12
Source File: AbstractSelectTreeViewer.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@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 13
Source File: DeconflictStepSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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 14
Source File: DateTimeParameter.java    From nomulus with 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 15
Source File: TestHiveBasicTableStatistics.java    From presto with Apache License 2.0 5 votes vote down vote up
private static OptionalLong tryParse(String value)
{
    Long number = Longs.tryParse(value);
    if (number != null) {
        return OptionalLong.of(number);
    }
    return OptionalLong.empty();
}
 
Example 16
Source File: BagGrouped.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** 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 17
Source File: LumongoQueryParser.java    From lumongo with 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 18
Source File: ThriftMetastoreUtil.java    From presto with 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 19
Source File: BtfTrace.java    From tracecompass with 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);
}
 
Example 20
Source File: AuroraResourceConverter.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
public Long parseFrom(String value) {
  return Longs.tryParse(value);
}