Search in sources :

Example 6 with JCatchBlock

use of com.sun.codemodel.JCatchBlock in project scout.rt by eclipse-scout.

the class JaxWsAnnotationProcessor method addEntryPointMethodImplementation.

/**
 * Creates the implementation of a entry point method.
 */
protected void addEntryPointMethodImplementation(final JCodeModelWrapper model, final JFieldVar webServiceContext, final JMethod method, final List<JClass> throwTypes, final boolean voidMethod, final String endpointInterfaceName) {
    final JBlock methodBody = method.body();
    final JInvocation runContext = JExpr.invoke(LOOKUP_RUN_CONTEXT_METHOD_NAME);
    final JTryBlock tryBlock = methodBody._try();
    // Invoke port type on behalf of RunContext.
    final JInvocation runContextInvocation = createRunContextInvocation(model, runContext, voidMethod, method, endpointInterfaceName);
    if (voidMethod) {
        tryBlock.body().add(runContextInvocation);
    } else {
        tryBlock.body()._return(runContextInvocation);
    }
    // Create exception handling.
    final JCatchBlock catchBlock = tryBlock._catch(model.ref(Exception.class));
    final JVar caughtException = catchBlock.param("e");
    final JBlock catchBody = catchBlock.body();
    if (throwTypes.isEmpty()) {
        // webservice method has no faults declared.
        catchBody._throw(JExpr.invoke(HANDLE_UNDECLARED_FAULT_METHOD_NAME).arg(caughtException));
    } else {
        // handle declared webservice faults.
        final JConditionalEx condition = new JConditionalEx(catchBody);
        for (final JClass throwType : throwTypes) {
            condition._elseif(caughtException._instanceof(throwType))._throw(JExprEx.cast(throwType, caughtException));
        }
        condition._else()._throw(JExpr.invoke(HANDLE_UNDECLARED_FAULT_METHOD_NAME).arg(caughtException));
    }
}
Also used : JClass(com.sun.codemodel.JClass) JBlock(com.sun.codemodel.JBlock) JInvocation(com.sun.codemodel.JInvocation) JTryBlock(com.sun.codemodel.JTryBlock) JCatchBlock(com.sun.codemodel.JCatchBlock) JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) IOException(java.io.IOException) JVar(com.sun.codemodel.JVar) JConditionalEx(org.eclipse.scout.jaxws.apt.internal.codemodel.JConditionalEx)

Example 7 with JCatchBlock

use of com.sun.codemodel.JCatchBlock in project avro-util by linkedin.

the class FastDeserializerGenerator method generateDeserializer.

