Search in sources :

Example 16 with InvalidException

use of org.rx.exception.InvalidException in project rxlib by RockyLOMO.

the class YamlConfiguration method enableWatch.

public synchronized YamlConfiguration enableWatch(@NonNull String outputFile) {
    if (watcher != null) {
        throw new InvalidException("Already watched");
    }
    if (!yaml.isEmpty()) {
        try (FileStream fs = new FileStream(outputFile)) {
            fs.setPosition(0);
            fs.writeString(new Yaml().dumpAsMap(yaml));
            fs.flip();
        }
    }
    watcher = new FileWatcher(Files.getFullPath(this.outputFile = outputFile), p -> p.toString().equals(this.outputFile));
    watcher.onChanged.combine((s, e) -> {
        String filePath = e.getPath().toString();
        log.info("Config changing {} {} -> {}", e.isCreate(), filePath, yaml);
        synchronized (this) {
            yaml.clear();
            if (!e.isDelete()) {
                write(filePath);
            }
        }
        log.info("Config changed {} {} -> {}", e.isCreate(), filePath, yaml);
        raiseEvent(onChanged, new ChangedEventArgs(filePath));
    });
    return this;
}
Also used : java.util(java.util) Getter(lombok.Getter) ApplicationException(org.rx.exception.ApplicationException) NonNull(lombok.NonNull) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Extends.values(org.rx.core.Extends.values) InvalidException(org.rx.exception.InvalidException) Extends.as(org.rx.core.Extends.as) CollectionUtils(org.apache.commons.collections4.CollectionUtils) File(java.io.File) Yaml(org.yaml.snakeyaml.Yaml) Slf4j(lombok.extern.slf4j.Slf4j) FileWatcher(org.rx.io.FileWatcher) Files(org.rx.io.Files) JSONObject(com.alibaba.fastjson.JSONObject) FileStream(org.rx.io.FileStream) ErrorCode(org.rx.annotation.ErrorCode) InputStream(java.io.InputStream) FileWatcher(org.rx.io.FileWatcher) InvalidException(org.rx.exception.InvalidException) FileStream(org.rx.io.FileStream) Yaml(org.yaml.snakeyaml.Yaml)

Example 17 with InvalidException

use of org.rx.exception.InvalidException in project rxlib by RockyLOMO.

the class Reflects method changeType.

@SuppressWarnings(NON_RAW_TYPES)
@ErrorCode("enumError")
@ErrorCode(cause = NoSuchMethodException.class)
@ErrorCode(cause = ReflectiveOperationException.class)
public static <T> T changeType(Object value, @NonNull Class<T> toType) {
    if (value == null) {
        if (!toType.isPrimitive()) {
            if (toType == List.class) {
                return (T) Collections.emptyList();
            }
            if (toType == Map.class) {
                return (T) Collections.emptyMap();
            }
            return null;
        }
        if (toType == boolean.class) {
            return (T) Boolean.FALSE;
        } else {
            value = 0;
        }
    }
    Object fValue = value;
    if (toType == String.class) {
        value = value.toString();
    } else if (toType == UUID.class) {
        value = UUID.fromString(value.toString());
    } else if (toType == BigDecimal.class) {
        value = new BigDecimal(value.toString());
    } else if (toType.isEnum()) {
        boolean failBack = true;
        if (NEnum.class.isAssignableFrom(toType)) {
            if (value instanceof String) {
                try {
                    value = Integer.valueOf((String) value);
                } catch (NumberFormatException e) {
                // ignore
                }
            }
            if (value instanceof Number) {
                int val = ((Number) value).intValue();
                value = NEnum.valueOf((Class) toType, val);
                failBack = false;
            }
        }
        if (failBack) {
            String val = value.toString();
            value = NQuery.of(toType.getEnumConstants()).singleOrDefault(p -> ((Enum) p).name().equals(val));
        }
        if (value == null) {
            throw new ApplicationException("enumError", values(fValue, toType.getSimpleName()));
        }
    } else if (!toType.isPrimitive() && TypeUtils.isInstance(value, toType)) {
    // int to long | int to Object ok, DO NOTHING
    // long to int not ok
    } else {
        Class<?> fromType = value.getClass();
        try {
            toType = (Class) primitiveToWrapper(toType);
            if (toType == Boolean.class && value instanceof Number) {
                int val = ((Number) value).intValue();
                if (val == 0) {
                    value = Boolean.FALSE;
                } else if (val == 1) {
                    value = Boolean.TRUE;
                } else {
                    throw new InvalidException("Value should be 0 or 1");
                }
            } else {
                NQuery<Method> methods = getMethodMap(toType).get(CHANGE_TYPE_METHOD);
                if (methods == null || fromType.isEnum()) {
                    Class<T> fType = toType;
                    ConvertBean convertBean = NQuery.of(CONVERT_BEANS).firstOrDefault(p -> TypeUtils.isInstance(fValue, p.baseFromType) && p.toType.isAssignableFrom(fType));
                    if (convertBean != null) {
                        return (T) convertBean.converter.apply(value, convertBean.toType);
                    }
                    throw new NoSuchMethodException(CHANGE_TYPE_METHOD);
                }
                if (isAssignable(toType, Number.class)) {
                    if (value instanceof Boolean) {
                        if (!(Boolean) value) {
                            value = "0";
                        } else {
                            value = "1";
                        }
                    } else if (value instanceof Number) {
                        // BigDecimal 1.001 to 1
                        Number num = (Number) value;
                        if (toType == Integer.class) {
                            value = num.intValue();
                        } else if (toType == Long.class) {
                            value = num.longValue();
                        } else if (toType == Byte.class) {
                            value = num.byteValue();
                        } else if (toType == Short.class) {
                            value = num.shortValue();
                        }
                    }
                }
                Method m = null;
                for (Method p : methods) {
                    if (!(p.getParameterCount() == 1 && p.getParameterTypes()[0].equals(String.class))) {
                        continue;
                    }
                    m = p;
                    break;
                }
                if (m == null) {
                    m = toType.getDeclaredMethod(CHANGE_TYPE_METHOD, String.class);
                }
                value = m.invoke(null, value.toString());
            }
        } catch (NoSuchMethodException e) {
            throw new ApplicationException(values(toType), e);
        } catch (ReflectiveOperationException e) {
            throw new ApplicationException(values(fromType, toType, value), e);
        }
    }
    return (T) value;
}
Also used : InvalidException(org.rx.exception.InvalidException) BigDecimal(java.math.BigDecimal) ApplicationException(org.rx.exception.ApplicationException) ErrorCode(org.rx.annotation.ErrorCode)

