Search in sources :

Example 66 with JFieldVar

use of com.sun.codemodel.JFieldVar 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 67 with JFieldVar

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

the class JavaDataTemplateGenerator method generateWithFieldBodyNested.

private void generateWithFieldBodyNested(RecordTemplateSpec.Field field, JDefinedClass maskNestedClass, Consumer<JMethod> methodBodyCustomizer) {
    // For fields with nested types, add a method that allows setting nested mask.
    if (hasNestedFields(field.getSchemaField().getType())) {
        final JClass fieldType = generate(field.getType());
        JClass nestedMaskType = getCodeModel().ref(fieldType.fullName() + "." + PROJECTION_MASK_CLASSNAME);
        String fieldName = escapeReserved(field.getSchemaField().getName());
        String maskFieldName = "_" + fieldName + "Mask";
        JInvocation getDataMap = JExpr.invoke("getDataMap");
        // Generate a fully typesafe method if the nested type has the new ProjectionMask API.
        if (hasProjectionMaskApi(fieldType, field.getType())) {
            JFieldVar maskField = maskNestedClass.fields().get(maskFieldName);
            if (maskField == null) {
                maskField = maskNestedClass.field(JMod.PRIVATE, nestedMaskType, maskFieldName);
            }
            final JMethod withFieldTypesafeMethod = maskNestedClass.method(JMod.PUBLIC, maskNestedClass, "with" + CodeUtil.capitalize(escapeReserved(fieldName)));
            if (!field.getSchemaField().getDoc().isEmpty()) {
                withFieldTypesafeMethod.javadoc().append(field.getSchemaField().getDoc());
            }
            setDeprecatedAnnotationAndJavadoc(withFieldTypesafeMethod, field.getSchemaField());
            JVar nestedMask = withFieldTypesafeMethod.param(getCodeModel().ref(Function.class).narrow(nestedMaskType, nestedMaskType), "nestedMask");
            withFieldTypesafeMethod.body().assign(maskField, nestedMask.invoke("apply").arg(JOp.cond(maskField.eq(JExpr._null()), fieldType.staticInvoke("createMask"), maskField)));
            withFieldTypesafeMethod.body().invoke(getDataMap, "put").arg(fieldName).arg(maskField.invoke("getDataMap"));
            methodBodyCustomizer.accept(withFieldTypesafeMethod);
            withFieldTypesafeMethod.body()._return(JExpr._this());
        }
        // Generate a method that accepts generic mask map if needed
        if (shouldGenerateGenericMaskApi(field.getType())) {
            final JMethod withFieldMethod = maskNestedClass.method(JMod.PUBLIC, maskNestedClass, "with" + CodeUtil.capitalize(escapeReserved(fieldName)));
            if (!field.getSchemaField().getDoc().isEmpty()) {
                withFieldMethod.javadoc().append(field.getSchemaField().getDoc());
            }
            setDeprecatedAnnotationAndJavadoc(withFieldMethod, field.getSchemaField());
            JVar maskMap = withFieldMethod.param(_maskMapClass, "nestedMask");
            withFieldMethod.body().invoke(getDataMap, "put").arg(fieldName).arg(maskMap.invoke("getDataMap"));
            methodBodyCustomizer.accept(withFieldMethod);
            withFieldMethod.body()._return(JExpr._this());
        }
    }
}
Also used : JFieldVar(com.sun.codemodel.JFieldVar) JClass(com.sun.codemodel.JClass) JInvocation(com.sun.codemodel.JInvocation) ByteString(com.linkedin.data.ByteString) JMethod(com.sun.codemodel.JMethod) JVar(com.sun.codemodel.JVar)

Example 68 with JFieldVar

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

the class JavaDataTemplateGenerator method generateUnion.