public FastDeserializer<T> generateDeserializer() {
    String className = getClassName(writer, reader, useGenericTypes ? "Generic" : "Specific");
    JPackage classPackage = codeModel._package(generatedPackageName);
    try {
        generatedClass = classPackage._class(className);
        JVar readerSchemaVar = generatedClass.field(JMod.PRIVATE | JMod.FINAL, Schema.class, "readerSchema");
        constructor = generatedClass.constructor(JMod.PUBLIC);
        JVar constructorParam = constructor.param(Schema.class, "readerSchema");
        constructor.body().assign(JExpr.refthis(readerSchemaVar.name()), constructorParam);
        Schema aliasedWriterSchema = writer;
        /**
         * {@link Schema.applyAliases} is not working correctly in avro-1.4 since there is a bug in this function:
         * {@literal Schema#getFieldAlias}.
         */
        if (!Utils.isAvro14()) {
            aliasedWriterSchema = Schema.applyAliases(writer, reader);
        }
        Symbol resolvingGrammar = new ResolvingGrammarGenerator().generate(aliasedWriterSchema, reader);
        FieldAction fieldAction = FieldAction.fromValues(aliasedWriterSchema.getType(), true, resolvingGrammar);
        if (useGenericTypes) {
            registerSchema(reader, readerSchemaVar);
        }
        JClass readerSchemaClass = schemaAssistant.classFromSchema(reader);
        /**
         * Writer schema could be using a different namespace from the reader schema, so we should always
         * use the reader schema class for generic type.
         */
        generatedClass._implements(codeModel.ref(FastDeserializer.class).narrow(readerSchemaClass));
        JMethod deserializeMethod = generatedClass.method(JMod.PUBLIC, readerSchemaClass, "deserialize");
        JBlock topLevelDeserializeBlock = new JBlock();
        final Supplier<JExpression> reuseSupplier = () -> JExpr.direct(VAR_NAME_FOR_REUSE);
        switch(aliasedWriterSchema.getType()) {
            case RECORD:
                processRecord(readerSchemaVar, aliasedWriterSchema.getName(), aliasedWriterSchema, reader, topLevelDeserializeBlock, fieldAction, JBlock::_return, reuseSupplier);
                break;
            case ARRAY:
                processArray(readerSchemaVar, "array", aliasedWriterSchema, reader, topLevelDeserializeBlock, fieldAction, JBlock::_return, reuseSupplier);
                break;
            case MAP:
                processMap(readerSchemaVar, "map", aliasedWriterSchema, reader, topLevelDeserializeBlock, fieldAction, JBlock::_return, reuseSupplier);
                break;
            default:
                throw new FastDeserializerGeneratorException("Incorrect top-level writer schema: " + aliasedWriterSchema.getType());
        }
        if (schemaAssistant.getExceptionsFromStringable().isEmpty()) {
            assignBlockToBody(deserializeMethod, topLevelDeserializeBlock);
        } else {
            JTryBlock tryBlock = deserializeMethod.body()._try();
            assignBlockToBody(tryBlock, topLevelDeserializeBlock);
            for (Class<? extends Exception> classException : schemaAssistant.getExceptionsFromStringable()) {
                JCatchBlock catchBlock = tryBlock._catch(codeModel.ref(classException));
                JVar exceptionVar = catchBlock.param("e");
                catchBlock.body()._throw(JExpr._new(codeModel.ref(AvroRuntimeException.class)).arg(exceptionVar));
            }
        }
        deserializeMethod._throws(codeModel.ref(IOException.class));
        deserializeMethod.param(readerSchemaClass, VAR_NAME_FOR_REUSE);
        deserializeMethod.param(Decoder.class, DECODER);
        Class<FastDeserializer<T>> clazz = compileClass(className, schemaAssistant.getUsedFullyQualifiedClassNameSet());
        return clazz.getConstructor(Schema.class).newInstance(reader);
    } catch (JClassAlreadyExistsException e) {
        throw new FastDeserializerGeneratorException("Class: " + className + " already exists");
    } catch (Exception e) {
        throw new FastDeserializerGeneratorException(e);
    }
}
Also used : Symbol(com.linkedin.avro.fastserde.backport.Symbol) Schema(org.apache.avro.Schema) JClass(com.sun.codemodel.JClass) JPackage(com.sun.codemodel.JPackage) AvroRuntimeException(org.apache.avro.AvroRuntimeException) JExpression(com.sun.codemodel.JExpression) IOException(java.io.IOException) JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) IOException(java.io.IOException) AvroTypeException(org.apache.avro.AvroTypeException) AvroRuntimeException(org.apache.avro.AvroRuntimeException) JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) ResolvingGrammarGenerator(com.linkedin.avro.fastserde.backport.ResolvingGrammarGenerator) JBlock(com.sun.codemodel.JBlock) JMethod(com.sun.codemodel.JMethod) JTryBlock(com.sun.codemodel.JTryBlock) JCatchBlock(com.sun.codemodel.JCatchBlock) JVar(com.sun.codemodel.JVar)

Example 8 with JCatchBlock

use of com.sun.codemodel.JCatchBlock in project metro-jax-ws by eclipse-ee4j.

the class ServiceGenerator method writeClassLoaderBaseResourceWSDLLocation.

