Search in sources :

Example 86 with JCodeModel

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

the class JaxWsAnnotationProcessor method generateEntryPoint.

/**
 * Generates the entry point and associated artifacts for the given definition.
 */
protected void generateEntryPoint(final EntryPointDefinition entryPointDefinition, final RoundEnvironment roundEnv) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
    final JCodeModel model = new JCodeModel();
    // Create EntryPoint class.
    final TypeElement _endpointInterface = entryPointDefinition.getEndpointInterface();
    final JClass endpointInterface = model.ref(_endpointInterface.getQualifiedName().toString());
    final JDefinedClass entryPoint = model._class(entryPointDefinition.getEntryPointQualifiedName())._implements(endpointInterface);
    // Add annotations to the EntryPoint.
    addAnnotations(model, entryPoint, entryPointDefinition, roundEnv);
    // Create handler chain.
    final HandlerChain _handlerChainAnnotation = _endpointInterface.getAnnotation(HandlerChain.class);
    if (_handlerChainAnnotation != null) {
        m_logger.info("Handler file not generated because provided as binding file [file={}, entryPoint={}, endpointInterface={}]", _handlerChainAnnotation.file(), entryPointDefinition.getEntryPointQualifiedName(), entryPointDefinition.getEndpointInterfaceQualifiedName());
    } else if (!entryPointDefinition.getHandlerChain().isEmpty() || entryPointDefinition.isAuthenticationEnabled()) {
        entryPoint.annotate(HandlerChain.class).param("file", new HandlerArtifactProcessor().generateHandlerArtifacts(entryPoint, entryPointDefinition, processingEnv, m_logger));
    }
    // Add JavaDoc to the EntryPoint.
    AptUtil.addJavaDoc(entryPoint, createJavaDocForEntryPoint(entryPointDefinition));
    // Inject WebServiceContext
    final JFieldVar webServiceContext = entryPoint.field(JMod.PROTECTED, WebServiceContext.class, WEBSERVICE_CONTEXT_FIELD_NAME);
    webServiceContext.annotate(Resource.class);
    // Overwrite all methods declared on the PortType interface.
    for (final Element _element : _endpointInterface.getEnclosedElements()) {
        if (!(ElementKind.METHOD.equals(_element.getKind()))) {
            continue;
        }
        final ExecutableElement _method = (ExecutableElement) _element;
        final String methodName = _method.getSimpleName().toString();
        final JType returnType = JTypeParser.parseType(model, _method.getReturnType());
        // Create the method.
        final JMethod method = entryPoint.method(JMod.PUBLIC, returnType, methodName);
        method.annotate(Override.class);
        // Add the method parameters.
        for (final VariableElement _param : _method.getParameters()) {
            method.param(JMod.FINAL, JTypeParser.parseType(model, _param.asType()), _param.getSimpleName().toString());
        }
        // Add exception throw clauses.
        final List<JClass> throwTypes = new ArrayList<>();
        for (final TypeMirror _throwType : _method.getThrownTypes()) {
            final JClass throwType = model.ref(_throwType.toString());
            throwTypes.add(throwType);
            method._throws(throwType);
        }
        // Create the method implementation.
        addEntryPointMethodImplementation(model, webServiceContext, method, throwTypes, TypeKind.VOID.equals(_method.getReturnType().getKind()), _endpointInterface.getQualifiedName().toString());
    }
    // Create the method to handle undeclared errors.
    addHandleUndeclaredFaultMethod(model, entryPoint);
    // Create the method to lookup the RunContext.
    addLookupRunContextMethod(model, entryPoint, webServiceContext);
    // Build and persist this compilation unit.
    AptUtil.buildAndPersist(model, processingEnv.getFiler());
    m_logger.info("Entry point successfully generated. [entryPoint={}, endpointInterface={}, entryPointDefinition={}]", entryPoint.fullName(), endpointInterface.fullName(), entryPointDefinition.getQualifiedName());
}
Also used : JDefinedClass(com.sun.codemodel.JDefinedClass) TypeElement(javax.lang.model.element.TypeElement) JClass(com.sun.codemodel.JClass) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) VariableElement(javax.lang.model.element.VariableElement) JCodeModel(com.sun.codemodel.JCodeModel) HandlerChain(javax.jws.HandlerChain) JFieldVar(com.sun.codemodel.JFieldVar) TypeMirror(javax.lang.model.type.TypeMirror) HandlerArtifactProcessor(org.eclipse.scout.jaxws.apt.internal.HandlerArtifactProcessor) JMethod(com.sun.codemodel.JMethod) JType(com.sun.codemodel.JType)

Example 87 with JCodeModel

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

