Search in sources :

Example 1 with JCatchBlock

use of com.helger.jcodemodel.JCatchBlock in project androidannotations by androidannotations.

the class RestMethodHandler method surroundWithRestTryCatch.

/**
	 * Adds the try/catch around the rest execution code.
	 *
	 * If an exception is caught, it will first check if the handler is set. If
	 * the handler is set, it will call the handler and return null (or nothing
	 * if void). If the handler isn't set, it will re-throw the exception so
	 * that it behaves as it did previous to this feature.
	 */
private JBlock surroundWithRestTryCatch(RestHolder holder, JBlock block, boolean methodReturnVoid) {
    if (holder.getRestErrorHandlerField() != null) {
        JBlock newBlock = new JBlock().bracesRequired(false).indentRequired(false);
        JTryBlock tryBlock = newBlock._try();
        codeModelHelper.copy(block, tryBlock.body());
        JCatchBlock jCatch = tryBlock._catch(getJClass(NESTED_RUNTIME_EXCEPTION));
        JBlock catchBlock = jCatch.body();
        JConditional conditional = catchBlock._if(JOp.ne(holder.getRestErrorHandlerField(), JExpr._null()));
        JVar exceptionParam = jCatch.param("e");
        JBlock thenBlock = conditional._then();
        // call the handler method if it was set.
        thenBlock.add(holder.getRestErrorHandlerField().invoke("onRestClientExceptionThrown").arg(exceptionParam));
        // return null if exception was caught and handled.
        if (!methodReturnVoid) {
            thenBlock._return(JExpr._null());
        }
        // re-throw the exception if handler wasn't set.
        conditional._else()._throw(exceptionParam);
        return newBlock;
    }
    return block;
}
Also used : JBlock(com.helger.jcodemodel.JBlock) JConditional(com.helger.jcodemodel.JConditional) JTryBlock(com.helger.jcodemodel.JTryBlock) JCatchBlock(com.helger.jcodemodel.JCatchBlock) JVar(com.helger.jcodemodel.JVar)

Example 2 with JCatchBlock

use of com.helger.jcodemodel.JCatchBlock in project androidannotations by androidannotations.

the class TransactionalHandler method process.

@Override
public void process(Element element, EComponentHolder holder) {
    ExecutableElement executableElement = (ExecutableElement) element;
    String returnTypeName = executableElement.getReturnType().toString();
    AbstractJClass returnType = getJClass(returnTypeName);
    JMethod method = codeModelHelper.overrideAnnotatedMethod(executableElement, holder);
    codeModelHelper.removeBody(method);
    JVar db = method.params().get(0);
    JBlock body = method.body();
    body.invoke(db, "beginTransaction");
    JTryBlock tryBlock = body._try();
    IJExpression activitySuper = holder.getGeneratedClass().staticRef("super");
    JInvocation superCall = JExpr.invoke(activitySuper, method);
    for (JVar param : method.params()) {
        superCall.arg(param);
    }
    JBlock tryBody = tryBlock.body();
    if (returnTypeName.equals("void")) {
        tryBody.add(superCall);
        tryBody.invoke(db, "setTransactionSuccessful");
        tryBody._return();
    } else {
        JVar result = tryBody.decl(returnType, "result_", superCall);
        tryBody.invoke(db, "setTransactionSuccessful");
        tryBody._return(result);
    }
    JCatchBlock catchBlock = tryBlock._catch(getJClass(RuntimeException.class));
    JVar exceptionParam = catchBlock.param("e");
    JBlock catchBody = catchBlock.body();
    JInvocation errorInvoke = catchBody.staticInvoke(getClasses().LOG, "e");
    errorInvoke.arg(logTagForClassHolder(holder));
    errorInvoke.arg("Error in transaction");
    errorInvoke.arg(exceptionParam);
    catchBody._throw(exceptionParam);
    tryBlock._finally().invoke(db, "endTransaction");
}
Also used : ExecutableElement(javax.lang.model.element.ExecutableElement) JBlock(com.helger.jcodemodel.JBlock) IJExpression(com.helger.jcodemodel.IJExpression) AbstractJClass(com.helger.jcodemodel.AbstractJClass) JInvocation(com.helger.jcodemodel.JInvocation) JMethod(com.helger.jcodemodel.JMethod) JTryBlock(com.helger.jcodemodel.JTryBlock) JCatchBlock(com.helger.jcodemodel.JCatchBlock) JVar(com.helger.jcodemodel.JVar)

Example 3 with JCatchBlock

use of com.helger.jcodemodel.JCatchBlock in project androidannotations by androidannotations.

the class OrmLiteDaoHandler method assignValue.