/*
       Generates the code to create URL for WSDL location from classloader base resource

       for e.g.:
       static {
           Exception e = null;
           URL url = null;
           try {
               url = new URL(ExampleService.class.getClassLoader().getResource("."), ...);
           } catch (MalformedURLException murl) {
               e = new WebServiceException(murl);
           }
           EXAMPLESERVICE_WSDL_LOCATION = url;
           EXAMPLESERVICE_EXCEPTION = e;
       }
     */
private void writeClassLoaderBaseResourceWSDLLocation(String className, JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
    JBlock staticBlock = cls.init();
    JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
    JVar urlVar = staticBlock.decl(cm.ref(URL.class), "url", JExpr._null());
    JTryBlock tryBlock = staticBlock._try();
    tryBlock.body().assign(urlVar, JExpr._new(cm.ref(URL.class)).arg(JExpr.dotclass(cm.ref(className)).invoke("getResource").arg(".")).arg(wsdlLocation));
    JCatchBlock catchBlock = tryBlock._catch(cm.ref(MalformedURLException.class));
    JVar murlVar = catchBlock.param("murl");
    catchBlock.body().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(murlVar));
    staticBlock.assign(urlField, urlVar);
    staticBlock.assign(exField, exVar);
}
Also used : MalformedURLException(java.net.MalformedURLException) WebServiceException(jakarta.xml.ws.WebServiceException) JBlock(com.sun.codemodel.JBlock) JTryBlock(com.sun.codemodel.JTryBlock) JCatchBlock(com.sun.codemodel.JCatchBlock) URL(java.net.URL) JVar(com.sun.codemodel.JVar)

Example 9 with JCatchBlock

use of com.sun.codemodel.JCatchBlock in project drill by apache.

the class ClassGenerator method addCtor.

/**
 * The code generator creates a method called __DRILL_INIT__ which takes the
 * place of the constructor when the code goes though the byte code merge.
 * For Plain-old Java, we call the method from a constructor created for
 * that purpose. (Generated code, fortunately, never includes a constructor,
 * so we can create one.) Since the init block throws an exception (which
 * should never occur), the generated constructor converts the checked
 * exception into an unchecked one so as to not require changes to the
 * various places that create instances of the generated classes.
 *
 * Example:<code><pre>
 * public StreamingAggregatorGen1() {
 *       try {
 *         __DRILL_INIT__();
 *     } catch (SchemaChangeException e) {
 *         throw new UnsupportedOperationException(e);
 *     }
 * }</pre></code>
 *
 * Note: in Java 8 we'd use the <tt>Parameter</tt> class defined in Java's
 * introspection package. But, Drill prefers Java 7 which only provides
 * parameter types.
 */
private void addCtor(Class<?>[] parameters) {
    JMethod ctor = clazz.constructor(JMod.PUBLIC);
    JBlock body = ctor.body();
    // If there are parameters, need to pass them to the super class.
    if (parameters.length > 0) {
        JInvocation superCall = JExpr.invoke("super");
        for (int i = 1; i < parameters.length; i++) {
            Class<?> p = parameters[i];
            superCall.arg(ctor.param(model._ref(p), "arg" + i));
        }
        body.add(superCall);
    }
    JTryBlock tryBlock = body._try();
    tryBlock.body().invoke(SignatureHolder.DRILL_INIT_METHOD);
    JCatchBlock catchBlock = tryBlock._catch(model.ref(SchemaChangeException.class));
    catchBlock.body()._throw(JExpr._new(model.ref(UnsupportedOperationException.class)).arg(catchBlock.param("e")));
}
Also used : SchemaChangeException(org.apache.drill.exec.exception.SchemaChangeException) JBlock(com.sun.codemodel.JBlock) JInvocation(com.sun.codemodel.JInvocation) JMethod(com.sun.codemodel.JMethod) JTryBlock(com.sun.codemodel.JTryBlock) JCatchBlock(com.sun.codemodel.JCatchBlock)

Example 10 with JCatchBlock

