org.osgl.util.E Java Examples

The following examples show how to use org.osgl.util.E. 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: ControllerEnhancerTest.java    From actframework with Apache License 2.0 6 votes vote down vote up
/**
 * GH issue #2
 * @throws Exception
 */
@Test
public void voidResultWithParamAppCtxFieldAndEmptyBody() throws Exception {
    prepare("VoidResultWithParamCtxFieldEmptyBody");
    m = method(String.class, int.class);
    //ctx.saveLocal();
    try {
        m.invoke(c, "foo", 100);
        fail("It shall throw out a Result");
    } catch (InvocationTargetException e) {
        Throwable r = e.getCause();
        yes(r instanceof Result, "r shall be of type Result, found: %s", E.stackTrace(r));
        eq(100, ctx.renderArg("age"));
        eq("foo", ctx.renderArg("who"));
    }
}
 
Example #2
Source File: AppManager.java    From actframework with Apache License 2.0 6 votes vote down vote up
private Iterator<App> appIterator() {
    final Iterator<App> itrByPort = byPort.values().iterator();
    return new Iterator<App>() {
        boolean byPortFinished = !itrByPort.hasNext();

        @Override
        public boolean hasNext() {
            if (!byPortFinished) {
                byPortFinished = !itrByPort.hasNext();
            }
            return !byPortFinished;
        }

        @Override
        public App next() {
            return byPortFinished ? null : itrByPort.next();
        }

        @Override
        public void remove() {
            E.unsupport();
        }
    };
}
 
Example #3
Source File: StringValueResolverManager.java    From actframework with Apache License 2.0 6 votes vote down vote up
public <T> StringValueResolver<T> arrayResolver(final Class<T> targetType, final char separator) {
    final Class<?> componentType = targetType.getComponentType();
    E.unexpectedIf(null == componentType, "specified target type is not array type: " + targetType);
    final StringValueResolver elementResolver = resolver(componentType);
    return new StringValueResolver<T>(targetType) {
        @Override
        public T resolve(String value) {
            List list = new ArrayList();
            List<String> parts = S.fastSplit(value, String.valueOf(separator));
            for (String part : parts) {
                list.add(elementResolver.resolve(part));
            }
            T array = (T) Array.newInstance(componentType, list.size());
            return (T)list.toArray((Object[])array);
        }
    };
}
 
Example #4
Source File: HeaderValueLoader.java    From actframework with Apache License 2.0 6 votes vote down vote up
public HeaderValueLoader(String name, BeanSpec beanSpec) {
    this.key = key(name, beanSpec);
    this.targetType = beanSpec.rawType();
    this.isArray = targetType.isArray();
    this.multiValues = (isArray || Collection.class.isAssignableFrom(targetType));
    if (this.isArray) {
        this.elementType = this.targetType.getComponentType();
    } else if (this.multiValues) {
        this.elementType = (Class)(beanSpec.typeParams().get(0));
    } else {
        this.elementType = null;
    }
    Class effectiveType = null != elementType ? elementType : targetType;
    this.stringValueResolver = App.instance().resolverManager().resolver(effectiveType, beanSpec);
    E.illegalArgumentIf(null == this.stringValueResolver, "Cannot find out StringValueResolver for %s", beanSpec);
    DefaultValue defValAnno = beanSpec.getAnnotation(DefaultValue.class);
    if (null != defValAnno) {
        this.defVal = stringValueResolver.resolve(defValAnno.value());
    } else {
        this.defVal = StringValueResolverValueLoaderBase.defVal(null, effectiveType);
    }
}
 
Example #5
Source File: ZXingResult.java    From actframework with Apache License 2.0 6 votes vote down vote up
private void renderCode(H.Response response) {
    response.contentType("image/png");
    Map<EncodeHintType, Object> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, Act.appConfig().encoding());
    hints.put(EncodeHintType.MARGIN, 0);
    ErrorCorrectionLevel level = errorCorrectionLevel();
    if (null != level) {
        hints.put(EncodeHintType.ERROR_CORRECTION, level);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    try {
        BitMatrix bitMatrix = writer.encode(getMessage(), barcodeFormat(), width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, "png", response.outputStream());
    } catch (Exception e) {
        throw E.unexpected(e);
    }
}
 