@Override
public void assignValue(JBlock targetBlock, IJAssignmentTarget fieldRef, EComponentHolder holder, Element element, Element param) {
    OrmLiteHolder ormLiteHolder = holder.getPluginHolder(new OrmLiteHolder(holder));
    AbstractJClass modelClass = getJClass(ormLiteHelper.getEntityType(param).toString());
    AbstractJClass idClass = getJClass(ormLiteHelper.getEntityIdType(param).toString());
    IJExpression modelClassDotClass = modelClass.dotclass();
    AbstractJClass daoClass = getJClass(OrmLiteClasses.DAO).narrow(modelClass, idClass);
    AbstractJClass daoImplClass = codeModelHelper.typeMirrorToJClass(param.asType());
    TypeMirror databaseHelperTypeMirror = annotationHelper.extractAnnotationParameter(element, "helper");
    JFieldVar databaseHelperRef = ormLiteHolder.getDatabaseHelperRef(databaseHelperTypeMirror);
    IJExpression injectExpr = databaseHelperRef.invoke("getDao").arg(modelClassDotClass);
    if (elementExtendsRuntimeExceptionDao(param)) {
        injectExpr = _new(daoImplClass).arg(cast(daoClass, injectExpr));
    }
    JTryBlock tryBlock = targetBlock._try();
    tryBlock.body().add(fieldRef.assign(injectExpr));
    JCatchBlock catchBlock = tryBlock._catch(getClasses().SQL_EXCEPTION);
    JVar exception = catchBlock.param("e");
    String fieldName = param.getSimpleName().toString();
    //
    catchBlock.body().staticInvoke(getClasses().LOG, //
    "e").arg(//
    logTagForClassHolder(holder)).arg(//
    "Could not create DAO " + fieldName).arg(exception);
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) JFieldVar(com.helger.jcodemodel.JFieldVar) OrmLiteHolder(org.androidannotations.ormlite.holder.OrmLiteHolder) IJExpression(com.helger.jcodemodel.IJExpression) AbstractJClass(com.helger.jcodemodel.AbstractJClass) JTryBlock(com.helger.jcodemodel.JTryBlock) JCatchBlock(com.helger.jcodemodel.JCatchBlock) JVar(com.helger.jcodemodel.JVar)

Example 4 with JCatchBlock

use of com.helger.jcodemodel.JCatchBlock in project androidannotations by androidannotations.

the class BackgroundHandler method process.

@Override
public void process(Element element, EComponentHolder holder) throws Exception {
    ExecutableElement executableElement = (ExecutableElement) element;
    JMethod delegatingMethod = codeModelHelper.overrideAnnotatedMethod(executableElement, holder);
    JBlock previousMethodBody = codeModelHelper.removeBody(delegatingMethod);
    JDefinedClass anonymousTaskClass = getCodeModel().anonymousClass(BackgroundExecutor.Task.class);
    JMethod executeMethod = anonymousTaskClass.method(JMod.PUBLIC, getCodeModel().VOID, "execute");
    executeMethod.annotate(Override.class);
    // Catch exception in user code
    JTryBlock tryBlock = executeMethod.body()._try();
    tryBlock.body().add(previousMethodBody);
    JCatchBlock catchBlock = tryBlock._catch(getClasses().THROWABLE);
    JVar caughtException = catchBlock.param("e");
    IJStatement uncaughtExceptionCall = //
    getClasses().THREAD.staticInvoke(//
    "getDefaultUncaughtExceptionHandler").invoke(//
    "uncaughtException").arg(//
    getClasses().THREAD.staticInvoke("currentThread")).arg(caughtException);
    catchBlock.body().add(uncaughtExceptionCall);
    Background annotation = element.getAnnotation(Background.class);
    String id = annotation.id();
    long delay = annotation.delay();
    String serial = annotation.serial();
    AbstractJClass backgroundExecutorClass = getJClass(BackgroundExecutor.class);
    JInvocation newTask = _new(anonymousTaskClass).arg(lit(id)).arg(lit(delay)).arg(lit(serial));
    JInvocation executeCall = backgroundExecutorClass.staticInvoke("execute").arg(newTask);
    delegatingMethod.body().add(executeCall);
}
Also used : BackgroundExecutor(org.androidannotations.api.BackgroundExecutor) Background(org.androidannotations.annotations.Background) JDefinedClass(com.helger.jcodemodel.JDefinedClass) ExecutableElement(javax.lang.model.element.ExecutableElement) AbstractJClass(com.helger.jcodemodel.AbstractJClass) JInvocation(com.helger.jcodemodel.JInvocation) IJStatement(com.helger.jcodemodel.IJStatement) JBlock(com.helger.jcodemodel.JBlock) JMethod(com.helger.jcodemodel.JMethod) JTryBlock(com.helger.jcodemodel.JTryBlock) JCatchBlock(com.helger.jcodemodel.JCatchBlock) JVar(com.helger.jcodemodel.JVar)

