Search in sources :

Example 36 with JDefinedClass

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

the class JavaRequestBuilderGenerator method generateResourceFacade.

private JDefinedClass generateResourceFacade(ResourceSchema resource, File sourceFile, Map<String, JClass> pathKeyTypes, Map<String, JClass> assocKeyTypes, Map<String, List<String>> pathToAssocKeys) throws JClassAlreadyExistsException, IOException {
    final ValidationResult validationResult = ValidateDataAgainstSchema.validate(resource.data(), resource.schema(), new ValidationOptions(RequiredMode.MUST_BE_PRESENT));
    if (!validationResult.isValid()) {
        throw new IllegalArgumentException(String.format("Resource validation error.  Resource File '%s', Error Details '%s'", sourceFile, validationResult.toString()));
    }
    final String packageName = resource.getNamespace();
    final JPackage clientPackage = (packageName == null || packageName.isEmpty()) ? getPackage() : getPackage(packageName);
    final String className;
    if (_version == RestliVersion.RESTLI_2_0_0) {
        className = getBuilderClassNameByVersion(RestliVersion.RESTLI_2_0_0, null, resource.getName(), true);
    } else {
        className = getBuilderClassNameByVersion(RestliVersion.RESTLI_1_0_0, null, resource.getName(), true);
    }
    final JDefinedClass facadeClass = clientPackage._class(className);
    annotate(facadeClass, sourceFile.getAbsolutePath());
    final JFieldVar baseUriField;
    final JFieldVar requestOptionsField;
    final JExpression baseUriGetter = JExpr.invoke("getBaseUriTemplate");
    final JExpression requestOptionsGetter = JExpr.invoke("getRequestOptions");
    if (_version == RestliVersion.RESTLI_2_0_0) {
        baseUriField = null;
        requestOptionsField = null;
        facadeClass._extends(BuilderBase.class);
    } else {
        // for old builder, instead of extending from RequestBuilderBase, add fields and getters in the class
        baseUriField = facadeClass.field(JMod.PRIVATE | JMod.FINAL, String.class, "_baseUriTemplate");
        requestOptionsField = facadeClass.field(JMod.PRIVATE, RestliRequestOptions.class, "_requestOptions");
        facadeClass.method(JMod.PRIVATE, String.class, "getBaseUriTemplate").body()._return(baseUriField);
        facadeClass.method(JMod.PUBLIC, RestliRequestOptions.class, "getRequestOptions").body()._return(requestOptionsField);
    }
    // make the original resource path available via a private final static variable.
    final JFieldVar originalResourceField = facadeClass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, String.class, "ORIGINAL_RESOURCE_PATH");
    final String resourcePath = getResourcePath(resource.getPath());
    originalResourceField.init(JExpr.lit(resourcePath));
    // create reference to RestliRequestOptions.DEFAULT_OPTIONS
    final JClass restliRequestOptionsClass = getCodeModel().ref(RestliRequestOptions.class);
    final JFieldRef defaultOptionsField = restliRequestOptionsClass.staticRef("DEFAULT_OPTIONS");
    if (_version == RestliVersion.RESTLI_1_0_0) {
        // same getPathComponents() logic as in RequestBuilderBase
        final JMethod pathComponentsGetter = facadeClass.method(JMod.PUBLIC, String[].class, "getPathComponents");
        pathComponentsGetter.body()._return(getCodeModel().ref(URIParamUtils.class).staticInvoke("extractPathComponentsFromUriTemplate").arg(baseUriField));
        // method that expresses the following logic
        //   (requestOptions == null) ? return RestliRequestOptions.DEFAULT_OPTIONS : requestOptions;
        final JMethod requestOptionsAssigner = facadeClass.method(JMod.PRIVATE | JMod.STATIC, RestliRequestOptions.class, "assignRequestOptions");
        final JVar requestOptionsAssignerParam = requestOptionsAssigner.param(RestliRequestOptions.class, "requestOptions");
        final JConditional requestNullCheck = requestOptionsAssigner.body()._if(requestOptionsAssignerParam.eq(JExpr._null()));
        requestNullCheck._then().block()._return(defaultOptionsField);
        requestNullCheck._else().block()._return(requestOptionsAssignerParam);
    }
    /*
    There will be 4 constructors:
      ()
      (RestliRequestOptions)
      (String)
      (String, RestliRequestOptions)
    */
    final JMethod noArgConstructor = facadeClass.constructor(JMod.PUBLIC);
    final JMethod requestOptionsOverrideConstructor = facadeClass.constructor(JMod.PUBLIC);
    final JMethod resourceNameOverrideConstructor = facadeClass.constructor(JMod.PUBLIC);
    final JMethod mainConstructor = facadeClass.constructor(JMod.PUBLIC);
    // no-argument constructor, delegates to the request options override constructor
    noArgConstructor.body().invoke(THIS).arg(defaultOptionsField);
    // request options override constructor
    final JVar requestOptionsOverrideOptionsParam = requestOptionsOverrideConstructor.param(RestliRequestOptions.class, "requestOptions");
    if (_version == RestliVersion.RESTLI_2_0_0) {
        requestOptionsOverrideConstructor.body().invoke(SUPER).arg(originalResourceField).arg(requestOptionsOverrideOptionsParam);
    } else {
        requestOptionsOverrideConstructor.body().assign(baseUriField, originalResourceField);
        final JInvocation requestOptionsOverrideAssignRequestOptions = new JBlock().invoke("assignRequestOptions").arg(requestOptionsOverrideOptionsParam);
        requestOptionsOverrideConstructor.body().assign(requestOptionsField, requestOptionsOverrideAssignRequestOptions);
    }
    // primary resource name override constructor, delegates to the main constructor
    final JVar resourceNameOverrideResourceNameParam = resourceNameOverrideConstructor.param(_stringClass, "primaryResourceName");
    resourceNameOverrideConstructor.body().invoke(THIS).arg(resourceNameOverrideResourceNameParam).arg(defaultOptionsField);
    // main constructor
    final JVar mainConsResourceNameParam = mainConstructor.param(_stringClass, "primaryResourceName");
    final JVar mainConsOptionsParam = mainConstructor.param(RestliRequestOptions.class, "requestOptions");
    final JExpression baseUriExpr;
    if (resourcePath.contains("/")) {
        baseUriExpr = originalResourceField.invoke("replaceFirst").arg(JExpr.lit("[^/]*/")).arg(mainConsResourceNameParam.plus(JExpr.lit("/")));
    } else {
        baseUriExpr = mainConsResourceNameParam;
    }
    if (_version == RestliVersion.RESTLI_2_0_0) {
        mainConstructor.body().invoke(SUPER).arg(baseUriExpr).arg(mainConsOptionsParam);
    } else {
        final JInvocation mainAssignRequestOptions = new JBlock().invoke("assignRequestOptions").arg(mainConsOptionsParam);
        mainConstructor.body().assign(baseUriField, baseUriExpr);
        mainConstructor.body().assign(requestOptionsField, mainAssignRequestOptions);
    }
    final String resourceName = CodeUtil.capitalize(resource.getName());
    final JMethod primaryResourceGetter = facadeClass.method(JMod.PUBLIC | JMod.STATIC, String.class, "getPrimaryResource");
    primaryResourceGetter.body()._return(originalResourceField);
    final List<String> pathKeys = getPathKeys(resourcePath, pathToAssocKeys);
    JClass keyTyperefClass = null;
    final JClass keyClass;
    JClass keyKeyClass = null;
    JClass keyParamsClass = null;
    final Class<?> resourceSchemaClass;
    Map<String, AssocKeyTypeInfo> assocKeyTypeInfos = Collections.emptyMap();
    StringArray supportsList = null;
    RestMethodSchemaArray restMethods = null;
    FinderSchemaArray finders = null;
    ResourceSchemaArray subresources = null;
    ActionSchemaArray resourceActions = null;
    ActionSchemaArray entityActions = null;
    if (resource.getCollection() != null) {
        resourceSchemaClass = CollectionSchema.class;
        final CollectionSchema collection = resource.getCollection();
        final String keyName = collection.getIdentifier().getName();
        // ComplexKeyResource parameterized by those two.
        if (collection.getIdentifier().getParams() == null) {
            keyClass = getJavaBindingType(collection.getIdentifier().getType(), facadeClass).valueClass;
            final JClass declaredClass = getClassRefForSchema(RestSpecCodec.textToSchema(collection.getIdentifier().getType(), _schemaResolver), facadeClass);
            if (!declaredClass.equals(keyClass)) {
                keyTyperefClass = declaredClass;
            }
        } else {
            keyKeyClass = getJavaBindingType(collection.getIdentifier().getType(), facadeClass).valueClass;
            keyParamsClass = getJavaBindingType(collection.getIdentifier().getParams(), facadeClass).valueClass;
            keyClass = getCodeModel().ref(ComplexResourceKey.class).narrow(keyKeyClass, keyParamsClass);
        }
        pathKeyTypes.put(keyName, keyClass);
        supportsList = collection.getSupports();
        restMethods = collection.getMethods();
        finders = collection.getFinders();
        subresources = collection.getEntity().getSubresources();
        resourceActions = collection.getActions();
        entityActions = collection.getEntity().getActions();
    } else if (resource.getAssociation() != null) {
        resourceSchemaClass = AssociationSchema.class;
        final AssociationSchema association = resource.getAssociation();
        keyClass = getCodeModel().ref(CompoundKey.class);
        supportsList = association.getSupports();
        restMethods = association.getMethods();
        finders = association.getFinders();
        subresources = association.getEntity().getSubresources();
        resourceActions = association.getActions();
        entityActions = association.getEntity().getActions();
        assocKeyTypeInfos = generateAssociationKey(facadeClass, association);
        final String keyName = getAssociationKey(resource, association);
        pathKeyTypes.put(keyName, keyClass);
        final List<String> assocKeys = new ArrayList<String>(4);
        for (Map.Entry<String, AssocKeyTypeInfo> entry : assocKeyTypeInfos.entrySet()) {
            assocKeys.add(entry.getKey());
            assocKeyTypes.put(entry.getKey(), entry.getValue().getBindingType());
        }
        pathToAssocKeys.put(keyName, assocKeys);
    } else if (resource.getSimple() != null) {
        resourceSchemaClass = SimpleSchema.class;
        final SimpleSchema simpleSchema = resource.getSimple();
        keyClass = _voidClass;
        supportsList = simpleSchema.getSupports();
        restMethods = simpleSchema.getMethods();
        subresources = simpleSchema.getEntity().getSubresources();
        resourceActions = simpleSchema.getActions();
    } else if (resource.getActionsSet() != null) {
        resourceSchemaClass = ActionsSetSchema.class;
        final ActionsSetSchema actionsSet = resource.getActionsSet();
        resourceActions = actionsSet.getActions();
        keyClass = _voidClass;
    } else {
        throw new IllegalArgumentException("unsupported resource type for resource: '" + resourceName + '\'');
    }
    generateOptions(facadeClass, baseUriGetter, requestOptionsGetter);
    final JFieldVar resourceSpecField = facadeClass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, _resourceSpecClass, "_resourceSpec");
    if (resourceSchemaClass == CollectionSchema.class || resourceSchemaClass == AssociationSchema.class || resourceSchemaClass == SimpleSchema.class) {
        final JClass schemaClass = getJavaBindingType(resource.getSchema(), null).schemaClass;
        final Set<ResourceMethod> supportedMethods = getSupportedMethods(supportsList);
        final JInvocation supportedMethodsExpr;
        if (supportedMethods.isEmpty()) {
            supportedMethodsExpr = _enumSetClass.staticInvoke("noneOf").arg(_resourceMethodClass.dotclass());
        } else {
            supportedMethodsExpr = _enumSetClass.staticInvoke("of");
            for (ResourceMethod resourceMethod : supportedMethods) {
                validateResourceMethod(resourceSchemaClass, resourceName, resourceMethod);
                supportedMethodsExpr.arg(_resourceMethodClass.staticRef(resourceMethod.name()));
            }
        }
        final JBlock staticInit = facadeClass.init();
        final JVar methodSchemaMap = methodMetadataMapInit(facadeClass, resourceActions, entityActions, staticInit);
        final JVar responseSchemaMap = responseMetadataMapInit(facadeClass, resourceActions, entityActions, staticInit);
        if (resourceSchemaClass == CollectionSchema.class || resourceSchemaClass == AssociationSchema.class) {
            final JClass assocKeyClass = getCodeModel().ref(TypeInfo.class);
            final JClass hashMapClass = getCodeModel().ref(HashMap.class).narrow(_stringClass, assocKeyClass);
            final JVar keyPartsVar = staticInit.decl(hashMapClass, "keyParts").init(JExpr._new(hashMapClass));
            for (Map.Entry<String, AssocKeyTypeInfo> typeInfoEntry : assocKeyTypeInfos.entrySet()) {
                final AssocKeyTypeInfo typeInfo = typeInfoEntry.getValue();
                final JInvocation typeArg = JExpr._new(assocKeyClass).arg(typeInfo.getBindingType().dotclass()).arg(typeInfo.getDeclaredType().dotclass());
                staticInit.add(keyPartsVar.invoke("put").arg(typeInfoEntry.getKey()).arg(typeArg));
            }
            staticInit.assign(resourceSpecField, JExpr._new(_resourceSpecImplClass).arg(supportedMethodsExpr).arg(methodSchemaMap).arg(responseSchemaMap).arg(keyTyperefClass == null ? keyClass.dotclass() : keyTyperefClass.dotclass()).arg(keyKeyClass == null ? JExpr._null() : keyKeyClass.dotclass()).arg(keyKeyClass == null ? JExpr._null() : keyParamsClass.dotclass()).arg(schemaClass.dotclass()).arg(keyPartsVar));
        } else //simple schema
        {
            staticInit.assign(resourceSpecField, JExpr._new(_resourceSpecImplClass).arg(supportedMethodsExpr).arg(methodSchemaMap).arg(responseSchemaMap).arg(schemaClass.dotclass()));
        }
        generateBasicMethods(facadeClass, baseUriGetter, keyClass, schemaClass, supportedMethods, restMethods, resourceSpecField, resourceName, pathKeys, pathKeyTypes, assocKeyTypes, pathToAssocKeys, requestOptionsGetter, resource.data().getDataMap("annotations"));
        if (resourceSchemaClass == CollectionSchema.class || resourceSchemaClass == AssociationSchema.class) {
            generateFinders(facadeClass, baseUriGetter, finders, keyClass, schemaClass, assocKeyTypeInfos, resourceSpecField, resourceName, pathKeys, pathKeyTypes, assocKeyTypes, pathToAssocKeys, requestOptionsGetter);
        }
        generateSubResources(sourceFile, subresources, pathKeyTypes, assocKeyTypes, pathToAssocKeys);
    } else //action set
    {
        final JBlock staticInit = facadeClass.init();
        final JInvocation supportedMethodsExpr = _enumSetClass.staticInvoke("noneOf").arg(_resourceMethodClass.dotclass());
        final JVar methodSchemaMap = methodMetadataMapInit(facadeClass, resourceActions, entityActions, staticInit);
        final JVar responseSchemaMap = responseMetadataMapInit(facadeClass, resourceActions, entityActions, staticInit);
        staticInit.assign(resourceSpecField, JExpr._new(_resourceSpecImplClass).arg(supportedMethodsExpr).arg(methodSchemaMap).arg(responseSchemaMap).arg(keyClass.dotclass()).arg(JExpr._null()).arg(JExpr._null()).arg(JExpr._null()).arg(getCodeModel().ref(Collections.class).staticInvoke("<String, Class<?>>emptyMap")));
    }
    generateActions(facadeClass, baseUriGetter, resourceActions, entityActions, keyClass, resourceSpecField, resourceName, pathKeys, pathKeyTypes, assocKeyTypes, pathToAssocKeys, requestOptionsGetter);
    generateClassJavadoc(facadeClass, resource);
    if (!checkVersionAndDeprecateBuilderClass(facadeClass, true)) {
        checkRestSpecAndDeprecateRootBuildersClass(facadeClass, resource);
    }
    return facadeClass;
}
Also used : HashMap(java.util.HashMap) ValidationResult(com.linkedin.data.schema.validation.ValidationResult) ValidationOptions(com.linkedin.data.schema.validation.ValidationOptions) ActionsSetSchema(com.linkedin.restli.restspec.ActionsSetSchema) StringArray(com.linkedin.data.template.StringArray) FinderSchemaArray(com.linkedin.restli.restspec.FinderSchemaArray) ActionSchemaArray(com.linkedin.restli.restspec.ActionSchemaArray) JConditional(com.sun.codemodel.JConditional) ArrayList(java.util.ArrayList) DataList(com.linkedin.data.DataList) List(java.util.List) Collections(java.util.Collections) JVar(com.sun.codemodel.JVar) AssociationSchema(com.linkedin.restli.restspec.AssociationSchema) JFieldRef(com.sun.codemodel.JFieldRef) RestMethodSchemaArray(com.linkedin.restli.restspec.RestMethodSchemaArray) CollectionSchema(com.linkedin.restli.restspec.CollectionSchema) RestliRequestOptions(com.linkedin.restli.client.RestliRequestOptions) JDefinedClass(com.sun.codemodel.JDefinedClass) SimpleSchema(com.linkedin.restli.restspec.SimpleSchema) JClass(com.sun.codemodel.JClass) JPackage(com.sun.codemodel.JPackage) ResourceSchemaArray(com.linkedin.restli.restspec.ResourceSchemaArray) JInvocation(com.sun.codemodel.JInvocation) JExpression(com.sun.codemodel.JExpression) JFieldVar(com.sun.codemodel.JFieldVar) URIParamUtils(com.linkedin.restli.internal.common.URIParamUtils) JBlock(com.sun.codemodel.JBlock) JMethod(com.sun.codemodel.JMethod) Map(java.util.Map) DataMap(com.linkedin.data.DataMap) HashMap(java.util.HashMap) ResourceMethod(com.linkedin.restli.common.ResourceMethod)

