use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class TimeSpan method valueOf.
/**
* Converts the given {@link String} into a {@link TimeSpan} object. Supported units are day,
* hour, minute and second.
*
* @param input the {@link String} to convert
* @return a {@link TimeSpan} represented by the given {@link String}
* @throws IllegalArgumentException if the input is not a valid string representation of a {@link
* TimeSpan}.
*/
public static TimeSpan valueOf(String input) {
// only seconds: use simple regex
Matcher secondMatcher = ONLY_DIGITS.matcher(input);
if (secondMatcher.matches()) {
return ofSeconds(Long.parseLong(secondMatcher.group(1)));
}
// values with units: more elaborate parsing necessary
List<String> tokens = splitIntoTokens(input);
@Var long days = 0;
@Var long hours = 0;
@Var long minutes = 0;
@Var long seconds = 0;
Iterator<String> it = tokens.iterator();
while (it.hasNext()) {
// first: value
String nextString = it.next();
long value = Long.parseLong(nextString);
// second: unit
if (!it.hasNext()) {
throw new IllegalArgumentException("Value " + nextString + " has no unit.");
}
String unit = it.next();
switch(unit) {
case "day":
case "days":
case "d":
if (days != 0) {
throw new IllegalArgumentException("Days set twice: " + unit);
}
days = value;
break;
case "h":
case "hour":
case "hours":
if (hours != 0) {
throw new IllegalArgumentException("Hours set twice: " + unit);
}
hours = value;
break;
case "min":
case "m":
if (minutes != 0) {
throw new IllegalArgumentException("Minutes set twice: " + unit);
}
minutes = value;
break;
case "s":
if (seconds != 0) {
throw new IllegalArgumentException("Seconds set twice: " + unit);
}
seconds = value;
break;
default:
throw new IllegalArgumentException("Unknown unit: " + unit);
}
}
return sum(of(seconds, SECONDS), of(minutes, MINUTES), of(hours, HOURS), of(days, DAYS));
}
use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class ClassTypeConverter method convert.
@Override
public Object convert(String optionName, String value, TypeToken<?> type, Annotation secondaryOption, Path pSource, LogManager logger) throws InvalidConfigurationException {
// null means "no prefix"
@Var Iterable<String> packagePrefixes = Collections.<String>singleton(null);
// get optional package prefix
if (secondaryOption != null) {
if (!(secondaryOption instanceof ClassOption)) {
throw new UnsupportedOperationException("Options of type Class may not be annotated with " + secondaryOption);
}
packagePrefixes = from(packagePrefixes).append(((ClassOption) secondaryOption).packagePrefix());
}
// get class object
@Var Class<?> cls = null;
for (String prefix : packagePrefixes) {
try {
cls = Classes.forName(value, prefix);
} catch (ClassNotFoundException ignored) {
// Ignore, we try next prefix and throw below if none is found.
}
}
if (cls == null) {
throw new InvalidConfigurationException("Class " + value + " specified in option " + optionName + " not found");
}
Object result;
if (type.getRawType().equals(Class.class)) {
// get value of type parameter
TypeToken<?> targetType = Classes.getSingleTypeArgument(type);
// check type
if (!targetType.isSupertypeOf(cls)) {
throw new InvalidConfigurationException(String.format("Class %s specified in option %s is not an instance of %s", value, optionName, targetType));
}
result = cls;
Classes.produceClassLoadingWarning(logger, cls, targetType.getRawType());
} else {
// This should be a factory interface for which we create a proxy implementation.
try {
result = Classes.createFactory(type, cls);
} catch (UnsuitedClassException e) {
throw new InvalidConfigurationException(String.format("Class %s specified in option %s is invalid (%s)", value, optionName, e.getMessage()));
}
Classes.produceClassLoadingWarning(logger, cls, type.getRawType());
}
return result;
}
use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class TimeSpanTypeConverter method convert.
@Override
public Object convert(String optionName, String valueStr, TypeToken<?> pType, Annotation pOption, Path pSource, LogManager logger) throws InvalidConfigurationException {
Class<?> type = pType.getRawType();
if (!(pOption instanceof TimeSpanOption)) {
throw new UnsupportedOperationException("Time span options need to be annotated with @TimeSpanOption");
}
TimeSpanOption option = (TimeSpanOption) pOption;
// find unit in input string
@Var int i = valueStr.length() - 1;
while (i >= 0 && LETTER_MATCHER.matches(valueStr.charAt(i))) {
i--;
}
if (i < 0) {
throw new InvalidConfigurationException("Option " + optionName + " contains no number");
}
// convert unit string to TimeUnit
String userUnitStr = valueStr.substring(i + 1).trim();
TimeUnit userUnit = userUnitStr.isEmpty() ? option.defaultUserUnit() : TIME_UNITS.get(userUnitStr);
if (userUnit == null) {
throw new InvalidConfigurationException("Option " + optionName + " contains invalid unit");
}
// Parse string without unit
long rawValue;
try {
rawValue = Long.parseLong(valueStr.substring(0, i + 1).trim());
} catch (NumberFormatException e) {
throw new InvalidConfigurationException("Option " + optionName + " contains invalid number");
}
// convert value from user unit to code unit
TimeUnit codeUnit = option.codeUnit();
long value = codeUnit.convert(rawValue, userUnit);
if (option.min() > value || value > option.max()) {
String codeUnitStr = TIME_UNITS.inverse().get(codeUnit);
throw new InvalidConfigurationException(String.format("Invalid value in configuration file: \"%s = %s (not in range [%d %s, %d %s])", optionName, value, option.min(), codeUnitStr, option.max(), codeUnitStr));
}
Object result;
if (type.equals(Integer.class)) {
if (value > Integer.MAX_VALUE) {
throw new InvalidConfigurationException("Value for option " + optionName + " is larger than " + Integer.MAX_VALUE);
}
result = (int) value;
} else if (type.equals(Long.class)) {
result = value;
} else {
assert type.equals(TimeSpan.class);
result = TimeSpan.of(rawValue, userUnit);
}
return result;
}
use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class Configuration method getValue.
/**
* This method gets the value which needs to be assigned to the option.
*
* @param options Options annotation.
* @param method Member the annotation is attached to.
* @param defaultValue The default value (may be null).
* @param type The type of the option.
* @param option The annotation of the option.
* @param member The member that declares the option.
* @return The value to assign (may be null).
* @throws UnsupportedOperationException If the declaration of the option in the source code is
* invalid.
* @throws InvalidConfigurationException If the user specified an invalid value for the option.
*/
@Nullable
private <T> Object getValue(Options options, Member method, @Nullable T defaultValue, TypeToken<T> type, Option option, AnnotatedElement member) throws InvalidConfigurationException {
boolean isEnum = type.getRawType().isEnum();
String optionName = getOptionName(options, method, option);
@Var String valueStr = getValueString(optionName, option, isEnum);
Annotation secondaryOption = getSecondaryAnnotation(member);
Object value;
if (!options.deprecatedPrefix().equals(NO_DEPRECATED_PREFIX)) {
String optionDeprecatedName = getOptionName(options, method, option, /* isDeprecated= */
true);
String deprecatedValueStr = getValueString(optionDeprecatedName, option, isEnum);
if (deprecatedValueStr != null && !deprecatedValueStr.equals(valueStr)) {
if (valueStr == null) {
valueStr = deprecatedValueStr;
logger.logf(Level.WARNING, "Using deprecated name for option '%s'%s, " + "please update your config to use the option name '%s' instead.", optionDeprecatedName, getOptionSourceForLogging(optionDeprecatedName), optionName);
} else {
logger.logf(Level.WARNING, "Option '%s'%s is set to a different value " + "than its deprecated previous name '%s'%s, " + "using the value '%s' of the former and ignoring the latter.", optionName, getOptionSourceForLogging(optionName), optionDeprecatedName, getOptionSourceForLogging(optionDeprecatedName), valueStr);
}
}
}
if (valueStr != null) {
if (secureMode && !option.secure()) {
throw new InvalidConfigurationException("Configuration option " + optionName + " was specified, but is not allowed in secure mode.");
}
value = convertValue(optionName, valueStr, type, secondaryOption);
if (member.isAnnotationPresent(Deprecated.class)) {
deprecatedProperties.add(optionName);
}
} else {
if (option.required()) {
throw new InvalidConfigurationException("Required configuration option " + optionName + " is missing.");
}
value = convertDefaultValue(optionName, defaultValue, type, secondaryOption);
}
if (printUsedOptions != null) {
printOptionInfos(member, optionName, valueStr, defaultValue);
}
return value;
}
use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class ProcessExecutor method join.
/**
* Wait for the process to terminate.
*
* @param timelimit Maximum time to wait for process (in milliseconds)
* @return The exit code of the process.
* @throws IOException passed from the handle* methods.
* @throws E passed from the handle* methods.
* @throws TimeoutException If timeout is hit.
* @throws InterruptedException If the current thread is interrupted.
*/
public int join(long timelimit) throws IOException, E, TimeoutException, InterruptedException {
try {
@Var Integer exitCode = null;
try {
if (timelimit > 0) {
exitCode = processFuture.get(timelimit, TimeUnit.MILLISECONDS);
} else {
exitCode = processFuture.get();
}
} catch (CancellationException e) {
// the processFuture has been cancelled, probably because the outFuture or
// the errFuture threw an exception
// ignore exception here and call get() on the other futures to get their
// exceptions
}
// wait for reading tasks to finish and to get exceptions
outFuture.get();
errFuture.get();
if (exitCode == null) {
// Assume this as an interrupt.
throw new InterruptedException();
}
return exitCode;
} catch (TimeoutException e) {
logger.log(Level.WARNING, "Killing", name, "due to timeout");
processFuture.cancel(true);
throw e;
} catch (InterruptedException e) {
logger.log(Level.WARNING, "Killing", name, "due to user interrupt");
processFuture.cancel(true);
throw e;
} catch (ExecutionException e) {
Throwable t = e.getCause();
Throwables.propagateIfPossible(t, IOException.class, exceptionClass);
throw new UnexpectedCheckedException("output handling of external process " + name, t);
} finally {
assert processFuture.isDone();
// needed for memory visibility of the Callables
Concurrency.waitForTermination(executor);
try {
in.close();
} catch (IOException e) {
// Not expected to happen because process is already dead anyway.
// Don't hide any real exception by throwing this one.
}
finished = true;
}
}
Aggregations