Example #6
Source File: ActError.java    From actframework with Apache License 2.0 6 votes vote down vote up
public static SourceInfo loadSourceInfo(StackTraceElement[] stackTraceElements, Class<? extends ActError> errClz) {
    E.illegalStateIf(Act.isProd());
    DevModeClassLoader cl = (DevModeClassLoader) App.instance().classLoader();
    String errClzName = errClz.getName();
    for (StackTraceElement stackTraceElement : stackTraceElements) {
        int line = stackTraceElement.getLineNumber();
        if (line <= 0) {
            continue;
        }
        String className = stackTraceElement.getClassName();
        if (S.eq(className, errClzName)) {
            continue;
        }
        Source source = cl.source(className);
        if (null == source) {
            continue;
        }
        return new SourceInfoImpl(source, line);
    }
    return null;
}
 
Example #7
Source File: ActErrorResult.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Deprecated
public static Result of(int statusCode) {
    E.illegalArgumentIf(statusCode < 400);
    switch (statusCode) {
        case 400:
            return ActBadRequest.create();
        case 401:
            return ActUnauthorized.create();
        case 403:
            return ActForbidden.create();
        case 404:
            return ActNotFound.create();
        case 405:
            return ActMethodNotAllowed.create();
        case 409:
            return ActConflict.create();
        case 501:
            return ActNotImplemented.create();
        default:
            if (Act.isDev()) {
                return new ActErrorResult(new RuntimeException());
            } else {
                return new ErrorResult(H.Status.of(statusCode));
            }
    }
}
 
Example #8
Source File: ConfigResourceLoader.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
protected void initialized() {
    String path = (String) options.get("value");
    E.unexpectedIf(S.blank(path), "resource path not specified");
    while (path.startsWith("/")) {
        path = path.substring(1);
    }
    if (path.startsWith("config/")) {
        path = path.substring(7);
    }
    resource = ResourceLoader._load(profileConfig(path), spec, hint, true);
    if (null == resource) {
        resource = ResourceLoader._load(commonConfig(path), spec, hint, true);
    }
    if (null == resource) {
        resource = ResourceLoader._load(confConfig(path), spec, hint, true);
    }
    if (null == resource) {
        resource = ResourceLoader._load(path, spec, hint, true);
    }
    if (null == resource && !ignoreResourceNotFound) {
        LOGGER.warn("config resource not found: %s", path);
    }
}
 
Example #9
Source File: ArrayReverse.java    From java-tool with Apache License 2.0 6 votes vote down vote up
public T[] reverse(T[] ts, int from, int to) {
    E.NPE(ts);
    Util.checkIndex(ts, from, to);
    if (to < from) {
        int t = to; to = from; from = t;
    }
    int len = to - from;
    T[] newTs = $.newArray(ts, len);
    if (0 == len) {
        return newTs;
    }
    int steps = len / 2, max = to - 1;
    for (int i = from; i < from + steps; ++i) {
        newTs[i] = ts[max - i];
        newTs[max - i] = ts[i];
    }
    return newTs;
}
 
Example #10
Source File: JobAnnotationProcessor.java    From actframework with Apache License 2.0 6 votes vote down vote up
private String evaluateExpression(String expression, Class<? extends Annotation> annoClass) {
    String prefix = annoClass.getSimpleName();
    if (S.eq(FixedDelay.class.getName(), prefix)) {
        prefix = "fixed-delay";
    } else {
        prefix = prefix.toLowerCase();
    }
    String ret = expression.trim();
    if (ret.startsWith(prefix)) {
        ret = (String) app().config().get(expression);
        if (S.blank(ret)) {
            throw E.invalidConfiguration("Expression configuration not found: %s", expression);
        }
    }
    return ret;
}
 