Example 37 with JDefinedClass

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

the class JavaRequestBuilderGenerator method generateDerivedBuilder.

private JDefinedClass generateDerivedBuilder(JClass baseBuilderClass, JClass valueClass, String finderName, String derivedBuilderName, JPackage clientPackage, ResourceMethod resourceMethod, DataMap annotations) throws JClassAlreadyExistsException {
    // this method applies to REST methods and finder
    final JDefinedClass derivedBuilderClass = clientPackage._class(JMod.PUBLIC, derivedBuilderName);
    annotate(derivedBuilderClass, null);
    checkVersionAndDeprecateBuilderClass(derivedBuilderClass, false);
    derivedBuilderClass._extends(baseBuilderClass.narrow(derivedBuilderClass));
    final JMethod derivedBuilderConstructor = derivedBuilderClass.constructor(JMod.PUBLIC);
    final JVar uriParam = derivedBuilderConstructor.param(_stringClass, "baseUriTemplate");
    final JVar resourceSpecParam = derivedBuilderConstructor.param(_resourceSpecClass, "resourceSpec");
    final JVar requestOptionsParam = derivedBuilderConstructor.param(RestliRequestOptions.class, "requestOptions");
    final JInvocation invocation = derivedBuilderConstructor.body().invoke(SUPER).arg(uriParam);
    // the new BatchGetEntityRequestBuilderBase does not need the valueClass parameter in constructor
    if (!baseBuilderClass.fullName().startsWith(BatchGetEntityRequestBuilderBase.class.getName() + "<")) {
        invocation.arg(valueClass.dotclass());
    }
    invocation.arg(resourceSpecParam).arg(requestOptionsParam);
    if (finderName != null) {
        derivedBuilderConstructor.body().add(JExpr._super().invoke("name").arg(finderName));
    }
    if (_validateEntityMethods.contains(resourceMethod) || _validatePatchMethods.contains(resourceMethod)) {
        JMethod validateMethod = derivedBuilderClass.method(JMod.PUBLIC | JMod.STATIC, ValidationResult.class, "validateInput");
        JVar inputParam;
        if (_validateEntityMethods.contains(resourceMethod)) {
            inputParam = validateMethod.param(valueClass, "input");
        } else {
            inputParam = validateMethod.param(getCodeModel().ref(PatchRequest.class).narrow(valueClass), "patch");
        }
        JBlock block = validateMethod.body();
        JVar annotationMap = block.decl(getCodeModel().ref(Map.class).narrow(String.class).narrow(getCodeModel().ref(List.class).narrow(String.class)), "annotations").init(JExpr._new(getCodeModel().ref(HashMap.class).narrow(String.class).narrow(getCodeModel().ref(List.class).narrow(String.class))));
        if (annotations != null) {
            for (Map.Entry<String, Object> entry : annotations.entrySet()) {
                DataList values = ((DataMap) entry.getValue()).getDataList("value");
                if (values != null) {
                    JInvocation list = getCodeModel().ref(Arrays.class).staticInvoke("asList");
                    for (Object value : values) {
                        list.arg(value.toString());
                    }
                    block.add(annotationMap.invoke("put").arg(entry.getKey()).arg(list));
                }
            }
        }
        JClass validatorClass = getCodeModel().ref(RestLiDataValidator.class);
        JVar validator = block.decl(validatorClass, "validator").init(JExpr._new(validatorClass).arg(annotationMap).arg(valueClass.dotclass()).arg(getCodeModel().ref(ResourceMethod.class).staticRef(resourceMethod.name())));
        block._return(validator.invoke("validateInput").arg(inputParam));
    }
    return derivedBuilderClass;
}
Also used : JDefinedClass(com.sun.codemodel.JDefinedClass) JClass(com.sun.codemodel.JClass) JInvocation(com.sun.codemodel.JInvocation) PatchRequest(com.linkedin.restli.common.PatchRequest) DataMap(com.linkedin.data.DataMap) DataList(com.linkedin.data.DataList) JBlock(com.sun.codemodel.JBlock) BatchGetEntityRequestBuilderBase(com.linkedin.restli.client.base.BatchGetEntityRequestBuilderBase) JMethod(com.sun.codemodel.JMethod) Arrays(java.util.Arrays) Map(java.util.Map) DataMap(com.linkedin.data.DataMap) HashMap(java.util.HashMap) ResourceMethod(com.linkedin.restli.common.ResourceMethod) JVar(com.sun.codemodel.JVar)