the class HandlerArtifactProcessor method createAndPersistHandlerDelegate.

/**
 * Generates the entry point for a handler.
 */
public String createAndPersistHandlerDelegate(final JClass portTypeEntryPoint, final EntryPointDefinition entryPointDefinition, final HandlerDefinition handler, final int idx, final ProcessingEnvironment env) throws IOException, JClassAlreadyExistsException {
    final JCodeModel model = new JCodeModel();
    final String fullName = entryPointDefinition.getEntryPointQualifiedName() + "_" + handler.getHandlerSimpleName() + HANDLER_SUFFIX;
    final JDefinedClass handlerDelegate = model._class(fullName);
    // Add 'Generated' annotation
    final JAnnotationUse generatedAnnotation = handlerDelegate.annotate(Generated.class);
    generatedAnnotation.param("value", JaxWsAnnotationProcessor.class.getName());
    generatedAnnotation.param("date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSZ").format(new Date()));
    generatedAnnotation.param("comments", "Handler delegate for " + handler.getHandlerQualifiedName());
    AptUtil.addJavaDoc(handlerDelegate, format("This class is auto-generated by APT triggered by Maven build and is based on the handler configuration declared in {@link %s}.", entryPointDefinition.getSimpleName()));
    switch(handler.getHandlerType()) {
        case SOAP:
            handlerDelegate._extends(model.ref(SOAPHandlerDelegate.class));
            break;
        case LOGICAL:
            handlerDelegate._extends(model.ref(HandlerDelegate.class).narrow(LogicalMessageContext.class));
            handlerDelegate._implements(model.ref(LogicalHandler.class).narrow(LogicalMessageContext.class));
            break;
        default:
            handlerDelegate._extends(model.ref(HandlerDelegate.class).narrow(MessageContext.class));
            break;
    }
    // Add default constructor with super call to provide handler annotation.
    final JClass entryPointDefinitionClass = model.ref(entryPointDefinition.getQualifiedName());
    final JMethod defaultConstructor = handlerDelegate.constructor(JMod.PUBLIC);
    defaultConstructor.body().invoke("super").arg(JExpr.dotclass(entryPointDefinitionClass).invoke("getAnnotation").arg(JExpr.dotclass(model.ref(WebServiceEntryPoint.class))).invoke("handlerChain").component(JExpr.lit(idx)));
    AptUtil.buildAndPersist(model, env.getFiler());
    return handlerDelegate.fullName();
}
Also used : JaxWsAnnotationProcessor(org.eclipse.scout.jaxws.apt.JaxWsAnnotationProcessor) LogicalMessageContext(javax.xml.ws.handler.LogicalMessageContext) JDefinedClass(com.sun.codemodel.JDefinedClass) JClass(com.sun.codemodel.JClass) SOAPHandlerDelegate(org.eclipse.scout.rt.server.jaxws.provider.handler.SOAPHandlerDelegate) JCodeModel(com.sun.codemodel.JCodeModel) Date(java.util.Date) JAnnotationUse(com.sun.codemodel.JAnnotationUse) LogicalMessageContext(javax.xml.ws.handler.LogicalMessageContext) MessageContext(javax.xml.ws.handler.MessageContext) JMethod(com.sun.codemodel.JMethod) WebServiceEntryPoint(org.eclipse.scout.rt.server.jaxws.provider.annotation.WebServiceEntryPoint) SimpleDateFormat(java.text.SimpleDateFormat)

Example 88 with JCodeModel

use of com.sun.codemodel.JCodeModel in project rest.li by linkedin.

the class RestRequestBuilderGenerator method run.

/**
 * @param generateLowercasePath true, files are generated with a lower case path; false, files are generated as spec specifies.
 */
