Java Code Examples for org.osgl.util.E#unexpected()

The following examples show how to use org.osgl.util.E#unexpected() . 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: 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 2
Source File: ActProviders.java    From actframework with Apache License 2.0 6 votes vote down vote up
public static void registerBuiltInNamedProviders(Class<?> providersClass, $.Func2<Class, NamedProvider, ?> register) {
    for (Field field : providersClass.getDeclaredFields()) {
        try {
            if (NamedProvider.class.isAssignableFrom(field.getType())) {
                field.setAccessible(true);
                Type type = field.getGenericType();
                if (type instanceof ParameterizedType) {
                    ParameterizedType ptype = $.cast(field.getGenericType());
                    NamedProvider<?> provider = $.cast(field.get(null));
                    register.apply((Class) ptype.getActualTypeArguments()[0], provider);
                }
            }
        } catch (Exception e) {
            throw E.unexpected(e);
        }
    }
}
 
Example 3
Source File: ActProviders.java    From actframework with Apache License 2.0 6 votes vote down vote up
public static void registerBuiltInProviders(Class<?> providersClass, $.Func2<Class, Provider, ?> register) {
    for (Field field : providersClass.getDeclaredFields()) {
        try {
            if (Provider.class.isAssignableFrom(field.getType())) {
                field.setAccessible(true);
                Type type = field.getGenericType();
                if (type instanceof ParameterizedType) {
                    ParameterizedType ptype = $.cast(field.getGenericType());
                    Provider<?> provider = $.cast(field.get(null));
                    register.apply((Class) ptype.getActualTypeArguments()[0], provider);
                }
            }
        } catch (Exception e) {
            throw E.unexpected(e);
        }
    }
}
 
Example 4
Source File: UndertowNetwork.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
public void bootUp() {
    try {
        xnio = Xnio.getInstance(UndertowNetwork.class.getClassLoader());
        // abcdefgdgd1234566789(dddd)
        worker = createWorker();
        socketOptions = createSocketOptions();
        serverOptions = OptionMap.builder()
                .set(UndertowOptions.BUFFER_PIPELINED_DATA, true)
                .set(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, false)
                .set(UndertowOptions.ALWAYS_SET_DATE, true)
                .set(UndertowOptions.RECORD_REQUEST_START_TIME, false)
                .set(UndertowOptions.NO_REQUEST_TIMEOUT, 60 * 1000)
                .set(UndertowOptions.ENABLE_STATISTICS, Act.conf().xioStatistics())
                .getMap();
        channels = new ArrayList<>();
    } catch (Exception e) {
        throw E.unexpected(e, "Error booting up Undertow service: %s", e.getMessage());
    }
}
 
Example 5
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 6
Source File: DataObjectEnhancerTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
private void happyBirthday(Object o) {
    try {
        happyBirthday.invoke(o);
    } catch (Exception e) {
        throw E.unexpected(e);
    }
}
 
Example 7
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 8
Source File: RequestTemplateManager.java    From actframework with Apache License 2.0 5 votes vote down vote up
public void load() {
    String content = getResourceAsString("requests.yml");
    if (null != content) {
        try {
            doParse(content);
        } catch (RuntimeException e) {
            throw E.unexpected(e, "Error loading requests.yml");
        }
    }
    addBuildInTemplates();
}
 
Example 9
Source File: StringValueResolverValueLoader.java    From actframework with Apache License 2.0 5 votes vote down vote up
private Object load(ParamTree tree, ActContext context) {
    ParamTreeNode node = tree.node(paramKey, context);
    if (null == node) {
        return null;
    }
    if (!node.isLeaf()) {
        throw E.unexpected("Expect leaf node, found: \n%s", node.debug());
    }
    String value = node.value();
    return (null == value) ? null : stringValueResolver.resolve(value);
}
 
Example 10
Source File: UploadFileStorageService.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static UploadFileStorageService create(App app) {
    File tmp = app.tmpDir();
    if (!tmp.exists() && !tmp.mkdirs()) {
        throw E.unexpected("Cannot create tmp dir");
    }
    Map<String, String> conf = C.newMap("storage.fs.home.dir", Files.file(app.tmpDir(), "uploads").getAbsolutePath(),
            "storage.keygen", KeyGenerator.Predefined.BY_DATE.name());
    conf.put(IStorageService.CONF_ID, "__upload");
    conf.put("storage.storeSuffix", "false");
    return new UploadFileStorageService(conf, app.config().uploadInMemoryCacheThreshold());
}
 
Example 11
Source File: IdGenerator.java    From actframework with Apache License 2.0 5 votes vote down vote up
public static EffectiveBytes valueOf(int n) {
    switch (n) {
        case 1: return ONE;
        case 2: return TWO;
        case 3: return THREE;
        case 4: return FOUR;
        default :
            throw E.unexpected("Invalid EffectiveByte value: %s. Expected: 1 - 4", n);
    }
}
 