Example 38 with JDefinedClass

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

the class JavaRequestBuilderGenerator method generateBasicMethods.

@SuppressWarnings("deprecation")
private void generateBasicMethods(JDefinedClass facadeClass, JExpression baseUriExpr, JClass keyClass, JClass valueClass, Set<ResourceMethod> supportedMethods, RestMethodSchemaArray restMethods, JVar resourceSpecField, String resourceName, List<String> pathKeys, Map<String, JClass> pathKeyTypes, Map<String, JClass> assocKeyTypes, Map<String, List<String>> pathToAssocKeys, JExpression requestOptionsExpr, DataMap annotations) throws JClassAlreadyExistsException {
    final Map<ResourceMethod, RestMethodSchema> schemaMap = new HashMap<ResourceMethod, RestMethodSchema>();
    if (restMethods != null) {
        for (RestMethodSchema restMethod : restMethods) {
            schemaMap.put(ResourceMethod.fromString(restMethod.getMethod()), restMethod);
        }
    }
    final Map<ResourceMethod, Class<?>> crudBuilderClasses = new HashMap<ResourceMethod, Class<?>>();
    if (_version == RestliVersion.RESTLI_2_0_0) {
        crudBuilderClasses.put(ResourceMethod.CREATE, CreateIdRequestBuilderBase.class);
    } else {
        // we use fully qualified class name to avoid importing the deprecated class
        // so far in Java there is no way to suppress deprecation warning for import
        crudBuilderClasses.put(ResourceMethod.CREATE, com.linkedin.restli.client.base.CreateRequestBuilderBase.class);
    }
    crudBuilderClasses.put(ResourceMethod.GET, GetRequestBuilderBase.class);
    crudBuilderClasses.put(ResourceMethod.UPDATE, UpdateRequestBuilderBase.class);
    crudBuilderClasses.put(ResourceMethod.PARTIAL_UPDATE, PartialUpdateRequestBuilderBase.class);
    crudBuilderClasses.put(ResourceMethod.DELETE, DeleteRequestBuilderBase.class);
    if (_version == RestliVersion.RESTLI_2_0_0) {
        crudBuilderClasses.put(ResourceMethod.BATCH_CREATE, BatchCreateIdRequestBuilderBase.class);
    } else {
        // we use fully qualified class name to avoid importing the deprecated class
        // so far in Java there is no way to suppress deprecation warning for import
        crudBuilderClasses.put(ResourceMethod.BATCH_CREATE, com.linkedin.restli.client.base.BatchCreateRequestBuilderBase.class);
    }
    crudBuilderClasses.put(ResourceMethod.BATCH_UPDATE, BatchUpdateRequestBuilderBase.class);
    crudBuilderClasses.put(ResourceMethod.BATCH_PARTIAL_UPDATE, BatchPartialUpdateRequestBuilderBase.class);
    crudBuilderClasses.put(ResourceMethod.BATCH_DELETE, BatchDeleteRequestBuilderBase.class);
    crudBuilderClasses.put(ResourceMethod.GET_ALL, GetAllRequestBuilderBase.class);
    if (_version == RestliVersion.RESTLI_2_0_0) {
        crudBuilderClasses.put(ResourceMethod.BATCH_GET, BatchGetEntityRequestBuilderBase.class);
    } else {
        // we use fully qualified class name to avoid importing the deprecated class
        // so far in Java there is no way to suppress deprecation warning for import
        crudBuilderClasses.put(ResourceMethod.BATCH_GET, com.linkedin.restli.client.base.BatchGetRequestBuilderBase.class);
    }
    for (Map.Entry<ResourceMethod, Class<?>> entry : crudBuilderClasses.entrySet()) {
        final ResourceMethod method = entry.getKey();
        final Class<?> refModel = entry.getValue();
        if (supportedMethods.contains(method)) {
            final String methodName = RestLiToolsUtils.normalizeUnderscores(method.toString());
            final RestMethodSchema schema = schemaMap.get(method);
            generateDerivedBuilderAndJavaDoc(facadeClass, baseUriExpr, keyClass, valueClass, resourceSpecField, resourceName, pathKeys, pathKeyTypes, assocKeyTypes, pathToAssocKeys, requestOptionsExpr, annotations, method, refModel, methodName, schema);
            if ((method == ResourceMethod.CREATE || method == ResourceMethod.BATCH_CREATE) && schema != null && schema.getAnnotations() != null && schema.getAnnotations().containsKey("returnEntity")) {
                Class<?> newBuildClass = methodName.equals("create") ? CreateIdEntityRequestBuilderBase.class : BatchCreateIdEntityRequestBuilderBase.class;
                String requestName = methodName.equals("create") ? "createAndGet" : "batchCreateAndGet";
                generateDerivedBuilderAndJavaDoc(facadeClass, baseUriExpr, keyClass, valueClass, resourceSpecField, resourceName, pathKeys, pathKeyTypes, assocKeyTypes, pathToAssocKeys, requestOptionsExpr, annotations, method, newBuildClass, requestName, schema);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) RestMethodSchema(com.linkedin.restli.restspec.RestMethodSchema) JDefinedClass(com.sun.codemodel.JDefinedClass) JClass(com.sun.codemodel.JClass) Map(java.util.Map) DataMap(com.linkedin.data.DataMap) HashMap(java.util.HashMap) ResourceMethod(com.linkedin.restli.common.ResourceMethod)

Example 39 with JDefinedClass

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

the class RestRequestBuilderGenerator method run.

public static GeneratorResult run(String resolverPath, String defaultPackage, final boolean generateImported, final boolean generateDataTemplates, RestliVersion version, RestliVersion deprecatedByVersion, String targetDirectoryPath, String[] sources) throws IOException {
    final RestSpecParser parser = new RestSpecParser();
    final JavaRequestBuilderGenerator generator = new JavaRequestBuilderGenerator(resolverPath, defaultPackage, generateDataTemplates, version, deprecatedByVersion);
    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()) {
        try {
            final JDefinedClass clazz = generator.generate(pair.first, pair.second);
        } catch (Exception e) {
            message.append(e.getMessage() + "\n");
        }
    }
    if (message.length() > 0) {
        throw new IOException(message.toString());
    }
    final PegasusDataTemplateGenerator.DataTemplatePersistentClassChecker dataTemplateChecker = new PegasusDataTemplateGenerator.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);
    targetFiles.addAll(JavaCodeUtil.targetFiles(targetDirectory, dataTemplateCodeModel, classLoader, checker));
    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: " + targetFiles);
        requestBuilderCodeModel.build(new FileCodeWriter(targetDirectory, true));
        dataTemplateCodeModel.build(new FileCodeWriter(targetDirectory, true));
    }
    return new DefaultGeneratorResult(parseResult.getSourceFiles(), targetFiles, modifiedFiles);
}
Also used : ResourceSchema(com.linkedin.restli.restspec.ResourceSchema) JDefinedClass(com.sun.codemodel.JDefinedClass) IOException(java.io.IOException) PegasusDataTemplateGenerator(com.linkedin.pegasus.generator.PegasusDataTemplateGenerator) JCodeModel(com.sun.codemodel.JCodeModel) IOException(java.io.IOException) FileCodeWriter(com.sun.codemodel.writer.FileCodeWriter) JavaCodeUtil(com.linkedin.pegasus.generator.JavaCodeUtil) CodeUtil(com.linkedin.pegasus.generator.CodeUtil) DefaultGeneratorResult(com.linkedin.pegasus.generator.DefaultGeneratorResult) JavaCodeUtil(com.linkedin.pegasus.generator.JavaCodeUtil) File(java.io.File)