protected void generateUnion(JDefinedClass unionClass, UnionTemplateSpec unionSpec) throws JClassAlreadyExistsException {
    extendUnionBaseClass(unionClass);
    final JVar schemaField = generateSchemaField(unionClass, unionSpec.getSchema(), unionSpec.getSourceFileFormat());
    // Generate instance vars for members.
    Map<String, JVar> memberVarMap = new HashMap<>();
    for (UnionTemplateSpec.Member member : unionSpec.getMembers()) {
        if (member.getClassTemplateSpec() != null) {
            final String memberName = CodeUtil.uncapitalize(CodeUtil.getUnionMemberName(member));
            final JVar memberVar = unionClass.field(JMod.PRIVATE, generate(member.getClassTemplateSpec()), "_" + memberName + "Member", JExpr._null());
            memberVarMap.put(member.getUnionMemberKey(), memberVar);
        }
    }
    final JClass changeListenerClass;
    final JVar changeListenerVar;
    // Generate change listener if there are any members.
    if (!memberVarMap.isEmpty()) {
        changeListenerClass = generateChangeListener(unionClass, memberVarMap);
        changeListenerVar = unionClass.field(JMod.PRIVATE, changeListenerClass, "__changeListener", JExpr._new(changeListenerClass).arg(JExpr._this()));
    } else {
        changeListenerClass = null;
        changeListenerVar = null;
    }
    // Default union datamap size to 1 (last arg) as union can have at-most one element.
    // We don't need cache for unions, so pass in -1 for cache size to ignore size param.
    generateDataMapConstructor(unionClass, schemaField, 1, -1, changeListenerVar);
    generateConstructorWithObjectArg(unionClass, schemaField, changeListenerVar);
    for (UnionTemplateSpec.Member member : unionSpec.getMembers()) {
        if (member.getClassTemplateSpec() != null) {
            generateUnionMemberAccessors(unionClass, member, generate(member.getClassTemplateSpec()), generate(member.getDataClass()), schemaField, memberVarMap.get(member.getUnionMemberKey()));
        }
    }
    unionSpec.getMembers().stream().map(UnionTemplateSpec.Member::getCustomInfo).distinct().forEach(customInfo -> generateCustomClassInitialization(unionClass, customInfo));
    if (_pathSpecMethods) {
        generatePathSpecMethodsForUnion(unionSpec, unionClass);
    }
    if (_fieldMaskMethods) {
        generateMaskBuilderForUnion(unionSpec, unionClass);
    }
    if (_copierMethods) {
        generateCopierMethods(unionClass, memberVarMap, changeListenerClass);
    }
    if (unionSpec.getTyperefClass() != null) {
        final TyperefTemplateSpec typerefClassSpec = unionSpec.getTyperefClass();
        final JDefinedClass typerefInfoClass = unionClass._class(getJModValue(typerefClassSpec.getModifiers()), escapeReserved(typerefClassSpec.getClassName()));
        generateTyperef(typerefInfoClass, typerefClassSpec);
        final JFieldVar typerefInfoField = unionClass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, TyperefInfo.class, DataTemplateUtil.TYPEREFINFO_FIELD_NAME);
        typerefInfoField.init(JExpr._new(typerefInfoClass));
        unionClass._implements(HasTyperefInfo.class);
        final JMethod typerefInfoMethod = unionClass.method(JMod.PUBLIC, TyperefInfo.class, "typerefInfo");
        typerefInfoMethod.body()._return(typerefInfoField);
    }
}
Also used : HashMap(java.util.HashMap) JDefinedClass(com.sun.codemodel.JDefinedClass) JFieldVar(com.sun.codemodel.JFieldVar) JClass(com.sun.codemodel.JClass) ByteString(com.linkedin.data.ByteString) UnionTemplateSpec(com.linkedin.pegasus.generator.spec.UnionTemplateSpec) TyperefTemplateSpec(com.linkedin.pegasus.generator.spec.TyperefTemplateSpec) JMethod(com.sun.codemodel.JMethod) JVar(com.sun.codemodel.JVar)

Example 69 with JFieldVar

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