Example #11
Source File: AppScanner.java    From actframework with Apache License 2.0 6 votes vote down vote up
private ProjectLayout probeLayoutPropertiesFile(File appBase) {
    File f = new File(appBase, ProjectLayout.PROJ_LAYOUT_FILE);
    if (f.exists() && f.canRead()) {
        Properties p = new Properties();
        InputStream is = IO.is(f);
        try {
            p.load(is);
        } catch (IOException e) {
            throw E.ioException(e);
        } finally {
            IO.close(is);
        }
        return ProjectLayout.util.build(p);
    } else {
        return null;
    }
}
 
Example #12
Source File: ThrottleFilter.java    From actframework with Apache License 2.0 5 votes vote down vote up
public ThrottleFilter(int throttle, boolean expireScale) {
    E.illegalArgumentIf(throttle < 1);
    this.throttle = throttle;
    this.expireScale = expireScale;
    final App app = Act.app();
    app.jobManager().on(SysEventId.CLASS_LOADER_INITIALIZED, "ThrottleFilter:initCache", new Runnable() {
        @Override
        public void run() {
            cache = app.cache(CACHE_NAME);
        }
    }, true);
}
 
Example #13
Source File: HeaderValueLoader.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Map<String, Object> map, BeanSpec beanSpec) {
    this.headerName = (String) map.get("value");
    if (S.blank(headerName)) {
        this.headerName = beanSpec.name();
    }
    E.unexpectedIf(S.blank(headerName), "header name not found");
    this.headerName = Keyword.of(this.headerName).httpHeader();
    this.targetType = beanSpec.rawType();
}
 
Example #14
Source File: ClassFilter.java    From actframework with Apache License 2.0 5 votes vote down vote up
public ClassFilter(boolean publicOnly, boolean noAbstract, Class<SUPER_TYPE> superType, Class<ANNOTATION_TYPE> annotationType) {
    E.npeIf(superType == null && annotationType == null);
    this.superType = superType;
    this.annotationType = annotationType;
    this.noAbstract = noAbstract;
    this.publicOnly = publicOnly;
}
 
Example #15
Source File: EndpointTester.java    From actframework with Apache License 2.0 5 votes vote down vote up
public ReqBuilder param(String key, Object val) {
    E.illegalArgumentIf(S.blank(key));
    if (method == H.Method.GET) {
        sb.append(paramAttached ? "&" : "?");
        paramAttached = true;
        sb.append(key).append("=").append(Codec.encodeUrl(S.string(val)));
    } else {
        postParams.add($.T2(key, val));
    }
    return this;
}
 
Example #16
Source File: UploadFileStorageService.java    From actframework with Apache License 2.0 5 votes vote down vote up
private boolean checkThresholding(int bytes) {
    if (!exceedThreshold && (written + bytes > threshold)) {
        exceedThreshold = true;
        fileOutputStream = createFileOutputStream();
        try {
            fileOutputStream.write(buf, 0, written);
        } catch (IOException e) {
            throw E.ioException(e);
        }
    }
    return exceedThreshold;
}
 
Example #17
Source File: SenderEnhancer.java    From actframework with Apache License 2.0 5 votes vote down vote up
void appendTo(InsnList list, int varIndex, String type) {
    super.appendTo(list, varIndex, type);
    String owner, desc;
    switch (type.hashCode()) {
        case _I:
            owner = "java/lang/Integer";
            desc = "(I)Ljava/lang/Integer;";
            break;
        case _Z:
            owner = "java/lang/Boolean";
            desc = "(Z)Ljava/lang/Boolean;";
            break;
        case _S:
            owner = "java/lang/Short";
            desc = "(S)Ljava/lang/Short";
            break;
        case _B:
            owner = "java/lang/Byte";
            desc = "(B)Ljava/lang/Byte;";
            break;
        case _C:
            owner = "java/lang/Character";
            desc = "(C)Ljava/lang/Character;";
            break;
        default:
            throw E.unexpected("int var type not recognized: %s", type);
    }
    MethodInsnNode method = new MethodInsnNode(INVOKESTATIC, owner, "valueOf", desc, false);
    list.add(method);
}
 
