Search in sources :

Example 1 with InvalidConfigurationException

use of org.sosy_lab.common.configuration.InvalidConfigurationException in project java-common-lib by sosy-lab.

the class IntegerTypeConverter 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 IntegerOption)) {
        throw new UnsupportedOperationException("IntegerTypeConverter needs options annotated with @IntegerOption");
    }
    IntegerOption option = (IntegerOption) pOption;
    assert type.equals(Integer.class) || type.equals(Long.class);
    Object value = BaseTypeConverter.valueOf(type, optionName, valueStr);
    long n = ((Number) value).longValue();
    if (option.min() > n || n > option.max()) {
        throw new InvalidConfigurationException(String.format("Invalid value in configuration file: \"%s = %s\" (not in range [%d, %d]).", optionName, value, option.min(), option.max()));
    }
    return value;
}
Also used : IntegerOption(org.sosy_lab.common.configuration.IntegerOption) InvalidConfigurationException(org.sosy_lab.common.configuration.InvalidConfigurationException)

Example 2 with InvalidConfigurationException

use of org.sosy_lab.common.configuration.InvalidConfigurationException 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;
}
Also used : Var(com.google.errorprone.annotations.Var) ClassOption(org.sosy_lab.common.configuration.ClassOption) UnsuitedClassException(org.sosy_lab.common.Classes.UnsuitedClassException) InvalidConfigurationException(org.sosy_lab.common.configuration.InvalidConfigurationException)

Example 3 with InvalidConfigurationException

use of org.sosy_lab.common.configuration.InvalidConfigurationException 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;
}
Also used : Var(com.google.errorprone.annotations.Var) InvalidConfigurationException(org.sosy_lab.common.configuration.InvalidConfigurationException) TimeSpan(org.sosy_lab.common.time.TimeSpan) TimeUnit(java.util.concurrent.TimeUnit) TimeSpanOption(org.sosy_lab.common.configuration.TimeSpanOption)

Example 4 with InvalidConfigurationException

use of org.sosy_lab.common.configuration.InvalidConfigurationException in project java-common-lib by sosy-lab.

the class Classes method createInstance.

/**
 * Creates an instance of class cls, passing the objects from argumentList to the constructor and
 * casting the object to class type.
 *
 * <p>If there is no matching constructor or the the class cannot be instantiated, an
 * InvalidConfigurationException is thrown.
 *
 * @param type The return type (has to be a super type of the class, of course).
 * @param cls The class to instantiate.
 * @param argumentTypes Array with the types of the parameters of the desired constructor
 *     (optional).
 * @param argumentValues Array with the values that will be passed to the constructor.
 * @param exceptionType An exception type the constructor is allowed to throw.
 */
@Deprecated
public static <T, X extends Exception> T createInstance(Class<T> type, Class<? extends T> cls, @Var @Nullable Class<?>[] argumentTypes, Object[] argumentValues, Class<X> exceptionType) throws X, InvalidConfigurationException {
    checkNotNull(exceptionType);
    if (argumentTypes == null) {
        // fill argumenTypes array
        argumentTypes = Stream.of(argumentValues).map(Object::getClass).toArray(Class[]::new);
    } else {
        checkArgument(argumentTypes.length == argumentValues.length);
    }
    String className = cls.getSimpleName();
    String typeName = type.getSimpleName();
    // get constructor
    Constructor<? extends T> ct;
    try {
        ct = cls.getConstructor(argumentTypes);
    } catch (NoSuchMethodException e) {
        throw new InvalidConfigurationException("Invalid " + typeName + " " + className + ", no matching constructor", e);
    }
    // verify signature
    String exception = Classes.verifyDeclaredExceptions(ct, exceptionType, InvalidConfigurationException.class);
    if (exception != null) {
        throw new InvalidConfigurationException(String.format("Invalid %s %s, constructor declares unsupported checked exception %s.", typeName, className, exception));
    }
    // instantiate
    try {
        return ct.newInstance(argumentValues);
    } catch (InstantiationException e) {
        throw new InvalidConfigurationException(String.format("Invalid %s %s, class cannot be instantiated (%s).", typeName, className, e.getMessage()), e);
    } catch (IllegalAccessException e) {
        throw new InvalidConfigurationException("Invalid " + typeName + " " + className + ", constructor is not accessible", e);
    } catch (InvocationTargetException e) {
        Throwable t = e.getCause();
        Throwables.propagateIfPossible(t, exceptionType, InvalidConfigurationException.class);
        throw new UnexpectedCheckedException("instantiation of " + typeName + " " + className, t);
    }
}
Also used : InvocationTargetException(java.lang.reflect.InvocationTargetException) InvalidConfigurationException(org.sosy_lab.common.configuration.InvalidConfigurationException)

Example 5 with InvalidConfigurationException

use of org.sosy_lab.common.configuration.InvalidConfigurationException in project java-common-lib by sosy-lab.

the class FileTypeConverter method convert.

@Override
public Object convert(String optionName, String pValue, TypeToken<?> pType, Annotation secondaryOption, Path pSource, LogManager logger) throws InvalidConfigurationException {
    Class<?> type = pType.getRawType();
    checkApplicability(type, secondaryOption, optionName);
    assert secondaryOption != null : "checkApplicability should ensure this";
    Path path;
    try {
        path = Paths.get(pValue);
    } catch (InvalidPathException e) {
        throw new InvalidConfigurationException(String.format("Invalid file name in option %s: %s", optionName, e.getMessage()), e);
    }
    return handleFileOption(optionName, path, ((FileOption) secondaryOption).value(), type, pSource);
}
Also used : Path(java.nio.file.Path) InvalidPathException(java.nio.file.InvalidPathException) InvalidConfigurationException(org.sosy_lab.common.configuration.InvalidConfigurationException)

Aggregations

InvalidConfigurationException (org.sosy_lab.common.configuration.InvalidConfigurationException)5 Var (com.google.errorprone.annotations.Var)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 InvalidPathException (java.nio.file.InvalidPathException)1 Path (java.nio.file.Path)1 TimeUnit (java.util.concurrent.TimeUnit)1 UnsuitedClassException (org.sosy_lab.common.Classes.UnsuitedClassException)1 ClassOption (org.sosy_lab.common.configuration.ClassOption)1 IntegerOption (org.sosy_lab.common.configuration.IntegerOption)1 TimeSpanOption (org.sosy_lab.common.configuration.TimeSpanOption)1 TimeSpan (org.sosy_lab.common.time.TimeSpan)1