Example 12
Source File: EventBus.java    From actframework with Apache License 2.0 5 votes vote down vote up
private <T extends EventObject> void callOn(final T event, List<? extends ActEventListener> listeners, boolean async) {
    if (null == listeners) {
        return;
    }
    JobManager jobManager = null;
    if (async) {
        jobManager = app().jobManager();
    }
    Set<ActEventListener> toBeRemoved = C.newSet();
    try {
        for (final ActEventListener l : listeners) {
            if (!async) {
                boolean result = callOn(event, l);
                if (result && once) {
                    toBeRemoved.add(l);
                }
            } else {
                jobManager.now(new Runnable() {
                    @Override
                    public void run() {
                        callOn(event, l);
                    }
                }, event instanceof SysEvent);
            }
        }
    } catch (ConcurrentModificationException e) {
        String eventName;
        if (event instanceof SysEvent) {
            eventName = event.toString();
        } else {
            eventName = event.getClass().getName();
        }
        throw E.unexpected("Concurrent modification issue encountered on handling event: " + eventName);
    }
    if (once && !toBeRemoved.isEmpty()) {
        listeners.removeAll(toBeRemoved);
    }
}
 
Example 13
Source File: EventBus.java    From actframework with Apache License 2.0 5 votes vote down vote up
static IdType typeOf(Object id) {
    if (id instanceof String) {
        return IdType.STRING;
    } else if (Enum.class.isInstance(id)) {
        return IdType.ENUM;
    } else {
        Class<?> type = id instanceof Class ? (Class<?>) id : id.getClass();
        if (Enum.class.isAssignableFrom(type) || EventObject.class.isAssignableFrom(type)) {
            return IdType.CLASS;
        } else {
            throw E.unexpected("Invalid event type: %s", id);
        }
    }
}
 
Example 14
Source File: BootstrapClassLoaderTestRunner.java    From actframework with Apache License 2.0 5 votes vote down vote up
private static void packageJarInto(File from, File to, String selector) {
    try {
        String cmd = S.fmt("jar cf %s %s", to.getAbsolutePath(), selector);
        Process p = Runtime.getRuntime().exec(cmd.split("[\\s]+"), null, from);
        p.waitFor();
        String out = IO.readContentAsString(p.getInputStream());
        String err = IO.readContentAsString(p.getErrorStream());
    } catch (Exception e) {
        throw E.unexpected(e);
    }
}
 
Example 15
Source File: HMAC.java    From actframework with Apache License 2.0 5 votes vote down vote up
Mac macOf(String key) {
    try {
        SecretKeySpec spec = new SecretKeySpec(key.getBytes(Charset.forName("UTF-8")), javaName);
        Mac mac = Mac.getInstance(javaName);
        mac.init(spec);
        return mac;
    } catch (Exception e) {
        throw E.unexpected(e);
    }
}
 
Example 16
Source File: AppCompiler.java    From actframework with Apache License 2.0 5 votes vote down vote up
private NameEnvironmentAnswer findType(String type) {
    try {
        byte[] bytes;
        Source source;
        if (Act.isDev()) {
            source = classLoader.source(type);
            if (null != source) {
                return new NameEnvironmentAnswer(source.compilationUnit(), null);
            }
        }
        bytes = classLoader.enhancedBytecode(type);
        if (bytes != null) {
            ClassFileReader classFileReader = new ClassFileReader(bytes, type.toCharArray(), true);
            return new NameEnvironmentAnswer(classFileReader, null);
        } else {
            if (type.startsWith("org.osgl") || type.startsWith("java.") || type.startsWith("javax.")) {
                return null;
            }
        }
        if (Act.isDev()) {
            return null;
        }
        source = classLoader.source(type);
        if (null == source) {
            return null;
        } else {
            return new NameEnvironmentAnswer(source.compilationUnit(), null);
        }
    } catch (ClassFormatException e) {
        throw E.unexpected(e);
    }
}
 
Example 17
Source File: EnvMatcher.java    From actframework with Apache License 2.0 5 votes vote down vote up
private void initType(String desc) {
    if (desc.contains("Profile")) {
        type = Type.Profile;
    } else if (desc.contains("Mode")) {
        type = Type.Mode;
    } else if (desc.contains("Group")) {
        type = Type.Group;
    } else {
        throw E.unexpected("Unknown Env annotation: %s", desc);
    }
}
 
Example 18
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 19
Source File: JobByteCodeScanner.java    From actframework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
    AnnotationVisitor av = super.visitAnnotation(desc, visible);
    Type type = Type.getType(desc);
    String className = type.getClassName();
    try {
        Class<? extends Annotation> c = (Class<? extends Annotation>)Class.forName(className);
        if (JobClassMetaInfo.isActionAnnotation(c)) {
            markRequireScan();
            if (null == methodInfo) {
                JobMethodMetaInfo tmp = new JobMethodMetaInfo(classInfo, paramTypes);
                methodInfo = tmp;
                classInfo.addAction(tmp);
                this.aav = new ActionAnnotationVisitor(av, c, methodInfo);
            } else {
                this.aav.add(c);
            }
            return this.aav;
        } else if (Env.isEnvAnnotation(c)) {
            this.eav = new EnvAnnotationVisitor(av, desc);
            return this.eav;
        }
    } catch (Exception e) {
        throw E.unexpected(e);
    }
    //markNotTargetClass();
    return av;
}
 
Example 20
Source File: ServerBootstrapClassLoader.java    From actframework with Apache License 2.0 4 votes vote down vote up
private void verifyHome() {
    if (!verifyDir(lib) || !verifyDir(plugin)) {
        throw E.unexpected("Cannot load Act: can't find lib or plugin dir");
    }
}