use of com.sun.codemodel.JFieldVar in project jsonschema2pojo by joelittlejohn.
the class EnumRule method addFactoryMethod.
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);
JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
JVar valueParam = fromValue.param(backingType, "value");
JBlock body = fromValue.body();
JVar constant = body.decl(_enum, "constant");
constant.init(quickLookupMap.invoke("get").arg(valueParam));
JConditional _if = body._if(constant.eq(JExpr._null()));
JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
JExpression expr = valueParam;
// if string no need to add ""
if (!isString(backingType)) {
expr = expr.plus(JExpr.lit(""));
}
illegalArgumentException.arg(expr);
_if._then()._throw(illegalArgumentException);
_if._else()._return(constant);
ruleFactory.getAnnotator().enumCreatorMethod(fromValue);
}
use of com.sun.codemodel.JFieldVar in project rest.li by linkedin.
the class JavaDataTemplateGenerator method generateSchemaField.
private JFieldVar generateSchemaField(JDefinedClass templateClass, DataSchema schema) {
final JFieldVar schemaField = templateClass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, schema.getClass(), DataTemplateUtil.SCHEMA_FIELD_NAME);
final String schemaJson = SchemaToJsonEncoder.schemaToJson(schema, JsonBuilder.Pretty.COMPACT);
final JInvocation parseSchemaInvocation;
if (schemaJson.length() < MAX_SCHEMA_FIELD_JSON_LENGTH) {
parseSchemaInvocation = _dataTemplateUtilClass.staticInvoke("parseSchema").arg(schemaJson);
} else {
JInvocation stringBuilderInvocation = JExpr._new(_stringBuilderClass);
for (int index = 0; index < schemaJson.length(); index += MAX_SCHEMA_FIELD_JSON_LENGTH) {
stringBuilderInvocation = stringBuilderInvocation.invoke("append").arg(schemaJson.substring(index, Math.min(schemaJson.length(), index + MAX_SCHEMA_FIELD_JSON_LENGTH)));
}
stringBuilderInvocation = stringBuilderInvocation.invoke("toString");
parseSchemaInvocation = _dataTemplateUtilClass.staticInvoke("parseSchema").arg(stringBuilderInvocation);
}
schemaField.init(JExpr.cast(getCodeModel()._ref(schema.getClass()), parseSchemaInvocation));
return schemaField;
}
use of com.sun.codemodel.JFieldVar 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;
}
use of com.sun.codemodel.JFieldVar in project Activiti by Activiti.
the class WSDLImporter method importStructure.
private void importStructure(Mapping mapping) {
QName qname = mapping.getElement();
JDefinedClass theClass = (JDefinedClass) mapping.getType().getTypeClass();
SimpleStructureDefinition structure = (SimpleStructureDefinition) this.structures.get(this.namespace + qname.getLocalPart());
Map<String, JFieldVar> fields = theClass.fields();
int index = 0;
for (Entry<String, JFieldVar> entry : fields.entrySet()) {
Class<?> fieldClass = ReflectUtil.loadClass(entry.getValue().type().boxify().fullName());
structure.setFieldName(index, entry.getKey(), fieldClass);
index++;
}
}
use of com.sun.codemodel.JFieldVar in project raml-module-builder by folio-org.
the class ClientGenerator method generateClassMeta.
public void generateClassMeta(String className, Object globalPath) {
String mapType = System.getProperty("json.type");
if (mapType != null) {
if (mapType.equals("mongo")) {
mappingType = "mongo";
}
}
this.globalPath = "GLOBAL_PATH";
/* Adding packages here */
JPackage jp = jCodeModel._package(RTFConsts.CLIENT_GEN_PACKAGE);
try {
/* Giving Class Name to Generate */
this.className = className.substring(RTFConsts.INTERFACE_PACKAGE.length() + 1, className.indexOf("Resource"));
jc = jp._class(this.className + CLIENT_CLASS_SUFFIX);
JDocComment com = jc.javadoc();
com.add("Auto-generated code - based on class " + className);
/* class variable to root url path to this interface */
JFieldVar globalPathVar = jc.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, String.class, "GLOBAL_PATH");
globalPathVar.init(JExpr.lit("/" + (String) globalPath));
/* class variable tenant id */
tenantId = jc.field(JMod.PRIVATE, String.class, "tenantId");
token = jc.field(JMod.PRIVATE, String.class, "token");
/* class variable to http options */
JFieldVar options = jc.field(JMod.PRIVATE, HttpClientOptions.class, "options");
/* class variable to http client */
httpClient = jc.field(JMod.PRIVATE, HttpClient.class, "httpClient");
/* constructor, init the httpClient - allow to pass keep alive option */
JMethod consructor = constructor(JMod.PUBLIC);
JVar host = consructor.param(String.class, "host");
JVar port = consructor.param(int.class, "port");
JVar param = consructor.param(String.class, "tenantId");
JVar token = consructor.param(String.class, "token");
JVar keepAlive = consructor.param(boolean.class, "keepAlive");
JVar connTO = consructor.param(int.class, "connTO");
JVar idleTO = consructor.param(int.class, "idleTO");
/* populate constructor */
JBlock conBody = consructor.body();
conBody.assign(JExpr._this().ref(tenantId), param);
conBody.assign(JExpr._this().ref(token), token);
conBody.assign(options, JExpr._new(jCodeModel.ref(HttpClientOptions.class)));
conBody.invoke(options, "setLogActivity").arg(JExpr.TRUE);
conBody.invoke(options, "setKeepAlive").arg(keepAlive);
conBody.invoke(options, "setDefaultHost").arg(host);
conBody.invoke(options, "setDefaultPort").arg(port);
conBody.invoke(options, "setConnectTimeout").arg(connTO);
conBody.invoke(options, "setIdleTimeout").arg(idleTO);
JExpression vertx = jCodeModel.ref("org.folio.rest.tools.utils.VertxUtils").staticInvoke("getVertxFromContextOrNew");
conBody.assign(httpClient, vertx.invoke("createHttpClient").arg(options));
/* constructor, init the httpClient */
JMethod consructor2 = constructor(JMod.PUBLIC);
JVar hostVar = consructor2.param(String.class, "host");
JVar portVar = consructor2.param(int.class, "port");
JVar tenantIdVar = consructor2.param(String.class, "tenantId");
JVar tokenVar = consructor2.param(String.class, "token");
JBlock conBody2 = consructor2.body();
conBody2.invoke("this").arg(hostVar).arg(portVar).arg(tenantIdVar).arg(tokenVar).arg(JExpr.TRUE).arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
JMethod consructor1 = constructor(JMod.PUBLIC);
JVar hostVar1 = consructor1.param(String.class, "host");
JVar portVar1 = consructor1.param(int.class, "port");
JVar tenantIdVar1 = consructor1.param(String.class, "tenantId");
JVar tokenVar1 = consructor1.param(String.class, "token");
JVar keepAlive1 = consructor1.param(boolean.class, "keepAlive");
JBlock conBody1 = consructor1.body();
conBody1.invoke("this").arg(hostVar1).arg(portVar1).arg(tenantIdVar1).arg(tokenVar1).arg(keepAlive1).arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
/* constructor, init the httpClient */
JMethod consructor3 = constructor(JMod.PUBLIC);
JBlock conBody3 = consructor3.body();
conBody3.invoke("this").arg("localhost").arg(JExpr.lit(8081)).arg("folio_demo").arg("folio_demo").arg(JExpr.FALSE).arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
consructor3.javadoc().add("Convenience constructor for tests ONLY!<br>Connect to localhost on 8081 as folio_demo tenant.");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
Aggregations