the class JavaDataTemplateGenerator method generateMaskBuilderForCollection.

private void generateMaskBuilderForCollection(JDefinedClass templateClass, DataSchema schema, JClass childClass, String wildcardMethodName, ClassTemplateSpec itemSpec) throws JClassAlreadyExistsException {
    // }
    if (hasNestedFields(schema)) {
        // Arrays can custom attributes like start and count. The expected size of the map is attribute size + 1 (for items).
        final JDefinedClass maskNestedClass = generateProjectionMaskNestedClass(templateClass, FilterConstants.ARRAY_ATTRIBUTES.size() + 1);
        JInvocation getDataMap = JExpr.invoke("getDataMap");
        // Generate fully typesafe API for specifying item/value mask if the nested type has ProjectionMask class.
        if (hasProjectionMaskApi(childClass, itemSpec)) {
            final JMethod withFieldTypesafeMethod = maskNestedClass.method(JMod.PUBLIC, maskNestedClass, "with" + CodeUtil.capitalize(wildcardMethodName));
            JClass nestedMaskType = getCodeModel().ref(childClass.fullName() + "." + PROJECTION_MASK_CLASSNAME);
            JFieldVar maskField = maskNestedClass.field(JMod.PRIVATE, nestedMaskType, "_" + wildcardMethodName + "Mask");
            JVar nestedMask = withFieldTypesafeMethod.param(getCodeModel().ref(Function.class).narrow(nestedMaskType, nestedMaskType), "nestedMask");
            withFieldTypesafeMethod.body().assign(maskField, nestedMask.invoke("apply").arg(JOp.cond(maskField.eq(JExpr._null()), childClass.staticInvoke("createMask"), maskField)));
            withFieldTypesafeMethod.body().invoke(getDataMap, "put").arg(JExpr.lit(FilterConstants.WILDCARD)).arg(maskField.invoke("getDataMap"));
            withFieldTypesafeMethod.body()._return(JExpr._this());
        }
        // Generate mask api using generic MaskMap if the item/value type is from external source.
        if (shouldGenerateGenericMaskApi(itemSpec)) {
            final JMethod withFieldMethod = maskNestedClass.method(JMod.PUBLIC, maskNestedClass, "with" + CodeUtil.capitalize(wildcardMethodName));
            JVar maskMap = withFieldMethod.param(_maskMapClass, "nestedMask");
            withFieldMethod.body().invoke(getDataMap, "put").arg(JExpr.lit(FilterConstants.WILDCARD)).arg(maskMap.invoke("getDataMap"));
            withFieldMethod.body()._return(JExpr._this());
        }
    }
}
Also used : JDefinedClass(com.sun.codemodel.JDefinedClass) JFieldVar(com.sun.codemodel.JFieldVar) JClass(com.sun.codemodel.JClass) JInvocation(com.sun.codemodel.JInvocation) JMethod(com.sun.codemodel.JMethod) JVar(com.sun.codemodel.JVar)

Example 70 with JFieldVar

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

the class JavaDataTemplateGenerator method generateMaskBuilderForUnion.