Example 18 with InvalidException

use of org.rx.exception.InvalidException in project rxlib by RockyLOMO.

the class Reflects method getResource.

public static InputStream getResource(String namePattern) {
    InputStream stream = getClassLoader().getResourceAsStream(namePattern);
    if (stream != null) {
        return stream;
    }
    InputStream in = getResources(namePattern).firstOrDefault();
    if (in == null) {
        throw new InvalidException("Resource %s not found", namePattern);
    }
    return in;
}
Also used : InputStream(java.io.InputStream) InvalidException(org.rx.exception.InvalidException)

Example 19 with InvalidException

use of org.rx.exception.InvalidException in project rxlib by RockyLOMO.

the class EntityDatabase method clearTimeRollingFiles.

public void clearTimeRollingFiles() {
    if (timeRollingPattern == null) {
        throw new InvalidException("Time rolling policy not enabled");
    }
    String p = filePath;
    if (p.startsWith("~/")) {
        p = App.USER_HOME + p.substring(1);
    }
    Files.deleteBefore(Files.getFullPath(p), DateTime.now(timeRollingPattern).addHours(-rollingHours), "*.mv.db");
}
Also used : InvalidException(org.rx.exception.InvalidException) App.toJsonString(org.rx.core.App.toJsonString)

Example 20 with InvalidException

use of org.rx.exception.InvalidException in project rxlib by RockyLOMO.

the class EntityDatabase method delete.

public <T> long delete(EntityQueryLambda<T> query) {
    if (query.conditions.isEmpty()) {
        throw new InvalidException("Forbid: empty condition");
    }
    query.limit(1000);
    SqlMeta meta = getMeta(query.entityType);
    StringBuilder sql = new StringBuilder(meta.deleteSql);
    sql.setLength(sql.length() - 2);
    StringBuilder subSql = new StringBuilder(meta.selectSql);
    replaceSelectColumns(subSql, meta.primaryKey.getKey());
    List<Object> params = new ArrayList<>();
    appendClause(subSql, query, params);
    sql.append(" IN(%s)", subSql);
    String execSql = sql.toString();
    long total = 0;
    int rf;
    while ((rf = executeUpdate(execSql, params)) > 0) {
        total += rf;
    }
    return total;
}
Also used : StringBuilder(org.rx.core.StringBuilder) InvalidException(org.rx.exception.InvalidException) App.toJsonString(org.rx.core.App.toJsonString)

Aggregations

InvalidException (org.rx.exception.InvalidException)29 SneakyThrows (lombok.SneakyThrows)11 App.toJsonString (org.rx.core.App.toJsonString)7 StringBuilder (org.rx.core.StringBuilder)6 Slf4j (lombok.extern.slf4j.Slf4j)5 Field (java.lang.reflect.Field)4 InetSocketAddress (java.net.InetSocketAddress)4 Map (java.util.Map)4 Getter (lombok.Getter)4 NonNull (lombok.NonNull)4 Test (org.junit.jupiter.api.Test)4 org.rx.core (org.rx.core)4 Extends (org.rx.core.Extends)4 ExceptionHandler (org.rx.exception.ExceptionHandler)4 JSONObject (com.alibaba.fastjson.JSONObject)3 RequiredArgsConstructor (lombok.RequiredArgsConstructor)3 DbColumn (org.rx.annotation.DbColumn)3 ErrorCode (org.rx.annotation.ErrorCode)3 App (org.rx.core.App)3 Constants (org.rx.core.Constants)3