Example 40 with JDefinedClass

use of com.sun.codemodel.JDefinedClass in project Activiti by Activiti.

the class CxfWSDLImporter method importStructure.

protected void importStructure(Mapping mapping) {
    QName qname = mapping.getElement();
    final JType type = mapping.getType().getTypeClass();
    if (type.isPrimitive()) {
        final Class<?> primitiveClass = ReflectUtil.loadClass(type.boxify().fullName());
        final StructureDefinition structure = new PrimitiveStructureDefinition(this.namespace + qname.getLocalPart(), primitiveClass);
        this.structures.put(structure.getId(), structure);
    } else if (type instanceof JDefinedClass) {
        JDefinedClass theClass = (JDefinedClass) type;
        SimpleStructureDefinition structure = new SimpleStructureDefinition(this.namespace + qname.getLocalPart());
        this.structures.put(structure.getId(), structure);
        importFields(theClass, structure);
    } else {
        final Class<?> referencedClass = ReflectUtil.loadClass(type.fullName());
        final StructureDefinition structure = new PrimitiveStructureDefinition(this.namespace + qname.getLocalPart(), referencedClass);
        this.structures.put(structure.getId(), structure);
    }
}
Also used : StructureDefinition(org.activiti.engine.impl.bpmn.data.StructureDefinition) SimpleStructureDefinition(org.activiti.engine.impl.bpmn.data.SimpleStructureDefinition) PrimitiveStructureDefinition(org.activiti.engine.impl.bpmn.data.PrimitiveStructureDefinition) JDefinedClass(com.sun.codemodel.JDefinedClass) SimpleStructureDefinition(org.activiti.engine.impl.bpmn.data.SimpleStructureDefinition) QName(javax.xml.namespace.QName) PrimitiveStructureDefinition(org.activiti.engine.impl.bpmn.data.PrimitiveStructureDefinition) JDefinedClass(com.sun.codemodel.JDefinedClass) JClass(com.sun.codemodel.JClass) JType(com.sun.codemodel.JType)

Aggregations

JDefinedClass (com.sun.codemodel.JDefinedClass)43 JClass (com.sun.codemodel.JClass)23 JMethod (com.sun.codemodel.JMethod)17 JVar (com.sun.codemodel.JVar)13 JCodeModel (com.sun.codemodel.JCodeModel)12 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)9 JType (com.sun.codemodel.JType)9 Test (org.junit.Test)9 JClassAlreadyExistsException (com.sun.codemodel.JClassAlreadyExistsException)8 Map (java.util.Map)8 JBlock (com.sun.codemodel.JBlock)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 JExpression (com.sun.codemodel.JExpression)5 JFieldVar (com.sun.codemodel.JFieldVar)5 HashMap (java.util.HashMap)5 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)4 ArrayList (java.util.ArrayList)4 DataMap (com.linkedin.data.DataMap)3 UnionTemplateSpec (com.linkedin.pegasus.generator.spec.UnionTemplateSpec)3 ResourceMethod (com.linkedin.restli.common.ResourceMethod)3