Example #18
Source File: SimpleProgressGauge.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public void stepTo(int steps) {
    E.illegalArgumentIf(steps < 0);
    if (null != delegate) {
        delegate.stepTo(steps);
    } else {
        if (currentSteps != steps) {
            currentSteps = steps;
            triggerUpdateEvent();
        }
    }
}
 
Example #19
Source File: SimpleProgressGauge.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static SimpleProgressGauge wrap(ProgressGauge progressGauge) {
    E.NPE(progressGauge);
    if (progressGauge instanceof SimpleProgressGauge) {
        return (SimpleProgressGauge) progressGauge;
    }
    return new SimpleProgressGauge(progressGauge);
}
 
Example #20
Source File: CliContext.java    From actframework with Apache License 2.0 5 votes vote down vote up
private void print0(String template, Object... args) {
    try {
        console.print(S.fmt(template, args));
    } catch (IOException e) {
        throw E.ioException(e);
    }
}
 
Example #21
Source File: TestServerBootstrapClassLoader.java    From actframework with Apache License 2.0 5 votes vote down vote up
protected byte[] tryLoadResource(String name) {
    if (!name.startsWith("act.")) return null;
    String fn = ClassNames.classNameToClassFileName(name, true);
    URL url = findResource(fn.substring(1));
    if (null == url) return null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IO.copy(url.openStream(), baos);
        return baos.toByteArray();
    } catch (IOException e) {
        throw E.ioException(e);
    }
}
 
Example #22
Source File: TypeConverterRegistry.java    From java-tool with Apache License 2.0 5 votes vote down vote up
private void registerBuiltInConverters() {
    for (Class<? extends Number> numberClass: N.NUMBER_CLASSES) {
        addIntoPath(keyOf(numberClass, Number.class), new $.TypeConverter(numberClass, Number.class) {
            @Override
            public Object convert(Object o) {
                return o;
            }
        });
        addIntoPath(keyOf(numberClass, String.class), Lang.TypeConverter.ANY_TO_STRING);
    }
    for (Field field : $.TypeConverter.class.getFields()) {
        if ($.TypeConverter.class.isAssignableFrom(field.getType())) {
            try {
                $.TypeConverter converter = $.cast(field.get(null));
                register(converter);
            } catch (IllegalAccessException e) {
                throw E.unexpected(e);
            }
        }
    }
    for (final Map.Entry<Class, Object> nullValEntry : NULL_VALS.entrySet()) {
        register(new $.TypeConverter<Void, Object>(Void.class, nullValEntry.getKey()) {
            @Override
            public Object convert(Void aVoid) {
                return nullValEntry.getValue();
            }
        });
    }
    register(NULL_CONVERTER);
}
 
Example #23
Source File: StringValueResolverValueLoaderBase.java    From actframework with Apache License 2.0 5 votes vote down vote up
public StringValueResolverValueLoaderBase(ParamKey key, DefaultValue def, BeanSpec spec, boolean simpleKeyOnly) {
    E.illegalArgumentIf(simpleKeyOnly && !key.isSimple());
    this.paramSpec = spec;
    this.param = spec.getAnnotation(Param.class);
    this.paramKey = key;
    this.defSpec = def;
    this.resolverManager = Act.app().resolverManager();
    this.injector = Act.app().injector();
    this.requireRuntimeType = !(spec.type() instanceof Class);
    this.stringValueResolver = this.requireRuntimeType ? null : lookupResolver(spec, spec.rawType());
    this.defVal = this.requireRuntimeType ? null : null != def ? this.stringValueResolver.resolve(def.value()) : defVal(param, spec.rawType());
}
 