use of com.sun.codemodel.JCatchBlock in project drill by apache.

the class HiveFuncHolder method generateEval.

private HoldingContainer generateEval(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[] workspaceJVars) {
    HoldingContainer out = g.declare(returnType);
    JCodeModel m = g.getModel();
    JBlock sub = new JBlock(true, true);
    // initialize DeferredObject's. For an optional type, assign the value holder only if it is not null
    for (int i = 0; i < argTypes.length; i++) {
        if (inputVariables[i].isOptional()) {
            sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
            JBlock conditionalBlock = new JBlock(false, false);
            JConditional jc = conditionalBlock._if(inputVariables[i].getIsSet().ne(JExpr.lit(0)));
            jc._then().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
            jc._else().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), JExpr._null());
            sub.add(conditionalBlock);
        } else {
            sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
            sub.assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
        }
    }
    // declare generic object for storing return value from GenericUDF.evaluate
    JVar retVal = sub.decl(m._ref(Object.class), "ret");
    // create try..catch block to call the GenericUDF instance with given input
    JTryBlock udfEvalTry = sub._try();
    udfEvalTry.body().assign(retVal, workspaceJVars[1].invoke("evaluate").arg(workspaceJVars[3]));
    JCatchBlock udfEvalCatch = udfEvalTry._catch(m.directClass(Exception.class.getCanonicalName()));
    JVar exVar = udfEvalCatch.param("ex");
    udfEvalCatch.body()._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName())).arg(JExpr.lit(String.format("GenericUDF.evaluate method failed"))).arg(exVar));
    // get the ValueHolder from retVal and return ObjectInspector
    sub.add(ObjectInspectorHelper.getDrillObject(m, returnOI, workspaceJVars[0], workspaceJVars[4], retVal));
    sub.assign(out.getHolder(), workspaceJVars[4]);
    // now add it to the doEval block in Generated class
    JBlock setup = g.getBlock(ClassGenerator.BlockType.EVAL);
    setup.directStatement(String.format("/** start %s for function %s **/ ", ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
    setup.add(sub);
    setup.directStatement(String.format("/** end %s for function %s **/ ", ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
    return out;
}
Also used : HoldingContainer(org.apache.drill.exec.expr.ClassGenerator.HoldingContainer) JBlock(com.sun.codemodel.JBlock) JConditional(com.sun.codemodel.JConditional) DrillDeferredObject(org.apache.drill.exec.expr.fn.impl.hive.DrillDeferredObject) JTryBlock(com.sun.codemodel.JTryBlock) JCatchBlock(com.sun.codemodel.JCatchBlock) JCodeModel(com.sun.codemodel.JCodeModel) JVar(com.sun.codemodel.JVar)

Aggregations

JBlock (com.sun.codemodel.JBlock)12 JCatchBlock (com.sun.codemodel.JCatchBlock)12 JTryBlock (com.sun.codemodel.JTryBlock)12 JVar (com.sun.codemodel.JVar)10 JClass (com.sun.codemodel.JClass)6 JClassAlreadyExistsException (com.sun.codemodel.JClassAlreadyExistsException)4 JCodeModel (com.sun.codemodel.JCodeModel)4 JInvocation (com.sun.codemodel.JInvocation)4 JMethod (com.sun.codemodel.JMethod)4 IOException (java.io.IOException)4 DrillDeferredObject (org.apache.drill.exec.expr.fn.impl.hive.DrillDeferredObject)4 ResolvingGrammarGenerator (com.linkedin.avro.fastserde.backport.ResolvingGrammarGenerator)2 Symbol (com.linkedin.avro.fastserde.backport.Symbol)2 JConditional (com.sun.codemodel.JConditional)2 JExpression (com.sun.codemodel.JExpression)2 JPackage (com.sun.codemodel.JPackage)2 WebServiceException (jakarta.xml.ws.WebServiceException)2 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 AvroRuntimeException (org.apache.avro.AvroRuntimeException)2