public static GeneratorResult run(String resolverPath, String defaultPackage, String rootPath, final boolean generateImported, final boolean generateDataTemplates, RestliVersion version, RestliVersion deprecatedByVersion, String targetDirectoryPath, String[] sources, boolean generateLowercasePath) throws IOException {
    final RestSpecParser parser = new RestSpecParser();
    final JavaRequestBuilderGenerator generator = new JavaRequestBuilderGenerator(resolverPath, defaultPackage, generateDataTemplates, version, deprecatedByVersion, rootPath);
    final ClassLoader classLoader = JavaCodeUtil.classLoaderFromResolverPath(resolverPath);
    final RestSpecParser.ParseResult parseResult = parser.parseSources(sources);
    final StringBuilder message = new StringBuilder();
    for (CodeUtil.Pair<ResourceSchema, File> pair : parseResult.getSchemaAndFiles()) {
        ResourceSchema resourceSchema = pair.first;
        // Skip unstructured data resources for client generation
        if (resourceSchema == null || ResourceEntityType.UNSTRUCTURED_DATA == resourceSchema.getEntityType()) {
            continue;
        }
        try {
            final JDefinedClass clazz = generator.generate(resourceSchema, pair.second, rootPath);
        } catch (Exception e) {
            _log.error("Failed to generate request builders for schema: " + resourceSchema.getName(), e);
            message.append(e.getMessage()).append("\n");
        }
    }
    if (message.length() > 0) {
        throw new IOException(message.toString());
    }
    final DataTemplatePersistentClassChecker dataTemplateChecker = new DataTemplatePersistentClassChecker(generateImported, generator.getSpecGenerator(), generator.getJavaDataTemplateGenerator(), Collections.<File>emptySet());
    final JavaCodeUtil.PersistentClassChecker checker = new JavaCodeUtil.PersistentClassChecker() {

        @Override
        public boolean isPersistent(JDefinedClass clazz) {
            if (generateDataTemplates || generator.isGeneratedArrayClass(clazz)) {
                try {
                    Class.forName(clazz.fullName(), false, classLoader);
                } catch (ClassNotFoundException e) {
                    return true;
                }
            }
            return dataTemplateChecker.isPersistent(clazz);
        }
    };
    final JCodeModel requestBuilderCodeModel = generator.getCodeModel();
    final JCodeModel dataTemplateCodeModel = generator.getJavaDataTemplateGenerator().getCodeModel();
    final File targetDirectory = new File(targetDirectoryPath);
    final List<File> targetFiles = JavaCodeUtil.targetFiles(targetDirectory, requestBuilderCodeModel, classLoader, checker, generateLowercasePath);
    targetFiles.addAll(JavaCodeUtil.targetFiles(targetDirectory, dataTemplateCodeModel, classLoader, checker, generateLowercasePath));
    final List<File> modifiedFiles;
    if (FileUtil.upToDate(parseResult.getSourceFiles(), targetFiles)) {
        modifiedFiles = Collections.emptyList();
        _log.info("Target files are up-to-date: " + targetFiles);
    } else {
        modifiedFiles = targetFiles;
        _log.info("Generating " + targetFiles.size() + " files");
        _log.debug("Files: " + targetFiles);
        requestBuilderCodeModel.build(new CaseSensitiveFileCodeWriter(targetDirectory, true, generateLowercasePath));
        dataTemplateCodeModel.build(new CaseSensitiveFileCodeWriter(targetDirectory, true, generateLowercasePath));
    }
    return new DefaultGeneratorResult(parseResult.getSourceFiles(), targetFiles, modifiedFiles);
}
Also used : ResourceSchema(com.linkedin.restli.restspec.ResourceSchema) CaseSensitiveFileCodeWriter(com.linkedin.pegasus.generator.CaseSensitiveFileCodeWriter) JDefinedClass(com.sun.codemodel.JDefinedClass) IOException(java.io.IOException) JCodeModel(com.sun.codemodel.JCodeModel) IOException(java.io.IOException) DataTemplatePersistentClassChecker(com.linkedin.pegasus.generator.DataTemplatePersistentClassChecker) JavaCodeUtil(com.linkedin.pegasus.generator.JavaCodeUtil) CodeUtil(com.linkedin.pegasus.generator.CodeUtil) DefaultGeneratorResult(com.linkedin.pegasus.generator.DefaultGeneratorResult) DataTemplatePersistentClassChecker(com.linkedin.pegasus.generator.DataTemplatePersistentClassChecker) JavaCodeUtil(com.linkedin.pegasus.generator.JavaCodeUtil) File(java.io.File)

Example 89 with JCodeModel

use of com.sun.codemodel.JCodeModel 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

JCodeModel (com.sun.codemodel.JCodeModel)89 Test (org.junit.Test)70 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)58 JPackage (com.sun.codemodel.JPackage)50 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)45 JType (com.sun.codemodel.JType)43 JDefinedClass (com.sun.codemodel.JDefinedClass)18 JClass (com.sun.codemodel.JClass)14 RuleFactory (org.jsonschema2pojo.rules.RuleFactory)14 Schema (org.jsonschema2pojo.Schema)13 JsonNode (com.fasterxml.jackson.databind.JsonNode)9 TextNode (com.fasterxml.jackson.databind.node.TextNode)7 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)5 File (java.io.File)5 IOException (java.io.IOException)5 URL (java.net.URL)5 JBlock (com.sun.codemodel.JBlock)4 JCatchBlock (com.sun.codemodel.JCatchBlock)4 JDocComment (com.sun.codemodel.JDocComment)4 JMethod (com.sun.codemodel.JMethod)4