Example 5 with JCatchBlock

use of com.helger.jcodemodel.JCatchBlock in project androidannotations by androidannotations.

the class HttpsClientHandler method assignValue.

@Override
public void assignValue(JBlock targetBlock, IJAssignmentTarget fieldRef, EComponentHolder holder, Element element, Element param) {
    IRInnerClass rInnerClass = getEnvironment().getRClass().get(IRClass.Res.RAW);
    HttpsClient annotation = element.getAnnotation(HttpsClient.class);
    JFieldRef trustStoreRawIdRef = annotationHelper.extractOneAnnotationFieldRef(element, getTarget(), rInnerClass, false, "trustStore", "trustStoreResName");
    JFieldRef keyStoreRawIdRef = annotationHelper.extractOneAnnotationFieldRef(element, getTarget(), rInnerClass, false, "keyStore", "keyStoreResName");
    String trustStorePwd = annotation.trustStorePwd();
    String keyStorePwd = annotation.keyStorePwd();
    boolean allowAllHostnames = annotation.allowAllHostnames();
    boolean useCustomTrustStore = trustStoreRawIdRef != null;
    boolean useCustomKeyStore = keyStoreRawIdRef != null;
    ProcessHolder.Classes classes = getClasses();
    JDefinedClass jAnonClass = getCodeModel().anonymousClass(classes.DEFAULT_HTTP_CLIENT);
    JMethod method = jAnonClass.method(JMod.PROTECTED, classes.CLIENT_CONNECTION_MANAGER, "createClientConnectionManager");
    method.annotate(Override.class);
    JTryBlock jTryBlock = method.body()._try();
    JVar jVarTrusted = null;
    JVar jVarKeystore = null;
    if (useCustomKeyStore) {
        jVarKeystore = jTryBlock.body().decl(classes.KEY_STORE, "keystore");
        jVarKeystore.init(classes.KEY_STORE.staticInvoke("getInstance").arg("BKS"));
    }
    if (useCustomTrustStore || useCustomKeyStore) {
        /*
			 * use default trust store
			 */
        jVarTrusted = jTryBlock.body().decl(classes.KEY_STORE, "trusted");
        jVarTrusted.init(classes.KEY_STORE.staticInvoke("getInstance").arg("BKS"));
    }
    JVar jVarRes = null;
    JVar jVarTrstFile = null;
    JVar jVarKeyFile = null;
    if (useCustomKeyStore || useCustomTrustStore) {
        jVarRes = jTryBlock.body().decl(classes.RESOURCES, "res", invoke("getResources"));
    }
    if (useCustomKeyStore) {
        JInvocation jInvRawKey = jVarRes.invoke("openRawResource").arg(keyStoreRawIdRef);
        jVarKeyFile = jTryBlock.body().decl(classes.INPUT_STREAM, "inKeystore", jInvRawKey);
    }
    if (useCustomTrustStore) {
        JInvocation jInvRawTrust = jVarRes.invoke("openRawResource").arg(trustStoreRawIdRef);
        jVarTrstFile = jTryBlock.body().decl(classes.INPUT_STREAM, "inTrustStore", jInvRawTrust);
    } else if (useCustomKeyStore) {
        jVarTrstFile = jTryBlock.body().decl(classes.INPUT_STREAM, "inTrustStore", _new(classes.FILE_INPUT_STREAM).arg("/system/etc/security/cacerts.bks"));
    }
    // try load
    if (useCustomKeyStore || useCustomTrustStore) {
        JTryBlock jTryLoad = jTryBlock.body()._try();
        if (useCustomKeyStore) {
            jTryLoad.body().add(invoke(jVarKeystore, "load").arg(jVarKeyFile).arg(invoke(lit(keyStorePwd), "toCharArray")));
        }
        jTryLoad.body().add(invoke(jVarTrusted, "load").arg(jVarTrstFile).arg(invoke(lit(trustStorePwd), "toCharArray")));
        // finally load
        JBlock jFinally = jTryLoad._finally();
        if (useCustomKeyStore) {
            jFinally.add(invoke(jVarKeyFile, "close"));
        }
        jFinally.add(invoke(jVarTrstFile, "close"));
    }
    if (null == jVarKeystore && null == jVarTrusted) {
        JVar jVarCcm = jTryBlock.body().decl(classes.CLIENT_CONNECTION_MANAGER, "ccm");
        jVarCcm.init(_super().invoke("createClientConnectionManager"));
        if (allowAllHostnames) {
            IJExpression jCast = cast(classes.SSL_SOCKET_FACTORY, jVarCcm.invoke("getSchemeRegistry").invoke("getScheme").arg("https").invoke("getSocketFactory"));
            jTryBlock.body().add(jCast.invoke("setHostnameVerifier").arg(classes.SSL_SOCKET_FACTORY.staticRef("ALLOW_ALL_HOSTNAME_VERIFIER")));
        }
        jTryBlock.body()._return(jVarCcm);
    } else {
        JVar jVarSslFact = jTryBlock.body().decl(classes.SSL_SOCKET_FACTORY, "newSslSocketFactory");
        jVarSslFact.init(_new(classes.SSL_SOCKET_FACTORY).arg(null == jVarKeystore ? _null() : jVarKeystore).arg(keyStorePwd).arg(jVarTrusted));
        if (allowAllHostnames) {
            jTryBlock.body().add(invoke(jVarSslFact, "setHostnameVerifier").arg(classes.SSL_SOCKET_FACTORY.staticRef("ALLOW_ALL_HOSTNAME_VERIFIER")));
        }
        JVar jVarSchemeReg = jTryBlock.body().decl(classes.SCHEME_REGISTRY, "registry");
        jVarSchemeReg.init(_new(classes.SCHEME_REGISTRY));
        jTryBlock.body().add(invoke(jVarSchemeReg, "register").arg(_new(classes.SCHEME).arg("https").arg(jVarSslFact).arg(lit(443))));
        jTryBlock.body().add(invoke(jVarSchemeReg, "register").arg(_new(classes.SCHEME).arg("http").arg(classes.PLAIN_SOCKET_FACTORY.staticInvoke("getSocketFactory")).arg(lit(80))));
        JVar jVarCcm = jTryBlock.body().decl(classes.CLIENT_CONNECTION_MANAGER, "ccm");
        jVarCcm.init(_new(classes.SINGLE_CLIENT_CONN_MANAGER).arg(invoke("getParams")).arg(jVarSchemeReg));
        jTryBlock.body()._return(jVarCcm);
    }
    // catch block
    JCatchBlock jCatchBlock = jTryBlock._catch(classes.EXCEPTION);
    JVar jVarExceptionParam = jCatchBlock.param("e");
    jCatchBlock.body().add(jVarExceptionParam.invoke("printStackTrace"));
    jCatchBlock.body()._return(_super().invoke("createClientConnectionManager"));
    targetBlock.add(fieldRef.assign(_new(jAnonClass)));
}
Also used : JFieldRef(com.helger.jcodemodel.JFieldRef) JDefinedClass(com.helger.jcodemodel.JDefinedClass) ProcessHolder(org.androidannotations.internal.process.ProcessHolder) IJExpression(com.helger.jcodemodel.IJExpression) JInvocation(com.helger.jcodemodel.JInvocation) IRInnerClass(org.androidannotations.rclass.IRInnerClass) HttpsClient(org.androidannotations.annotations.HttpsClient) JBlock(com.helger.jcodemodel.JBlock) JMethod(com.helger.jcodemodel.JMethod) JTryBlock(com.helger.jcodemodel.JTryBlock) JCatchBlock(com.helger.jcodemodel.JCatchBlock) JVar(com.helger.jcodemodel.JVar)

