use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class Configuration method convertDefaultValue.
@Nullable
private <T> Object convertDefaultValue(String optionName, @Nullable T defaultValue, TypeToken<T> type, @Nullable Annotation secondaryOption) throws InvalidConfigurationException {
@Var TypeToken<?> innerType;
if (type.isArray()) {
innerType = checkNotNull(type.getComponentType());
} else if (COLLECTIONS.containsKey(type.getRawType())) {
innerType = Classes.getSingleTypeArgument(type);
} else {
innerType = type;
}
innerType = innerType.wrap();
checkApplicability(secondaryOption, innerType);
if (type.equals(innerType)) {
// If its not a collection, we try to pass the default value to the
// type converter if there is any.
// TODO: Also pass default values inside a collection.
TypeConverter converter = getConverter(type, secondaryOption);
return converter.convertDefaultValue(optionName, defaultValue, type, secondaryOption);
}
return defaultValue;
}
use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class Configuration method setOptionValueForField.
/**
* This method sets a new value to a field with an {@link Options}-annotation. It takes the name
* and the new value of an option, checks it for allowed values and injects it into the object.
*
* @param obj the object to be injected
* @param field the field of the value to be injected
* @param options options-annotation of the class of the object
*/
private <T> void setOptionValueForField(Object obj, Field field, Options options) throws InvalidConfigurationException, IllegalAccessException {
// check validity of field
if (Modifier.isStatic(field.getModifiers())) {
throw new UnsupportedOperationException("@Option is not allowed on static members");
}
if (Modifier.isFinal(field.getModifiers())) {
throw new UnsupportedOperationException("@Option is not allowed on final fields" + " because Java doesn't guarantee visibility of new value");
}
// try to read default value
@Var Object defaultValue = null;
try {
defaultValue = field.get(obj);
} catch (IllegalArgumentException e) {
throw new AssertionError("Type checks above were not successful apparently.", e);
}
@SuppressWarnings("unchecked") T typedDefaultValue = (T) defaultValue;
// determine type of option
@SuppressWarnings("unchecked") TypeToken<T> type = (TypeToken<T>) TypeToken.of(field.getGenericType());
// get value
Option option = field.getAnnotation(Option.class);
String name = getOptionName(options, field, option);
Object value = getValue(options, field, typedDefaultValue, type, option, field);
// options which were not changed need not to be set
if (value == defaultValue) {
logger.log(Level.CONFIG, "Option:", name, "Class:", field.getDeclaringClass().getName(), "field:", field.getName(), "value: <DEFAULT>");
return;
}
logger.log(Level.CONFIG, "Option:", name, "Class:", field.getDeclaringClass().getName(), "field:", field.getName(), "value:", value);
// set value to field
try {
field.set(obj, value);
} catch (IllegalArgumentException e) {
throw new AssertionError("Type checks above were not successful apparently.", e);
}
}
use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class Configuration method convertSingleValue.
/**
* This function takes a value (String) and a type and returns an Object of this type with the
* value as content.
*
* <p>The type may not be an array or a collection type, and the value may only be a single value
* (not multiple values).
*
* @param optionName name of option, only for error handling
* @param valueStr new value of the option
* @param type type of the object
* @param secondaryOption the optional second annotation of the option (needs to fit to the type)
*/
@Nullable
private Object convertSingleValue(String optionName, @Var String valueStr, @Var TypeToken<?> type, @Nullable Annotation secondaryOption) throws InvalidConfigurationException {
boolean isAnnotated = type.getRawType() == AnnotatedValue.class;
@Var String annotation = null;
if (isAnnotated) {
type = Classes.getSingleTypeArgument(type);
Iterator<String> parts = ANNOTATION_VALUE_SPLITTER.split(valueStr).iterator();
valueStr = parts.next();
annotation = Iterators.getNext(parts, null);
}
// try to find a type converter, either for the type of the annotation
// or for the type of the field
TypeConverter converter = getConverter(type, secondaryOption);
@Var Object result = converter.convert(optionName, valueStr, type, secondaryOption, sources.get(optionName), firstNonNull(logger, LogManager.createNullLogManager()));
if (result != null && isAnnotated) {
result = AnnotatedValue.create(result, Optional.ofNullable(annotation));
}
return result;
}
use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class OptionCollector method getSourceCode.
/**
* This function returns the content of a sourcefile as String.
*
* @param cls the class whose sourcefile should be retrieved
*/
private String getSourceCode(Class<?> cls) {
// get name of sourcefile
@Var String filename = cls.getName().replace('.', File.separatorChar);
// encapsulated classes have a "$" in filename
if (filename.contains("$")) {
filename = filename.substring(0, filename.indexOf('$'));
}
filename += ".java";
try {
Path path = codeSourceToSourcePath.get(cls.getProtectionDomain().getCodeSource());
return MoreFiles.asCharSource(path.resolve(filename), StandardCharsets.UTF_8).read();
} catch (ExecutionException | IOException e) {
// Do not print exception message to avoid having a different error message for each file.
errorMessages.add("INFO: Could not find source files for classes in " + cls.getProtectionDomain().getCodeSource().getLocation());
return "";
}
}
use of com.google.errorprone.annotations.Var in project java-common-lib by sosy-lab.
the class OptionCollector method getDefaultValueFromContent.
/**
* This function searches for fieldstring in content and returns the value of the field.
*
* @param content sourcecode where to search
* @param fieldPattern regexp specifying the name of the field, whose value is returned
*/
private static String getDefaultValueFromContent(String content, String fieldPattern) {
// search for fieldString and get the whole content after it (=rest),
// in 'rest' search for ';' and return all before it (=defaultValue)
@Var String defaultValue = "";
List<String> splitted = Splitter.onPattern(fieldPattern).splitToList(content);
if (splitted.size() > 1) {
// first part is before fieldString, second part is after it
String rest = splitted.get(1);
defaultValue = rest.substring(0, rest.indexOf(';')).trim();
// remove unnecessary parts of field
if (defaultValue.startsWith("=")) {
defaultValue = defaultValue.substring(1).trim();
// remove comments
while (defaultValue.contains("/*")) {
defaultValue = defaultValue.substring(0, defaultValue.indexOf("/*")) + defaultValue.substring(defaultValue.indexOf("*/") + 2);
}
if (defaultValue.contains("//")) {
defaultValue = defaultValue.substring(0, defaultValue.indexOf("//"));
}
// remove brackets from file: new File("example.txt") --> "example.txt"
defaultValue = stripSurroundingFunctionCall(defaultValue, "new File");
defaultValue = stripSurroundingFunctionCall(defaultValue, "Paths.get");
defaultValue = stripSurroundingFunctionCall(defaultValue, "new Path");
defaultValue = stripSurroundingFunctionCall(defaultValue, "Pattern.compile");
defaultValue = stripSurroundingFunctionCall(defaultValue, "PathTemplate.ofFormatString");
defaultValue = stripSurroundingFunctionCall(defaultValue, "PathCounterTemplate.ofFormatString");
if (defaultValue.startsWith("TimeSpan.ofNanos(")) {
defaultValue = defaultValue.substring("TimeSpan.ofNanos(".length(), defaultValue.length() - 1) + "ns";
}
if (defaultValue.startsWith("TimeSpan.ofMillis(")) {
defaultValue = defaultValue.substring("TimeSpan.ofMillis(".length(), defaultValue.length() - 1) + "ms";
}
if (defaultValue.startsWith("TimeSpan.ofSeconds(")) {
defaultValue = defaultValue.substring("TimeSpan.ofSeconds(".length(), defaultValue.length() - 1) + "s";
}
@Var Matcher match = IMMUTABLE_SET_PATTERN.matcher(defaultValue);
if (match.matches()) {
defaultValue = "{" + match.group(2) + "}";
}
match = IMMUTABLE_LIST_PATTERN.matcher(defaultValue);
if (match.matches()) {
defaultValue = "[" + match.group(2) + "]";
}
}
} else {
// special handling for generics
String stringSetFieldPattern = fieldPattern.replace("\\s+Set\\s+", "\\s+Set<String>\\s+");
if (content.contains(stringSetFieldPattern)) {
return getDefaultValueFromContent(content, stringSetFieldPattern);
}
// TODO: other types of generics?
}
return defaultValue.trim();
}
Aggregations