private void generateMaskBuilderForUnion(UnionTemplateSpec unionSpec, JDefinedClass unionClass) throws JClassAlreadyExistsException {
    final JDefinedClass maskNestedClass = generateProjectionMaskNestedClass(unionClass, unionSpec.getMembers().size());
    // Generates a method in the ProjectionMask class for each member. APIs generated are similar to fields in a record.
    for (UnionTemplateSpec.Member member : unionSpec.getMembers()) {
        String memberKey = member.getUnionMemberKey();
        String methodName = CodeUtil.getUnionMemberName(member);
        JInvocation getDataMap = JExpr.invoke("getDataMap");
        if (hasNestedFields(member.getSchema())) {
            final JClass memberType = generate(member.getClassTemplateSpec());
            // }
            if (shouldGenerateGenericMaskApi(member.getClassTemplateSpec())) {
                final JMethod withMemberMethod = maskNestedClass.method(JMod.PUBLIC, maskNestedClass, "with" + CodeUtil.capitalize(escapeReserved(methodName)));
                JVar maskMap = withMemberMethod.param(_maskMapClass, "nestedMask");
                withMemberMethod.body().invoke(getDataMap, "put").arg(memberKey).arg(maskMap.invoke("getDataMap"));
                withMemberMethod.body()._return(JExpr._this());
            }
            // }
            if (hasProjectionMaskApi(memberType, member.getClassTemplateSpec())) {
                JClass nestedMaskType = getCodeModel().ref(memberType.fullName() + "." + PROJECTION_MASK_CLASSNAME);
                final JMethod withMemberTypesafeMethod = maskNestedClass.method(JMod.PUBLIC, maskNestedClass, "with" + CodeUtil.capitalize(escapeReserved(methodName)));
                String maskFieldName = "_" + CodeUtil.capitalize(escapeReserved(methodName)) + "Mask";
                JFieldVar maskField = maskNestedClass.field(JMod.PRIVATE, nestedMaskType, maskFieldName);
                JVar nestedMask = withMemberTypesafeMethod.param(getCodeModel().ref(Function.class).narrow(nestedMaskType, nestedMaskType), "nestedMask");
                withMemberTypesafeMethod.body().assign(maskField, nestedMask.invoke("apply").arg(JOp.cond(maskField.eq(JExpr._null()), memberType.staticInvoke("createMask"), maskField)));
                withMemberTypesafeMethod.body().invoke(getDataMap, "put").arg(memberKey).arg(maskField.invoke("getDataMap"));
                withMemberTypesafeMethod.body()._return(JExpr._this());
            }
        } else {
            // Generate a mask API to project the member.
            // public ProjectionMask withFoo() {
            // getDataMap().put("foo", MaskMap.POSITIVE_MASK);
            // }
            final JMethod withMemberMethod = maskNestedClass.method(JMod.PUBLIC, maskNestedClass, "with" + CodeUtil.capitalize(escapeReserved(methodName)));
            withMemberMethod.body().invoke(getDataMap, "put").arg(memberKey).arg(getCodeModel().ref(MaskMap.class).staticRef("POSITIVE_MASK"));
            withMemberMethod.body()._return(JExpr._this());
        }
    }
}
Also used : JDefinedClass(com.sun.codemodel.JDefinedClass) JFieldVar(com.sun.codemodel.JFieldVar) JClass(com.sun.codemodel.JClass) JInvocation(com.sun.codemodel.JInvocation) ByteString(com.linkedin.data.ByteString) UnionTemplateSpec(com.linkedin.pegasus.generator.spec.UnionTemplateSpec) JMethod(com.sun.codemodel.JMethod) JVar(com.sun.codemodel.JVar)

Aggregations

JFieldVar (com.sun.codemodel.JFieldVar)74 JMethod (com.sun.codemodel.JMethod)33 JVar (com.sun.codemodel.JVar)28 JClass (com.sun.codemodel.JClass)24 Test (org.junit.Test)24 JBlock (com.sun.codemodel.JBlock)21 JInvocation (com.sun.codemodel.JInvocation)19 JDefinedClass (com.sun.codemodel.JDefinedClass)16 Random (java.util.Random)12 ByteString (com.linkedin.data.ByteString)10 HashMap (java.util.HashMap)10 JsonNode (com.fasterxml.jackson.databind.JsonNode)9 JExpression (com.sun.codemodel.JExpression)9 JConditional (com.sun.codemodel.JConditional)8 JType (com.sun.codemodel.JType)8 ArrayList (java.util.ArrayList)7 Map (java.util.Map)6 JFieldRef (com.sun.codemodel.JFieldRef)5 JCodeModel (com.sun.codemodel.JCodeModel)3 JPackage (com.sun.codemodel.JPackage)3