Aggregations

JCatchBlock (com.helger.jcodemodel.JCatchBlock)5 JTryBlock (com.helger.jcodemodel.JTryBlock)5 JVar (com.helger.jcodemodel.JVar)5 JBlock (com.helger.jcodemodel.JBlock)4 AbstractJClass (com.helger.jcodemodel.AbstractJClass)3 IJExpression (com.helger.jcodemodel.IJExpression)3 JInvocation (com.helger.jcodemodel.JInvocation)3 JMethod (com.helger.jcodemodel.JMethod)3 JDefinedClass (com.helger.jcodemodel.JDefinedClass)2 ExecutableElement (javax.lang.model.element.ExecutableElement)2 IJStatement (com.helger.jcodemodel.IJStatement)1 JConditional (com.helger.jcodemodel.JConditional)1 JFieldRef (com.helger.jcodemodel.JFieldRef)1 JFieldVar (com.helger.jcodemodel.JFieldVar)1 TypeMirror (javax.lang.model.type.TypeMirror)1 Background (org.androidannotations.annotations.Background)1 HttpsClient (org.androidannotations.annotations.HttpsClient)1 BackgroundExecutor (org.androidannotations.api.BackgroundExecutor)1 ProcessHolder (org.androidannotations.internal.process.ProcessHolder)1 OrmLiteHolder (org.androidannotations.ormlite.holder.OrmLiteHolder)1