Example #24
Source File: JobMethodMetaInfo.java    From actframework with Apache License 2.0 5 votes vote down vote up
public List<JobMethodMetaInfo> extendedJobMethodMetaInfoList(App app) {
    E.illegalStateIf(!classInfo().isAbstract(), "this job method meta info is not abstract");
    final List<JobMethodMetaInfo> list = new ArrayList<>();
    final JobClassMetaInfo clsInfo = classInfo();
    String clsName = clsInfo.className();
    ClassNode node = app.classLoader().classInfoRepository().node(clsName);
    if (null == node) {
        return list;
    }
    final JobMethodMetaInfo me = this;
    node.visitTree(new $.Visitor<ClassNode>() {
        @Override
        public void visit(ClassNode classNode) throws $.Break {
            if (!classNode.isAbstract() && classNode.isPublic()) {
                JobClassMetaInfo subClsInfo = new JobClassMetaInfo().className(classNode.name());
                JobMethodMetaInfo subMethodInfo = new JobMethodMetaInfo(subClsInfo, JobMethodMetaInfo.this);
                if (me.isStatic()) {
                    subMethodInfo.invokeStaticMethod();
                } else {
                    subMethodInfo.invokeInstanceMethod();
                }
                subMethodInfo.name(me.name());
                subMethodInfo.returnType(me.returnType());
                list.add(subMethodInfo);
            }
        }
    });
    return list;
}
 
Example #25
Source File: Compare.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(Object value) {
    E.illegalArgumentIfNot(value instanceof Comparable);
    Class<?> commonSuperType = $.commonSuperTypeOf(initVal, value);
    E.illegalArgumentIfNot(Comparable.class.isAssignableFrom(commonSuperType), "Expected value (%s) cannot be compared to found value (%s)", initVal, value);
    Comparable expected = (Comparable) this.initVal;
    Comparable found = (Comparable) value;
    return type.applyTo(expected, found);
}
 
Example #26
Source File: ReflectedInvokerHelper.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static Method overwrittenMethodOf(Method method) {
    Class host = method.getDeclaringClass();
    Class base = host.getSuperclass();
    try {
        return base.getMethod(method.getName(), method.getParameterTypes());
    } catch (NoSuchMethodException e) {
        throw E.unexpected("Unable to find the overwritten method of " + method);
    }
}
 
Example #27
Source File: JobTrigger.java    From actframework with Apache License 2.0 5 votes vote down vote up
static JobTrigger of(AppConfig config, Every anno) {
    String duration = anno.value();
    if (duration.startsWith("every.")) {
        duration = (String) config.get(duration);
    } else if (duration.startsWith("${") && duration.endsWith("}")) {
        duration = duration.substring(2, duration.length() - 1);
        duration = (String) config.get(duration);
    }
    if (S.blank(duration)) {
        throw E.invalidConfiguration("Cannot find configuration for duration: %s", anno.value());
    }
    return every(duration, anno.startImmediately());
}
 
Example #28
Source File: ControllerEnhancerTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Test
public void templatePathShallBeSetWithoutRenderArgsWithReturnType() throws Exception {
    prepare("TemplatePathShallBeSetWithoutRenderArgsWithReturnType");
    m = method();
    try {
        m.invoke(c);
        eq("/template", ctx.templatePath());
    } catch (InvocationTargetException e) {
        fail("it shall not throw exception here: %s", E.stackTrace(e.getTargetException()));
    }
}
 
Example #29
Source File: JobTrigger.java    From actframework with Apache License 2.0 5 votes vote down vote up
static JobTrigger of(AppConfig config, Cron anno) {
    String v = anno.value();
    if (v.startsWith("cron.")) {
        v = (String) config.get(v);
    } else if (v.startsWith("${") && v.endsWith("}")) {
        v = v.substring(2, v.length() - 1);
        v = (String) config.get(v);
    }
    if (S.blank(v)) {
        throw E.invalidConfiguration("Cannot find configuration for cron: %s", anno.value());
    }
    return cron(v);
}
 
Example #30
Source File: CliContext.java    From actframework with Apache License 2.0 5 votes vote down vote up
private void println0(String template, Object... args) {
    try {
        if (args.length > 0) {
            template = S.fmt(template);
        }
        console.println(template);
    } catch (IOException e) {
        throw E.ioException(e);
    }
}