List of usage examples for org.apache.commons.lang3 StringUtils uncapitalize
public static String uncapitalize(final String str)
Uncapitalizes a String, changing the first letter to lower case as per Character#toLowerCase(char) .
From source file:org.gerzog.jstataggr.expressions.juel.JuelExpressionHandlerBuilder.java
public JuelExpressionHandlerBuilder registerBean(final Object bean) { return registerBean(bean, StringUtils.uncapitalize(bean.getClass().getSimpleName())); }
From source file:org.graylog.plugins.pipelineprocessor.functions.strings.Uncapitalize.java
@Override protected String apply(String value, Locale unused) { return StringUtils.uncapitalize(value); }
From source file:org.grible.servlets.ui.dialogs.GetGeneratedClassDialog.java
private String getJavaClass() { StringBuilder pack = new StringBuilder(); try {//from w w w . j av a2 s. c o m pack.append("<br>package com.company.descriptors;"); StringBuilder imp = new StringBuilder(); imp.append("<br><br>import java.util.HashMap;"); imp.append("<br>import org.grible.adaptor.BaseDescriptor;"); boolean isListIncluded = false; boolean isDataHelperIncluded = false; StringBuilder header = new StringBuilder(); header.append("<br><br>public class "); header.append(className); header.append(" extends BaseDescriptor {"); StringBuilder fields = new StringBuilder("<br>"); StringBuilder methods = new StringBuilder(); StringBuilder constructor = new StringBuilder("<br><br>public "); constructor.append(className); constructor.append("(HashMap<String, String> data) {"); constructor.append("<br>super(data);"); Key[] keys = null; if (ServletHelper.isJson()) { keys = table.getTableJson().getKeys(); } else { keys = table.getKeys(); } for (int i = 0; i < keys.length; i++) { String keyName = keys[i].getName(); String fieldName = StringUtils.uncapitalize(keyName).replace(" ", ""); String type = "String"; String method = "getString(\"" + keyName + "\");"; List<String> values = null; if (ServletHelper.isJson()) { values = jDao.getValuesByKeyOrder(table, i); } else { values = pDao.getValuesByKeyOrder(table, i); } if (keys[i].getType() == KeyType.TEXT) { if (StringUtils.join(values, "").matches("[true|false]+")) { type = "boolean"; method = "getBoolean(\"" + keyName + "\");"; } } else { Table refTable = null; if (ServletHelper.isJson()) { refTable = jDao.getTable(keys[i].getRefid(), productId); } else { refTable = pDao.getTable(keys[i].getRefid()); } if (keys[i].getType() == KeyType.STORAGE) { isDataHelperIncluded = true; String refClassName = refTable.getClassName(); if (StringUtils.join(values, "").contains(";")) { isListIncluded = true; type = "List<" + refClassName + ">"; method = "DataStorage.getDescriptors(" + refClassName + ".class, getString(\"" + keyName + "\"));"; } else { type = refClassName; method = "DataStorage.getDescriptor(" + refClassName + ".class, getString(\"" + keyName + "\"));"; } } else { type = refTable.getName(); method = "(getString(\"" + keyName + "\") != null) ? " + refTable.getName() + ".valueOf(getString(\"" + keyName + "\")) : null;"; } } fields.append("<br>private ").append(type).append(" ").append(fieldName).append(";"); constructor.append("<br>this.").append(fieldName).append(" = ").append(method); methods.append("<br><br>public ").append(type).append(" get").append(keyName) .append("() {<br>return ").append(fieldName).append(";<br>}"); } if (isListIncluded) { imp.append("<br>import java.util.List;"); } if (isDataHelperIncluded) { imp.append("<br>import org.grible.adaptor.DataStorage;"); } constructor.append("<br>}"); pack.append(imp).append(header).append(fields).append(constructor).append(methods).append("<br>}"); } catch (Exception e) { e.printStackTrace(); } return pack.toString(); }
From source file:org.guess.generate.Generate.java
public static void main(String[] args) { // ========== ?? ==================== // ??????/*from w w w.jav a2 s. co m*/ // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName // ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "net.iharding.modulesmeta"; String moduleName = "meta"; // ???sys String className = "project"; // ??user String classAuthor = "Joe.zhang"; // String functionName = "??"; // ?? List<Field> fields = new ArrayList<Field>(); fields.add(new Field("projectCode", "?", "String")); fields.add(new Field("projectName", "??", "String")); fields.add(new Field("remark", "", "String")); fields.add(new Field("createDate", "", "Date")); fields.add(new Field("updateDate", "", "Date")); fields.add(new Field("createId", "", "createId")); fields.add(new Field("updateId", "", "updateId")); // ??? Boolean isEnable = true; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; // ? File projectPath = null; try { projectPath = new DefaultResourceLoader().getResource("").getFile(); // File projectPath = new File("D:/template"); while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) { projectPath = projectPath.getParentFile(); } logger.info("Project Path: {}", projectPath); // ? String tplPath = StringUtils.replace( projectPath.getAbsolutePath() + "/src/test/java/org/guess/generate/temp", "/", separator); logger.info("Template Path: {}", tplPath); // Java String javaPath = StringUtils.replaceEach( projectPath.getAbsolutePath() + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." }, new String[] { separator, separator }); // String javaPath = "D:/template"; logger.info("Java Path: {}", javaPath); String viewPath = StringUtils.replace( projectPath + "/src/main/webapp/WEB-INF/content/" + moduleName + "/" + className, "/", separator); // String viewPath = "D:/template"; // ??? Configuration cfg = new Configuration(); FileUtils.isFolderExitAndCreate(tplPath); cfg.setDirectoryForTemplateLoading(new File(tplPath)); // ??? Map<String, Object> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtil.getCurrenDate()); model.put("functionName", functionName); model.put("tableName", model.get("moduleName") + "_" + model.get("className")); model.put("fields", fields); // ? Entity Template template = cfg.getTemplate("entity.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "model" + separator + model.get("ClassName") + ".java"; // writeFile(content, filePath); logger.info("Entity: {}", filePath); // ? Dao template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + model.get("ClassName") + "Dao.java"; writeFile(content, filePath); logger.info("Dao: {}", filePath); // ? DaoImpl template = cfg.getTemplate("daoImpl.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + "impl" + separator + model.get("ClassName") + "DaoImpl.java"; writeFile(content, filePath); logger.info("Dao: {}", filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + model.get("ClassName") + "Service.java"; writeFile(content, filePath); logger.info("Service: {}", filePath); // ? Service template = cfg.getTemplate("serviceImpl.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + "impl" + separator + model.get("ClassName") + "ServiceImpl.java"; writeFile(content, filePath); logger.info("Service: {}", filePath); // ? Controller template = cfg.getTemplate("controller.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "controller" + separator + model.get("ClassName") + "Controller.java"; writeFile(content, filePath); logger.info("Controller: {}", filePath); /* // ? list.jsp template = cfg.getTemplate("list.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + "list.jsp"; writeFile(content, filePath); logger.info("Controller: {}", filePath); // ? edit.jsp template = cfg.getTemplate("edit.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + "edit.jsp"; writeFile(content, filePath); logger.info("Controller: {}", filePath);*/ logger.info("Generate Success."); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.gvnix.addon.datatables.addon.DatatablesMetadata.java
public DatatablesMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, DatatablesAnnotationValues annotationValues, JavaType entity, MemberDetails entityMemberDetails, List<FieldMetadata> identifierProperties, String entityPlural, Map<JavaSymbolName, DateTimeFormatDetails> datePatterns, JavaType webScaffoldAspectName, WebJpaBatchMetadata webJpaBatchMetadata, JpaQueryMetadata jpaQueryMetadata, WebScaffoldAnnotationValues webScaffoldAnnotationValues, Map<FinderMetadataDetails, QueryHolderTokens> findersRegistered, WebMetadataService webMetadataService, ProjectOperations projectOperations) { super(identifier, aspectName, governorPhysicalTypeMetadata); Validate.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid"); this.annotationValues = annotationValues; this.helper = new WebItdBuilderHelper(this, governorPhysicalTypeMetadata, builder.getImportRegistrationResolver()); // Roo only uses one property this.entityIdentifier = identifierProperties.get(0); this.entityIdentifierType = entityIdentifier.getFieldType(); this.entity = entity; this.entityMemberDetails = entityMemberDetails; this.entityName = entity.getSimpleTypeName(); this.entityPlural = entityPlural; this.entityDatePatterns = datePatterns; this.webJpaBatchMetadata = webJpaBatchMetadata; this.jpaQueryMetadata = jpaQueryMetadata; this.webScaffoldAnnotationValues = webScaffoldAnnotationValues; // Prepare method names which includes entity plural this.findAllMethodName = new JavaSymbolName("findAll".concat(StringUtils.capitalize(entityPlural))); this.renderItemsMethodName = new JavaSymbolName("render".concat(StringUtils.capitalize(entityPlural))); this.findByParametersMethodName = new JavaSymbolName( "find".concat(StringUtils.capitalize(entityPlural)).concat("ByParameters")); this.entityListType = new JavaType(LIST.getFullyQualifiedTypeName(), 0, DataType.TYPE, null, Arrays.asList(entity)); this.entityList = StringUtils.uncapitalize(entityPlural); // this.entityIdListType = new // JavaType(LIST.getFullyQualifiedTypeName(), // 0, DataType.TYPE, null, Arrays.asList(entityIdentifierType)); this.entityIdArrayType = new JavaType(entityIdentifierType.getFullyQualifiedTypeName(), 1, DataType.TYPE, null, null);/* w ww.j a v a2s . com*/ // store finders information if (findersRegistered != null) { this.findersRegistered = Collections.unmodifiableMap(findersRegistered); } else { this.findersRegistered = null; } this.webMetadataService = webMetadataService; this.projectOperations = projectOperations; // Adding precedence declaration // This aspect before webScaffold builder.setDeclarePrecedence(aspectName, webScaffoldAspectName); // Adding field definition builder.addField(getConversionServiceField()); builder.addField(getMessageSourceField()); builder.addField(getBeanWrapperField()); builder.addField(getEntityManagerProvider()); builder.addField(getDatatablesUtilsBean()); builder.addField(getQuerydslUtilsBean()); // Adding methods builder.addMethod(getListDatatablesRequestMethod()); builder.addMethod(getPopulateDatatablesConfig()); builder.addMethod(getListRooRequestMethod()); builder.addMethod(getPopulateParameterMapMethod()); builder.addMethod(getGetPropertyMapMethod()); builder.addMethod(getGetPropertyMapUrlMethod()); builder.addMethod(getSetDatatablesBaseFilterMethod(annotationValues)); builder.addMethod(getColumnTypeRequestMethod()); builder.addMethod(geti18nTextRequestMethod()); // Detail methods builder.addMethod(getListDatatablesDetailMethod()); builder.addMethod(getCreateDatatablesDetailMethod()); builder.addMethod(getUpdateDatatablesDetailMethod()); builder.addMethod(getDeleteDatatablesDetailMethod()); // Add AJAX mode required methods if (isAjax()) { if (isStantardMode()) { builder.addMethod(getFindAllMethod()); // Adding filters methods builder.addMethod(getCheckFilterExpressionsMethod()); } else { if (isInlineEditing()) { // InlineEditing not supported on non-standard mode throw new IllegalArgumentException( aspectName.getFullyQualifiedTypeName().concat(".@GvNIXDatatables: 'mode = ") .concat(annotationValues.getMode()).concat("' can't use inlineEditing")); } // Render mode requires this methods builder.addMethod(getPopulateItemForRenderMethod()); builder.addMethod(getRenderItemsMethod()); builder.addMethod(getFindAllMethodRenderMode()); } // add ajax request for finders if (this.findersRegistered != null) { for (Entry<FinderMetadataDetails, QueryHolderTokens> finder : this.findersRegistered.entrySet()) { if (finder.getValue() != null) { builder.addMethod(getAjaxFinderMethod(finder.getKey(), finder.getValue())); } } } // Export via AJAX methods addAjaxExportMethods(); } else if (!isStantardMode()) { // Non-Standard view mode requires AJAX data mode throw new IllegalArgumentException( aspectName.getFullyQualifiedTypeName().concat(".@GvNIXDatatables: 'mode = ") .concat(annotationValues.getMode()).concat("' requires 'ajax = true'")); } else { // DOM standard mode requires finder by parameters builder.addMethod(getFindByParametersMethod()); } if (isInlineEditing()) { if (!hasJpaBatchSupport()) { // InlineEditing requires batch support throw new IllegalArgumentException(aspectName.getFullyQualifiedTypeName().concat( ". Inline editing requires batch support. Run 'jpa batch add' command or 'web mvc batch add' command")); } builder.addMethod(getJsonFormsMethod(true)); builder.addMethod(getJsonFormsMethod(false)); builder.addMethod(getRenderUpdateFormsMethod()); builder.addMethod(getPopulateItemForRenderMethod()); } // Create a representation of the desired output ITD itdTypeDetails = builder.build(); }
From source file:org.gvnix.addon.datatables.addon.DatatablesMetadata.java
/** * Returns <code>listDatatablesDetail</code> method <br> * This method is default list request handler for detail datatables * controllers/*w w w .ja v a2s. co m*/ * * @return */ private MethodMetadata getListDatatablesDetailMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType.convertFromJavaTypes(MODEL, HTTP_SERVLET_REQUEST); // Include Item in parameters to use spring's binder to get baseFilter // values parameterTypes.add(new AnnotatedJavaType(entity, new AnnotationMetadataBuilder(MODEL_ATTRIBUTE).build())); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists( new JavaSymbolName(DatatablesConstants.LIST_DTTBLS_DET_MTHD_NAME), parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // @RequestMapping AnnotationMetadataBuilder methodAnnotation = new AnnotationMetadataBuilder(); methodAnnotation.setAnnotationType(REQUEST_MAPPING); // @RequestMapping(... produces = "text/html") methodAnnotation.addStringAttribute(DatatablesConstants.RQST_MAP_ANN_PROD_NAME, DatatablesConstants.RQST_MAP_ANN_VAL_HTML); // @RequestMapping(... value ="/list") methodAnnotation.addStringAttribute(DatatablesConstants.RQST_MAP_ANN_VAL_NAME, DatatablesConstants.RQST_MAP_ANN_LIST); annotations.add(methodAnnotation); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(UI_MODEL); parameterNames.add(new JavaSymbolName(DatatablesConstants.REQUEST_PARAMETER_NAME)); // Include Item in parameters to use spring's binder to get baseFilter // values parameterNames.add(new JavaSymbolName(StringUtils.uncapitalize(entityName))); // Add method javadoc (not generated to disk because #10229) CommentStructure comments = new CommentStructure(); JavadocComment javadoc = new JavadocComment( "Show only the list view fragment for entity as detail datatables into a master datatables."); comments.addComment(javadoc, CommentStructure.CommentLocation.BEGINNING); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // [Code generated] bodyBuilder.appendFormalLine( "// Do common datatables operations: get entity list filtered by request parameters"); if (!isAjax()) { // listDatatables(uiModel, request, pet); bodyBuilder.appendFormalLine(LIST_DATATABLES.getSymbolName().concat("(uiModel, request, ") .concat(entity.getSimpleTypeName().toLowerCase()).concat(");")); } else { // listDatatables(uiModel, request); bodyBuilder.appendFormalLine(LIST_DATATABLES.getSymbolName().concat("(uiModel, request);")); } bodyBuilder.appendFormalLine("// Show only the list fragment (without footer, header, menu, etc.) "); // return "forward:/WEB-INF/views/pets/list.jspx"; bodyBuilder.appendFormalLine("return \"forward:/WEB-INF/views/" .concat(webScaffoldAnnotationValues.getPath()).concat("/list.jspx\";")); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, new JavaSymbolName(DatatablesConstants.LIST_DTTBLS_DET_MTHD_NAME), JavaType.STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); methodBuilder.setCommentStructure(comments); return methodBuilder.build(); // Build and return a MethodMetadata // instance }
From source file:org.gvnix.addon.datatables.addon.DatatablesMetadata.java
/** * Gets <code>populateItemForRender</code> method <br> * This methods prepares request attributes to render a entity item in * non-standard render mode. User can make push-in of this method to * customize the parameters received on target .jspx view. * // w ww . j a v a 2 s .c o m * @return */ private MethodMetadata getPopulateItemForRenderMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType.convertFromJavaTypes(HTTP_SERVLET_REQUEST, entity, JavaType.BOOLEAN_PRIMITIVE); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(POPULATE_ITEM_FOR_RENDER, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(REQUEST_PARAM_NAME); parameterNames.add(new JavaSymbolName(StringUtils.uncapitalize(entityName))); parameterNames.add(new JavaSymbolName("editing")); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildPopulateItemForRenderMethodBody(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, POPULATE_ITEM_FOR_RENDER, JavaType.VOID_PRIMITIVE, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance }
From source file:org.gvnix.addon.datatables.addon.DatatablesMetadata.java
/** * Build standard body method for <code>populateItemForRender</code> method <br> * This methods prepares request attributes to render a entity item in * non-standard render mode. User can make push-in of this method to * customize the parameters received on target .jspx view. * // ww w . j a v a 2 s.co m * @param bodyBuilder */ private void buildPopulateItemForRenderMethodBody(InvocableMemberBodyBuilder bodyBuilder) { // Model uiModel = new ExtendedModelMap(); bodyBuilder.appendFormalLine(String.format("%s uiModel = new %s();", MODEL, EXTENDED_MODEL_MAP)); bodyBuilder.appendFormalLine(""); // request.setAttribute("pet", pet); bodyBuilder .appendFormalLine(String.format("%s.setAttribute(\"%s\", %s);", REQUEST_PARAM_NAME.getSymbolName(), StringUtils.uncapitalize(entityName), StringUtils.uncapitalize(entityName) )); // request.setAttribute("itemId", // conversion_service.convert(pet.getId(), String.class); bodyBuilder.appendFormalLine(String.format( "%s.setAttribute(\"itemId\", %s.convert(%s.get%s(),String.class));", REQUEST_PARAM_NAME.getSymbolName(), getConversionServiceField().getFieldName().getSymbolName(), StringUtils.uncapitalize(entityName), StringUtils.capitalize(entityIdentifier.getFieldName().getSymbolName()))); bodyBuilder.appendFormalLine(""); // if (editing) { bodyBuilder.appendFormalLine("if (editing) {"); bodyBuilder.indent(); // // spring from:input tag uses BindingResult to locate property // editors for each bean // // property. So, we add a request attribute (required key id // BindingResult.MODEL_KEY_PREFIX + object name) // // with a correctly initialized bindingResult. bodyBuilder.appendFormalLine( "// spring from:input tag uses BindingResult to locate property editors for each bean"); bodyBuilder.appendFormalLine( "// property. So, we add a request attribute (required key id BindingResult.MODEL_KEY_PREFIX + object name)"); bodyBuilder.appendFormalLine("// with a correctly initialized bindingResult."); // BeanPropertyBindingResult bindindResult = new // BeanPropertyBindingResult(vet, "vet"); bodyBuilder.appendFormalLine(String.format("%s bindindResult = new %s(%s, \"%s\");", helper.getFinalTypeName(BEAN_PROPERTY_BINDING_RESULT), helper.getFinalTypeName(BEAN_PROPERTY_BINDING_RESULT), StringUtils.uncapitalize(entityName), StringUtils.uncapitalize(entityName))); // bindindResult.initConversion(conversionService_datatables); bodyBuilder.appendFormalLine(String.format("bindindResult.initConversion(%s);", getConversionServiceField().getFieldName().getSymbolName())); // request.setAttribute(BindingResult.MODEL_KEY_PREFIX + // "vet",bindindResult); bodyBuilder.appendFormalLine(String.format("%s.setAttribute(%s.MODEL_KEY_PREFIX + \"%s\",bindindResult);", REQUEST_PARAM_NAME.getSymbolName(), helper.getFinalTypeName(SpringJavaType.BINDING_RESULT), StringUtils.uncapitalize(entityName))); // // Add date time patterns and enums to populate inputs bodyBuilder.appendFormalLine("// Add date time patterns and enums to populate inputs"); // populateEditForm(uiModel, vet); bodyBuilder.appendFormalLine( String.format("populateEditForm(uiModel, %s);", StringUtils.uncapitalize(entityName))); if (!entityDatePatterns.isEmpty()) { // } else { bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine(ELSE); bodyBuilder.indent(); // // Add date time patterns bodyBuilder.appendFormalLine("// Add date time patterns"); // Add date patterns (if any) // Delegates on Roo standard populate date patterns method // addDateTimeFormatPatterns(uiModel); bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(uiModel);"); } // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(""); // Load uiModel attributes into request bodyBuilder.appendFormalLine("// Load uiModel attributes into request"); // Map<String,Object> modelMap = uiModel.asMap(); bodyBuilder.appendFormalLine( String.format("%s modelMap = uiModel.asMap();", helper.getFinalTypeName(MAP_STRING_OBJECT))); // for (Entry<String,Object> entry : uiModel.asMap().entrySet()){ bodyBuilder.appendFormalLine( String.format("for (%s key : modelMap.keySet()){", helper.getFinalTypeName(JavaType.STRING))); bodyBuilder.indent(); // request.setAttribute(entry.getKey(), entry.getValue()); bodyBuilder.appendFormalLine("request.setAttribute(key, modelMap.get(key));"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); }
From source file:org.gvnix.addon.datatables.addon.DatatablesMetadata.java
/** * Build method body for <code>listDatatables</code> method for DOM mode * //from w ww . ja va 2 s.c om * @param bodyBuilder */ private void buildListDatatablesRequesMethodDomBody(InvocableMemberBodyBuilder bodyBuilder) { // // Get parentId parameter for details bodyBuilder.appendFormalLine("// Get parentId parameter for details"); // if (request.getParameterMap().containsKey("_dt_parentId")){ bodyBuilder.appendFormalLine("if (request.getParameterMap().containsKey(\"_dt_parentId\")){"); bodyBuilder.indent(); // uiModel.addAttribute("parentId",request.getParameter("_dt_parentId")); bodyBuilder.appendFormalLine("uiModel.addAttribute(\"parentId\",request.getParameter(\"_dt_parentId\"));"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); String listVarName = StringUtils.uncapitalize(entityPlural); bodyBuilder.appendFormalLine("// Get data (filtered by received parameters) and put it on pageContext"); // List<Visit> visits = // findByParameters(visit,request.getParameterNames()); bodyBuilder.appendFormalLine(String.format( "@SuppressWarnings(\"unchecked\") %s %s = %s(%s, request != null ? request.getParameterNames() : null);", helper.getFinalTypeName(entityListType), listVarName, findByParametersMethodName.getSymbolName(), entityName)); // uiModel.addAttribute("pets",pets); bodyBuilder.appendFormalLine(String.format("%s.addAttribute(\"%s\",%s);", UI_MODEL.getSymbolName(), entityPlural.toLowerCase(), listVarName)); buildListDatatablesRequestMethodDetailBody(bodyBuilder); // return "pets/list"; bodyBuilder.appendFormalLine(String.format("return \"%s/list\";", webScaffoldAnnotationValues.getPath())); }
From source file:org.gvnix.addon.datatables.addon.DatatablesMetadata.java
/** * Returns <code>findAllMethod</code> method <br> * This method handles datatables AJAX request for data which are no related * to a Roo Dynamic finder.//w w w .ja va2 s.c o m * * @return */ private MethodMetadata getFindAllMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>(); parameterTypes.add(new AnnotatedJavaType(DATATABLES_CRITERIA_TYPE, new AnnotationMetadataBuilder(DATATABLES_PARAMS).build())); parameterTypes.add(new AnnotatedJavaType(entity, new AnnotationMetadataBuilder(MODEL_ATTRIBUTE).build())); parameterTypes.addAll(AnnotatedJavaType.convertFromJavaTypes(HTTP_SERVLET_REQUEST)); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(findAllMethodName, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); AnnotationMetadataBuilder methodAnnotation = new AnnotationMetadataBuilder(); methodAnnotation.setAnnotationType(REQUEST_MAPPING); methodAnnotation.addStringAttribute(HEADERS, ACCEPT_APPLICATION_JSON); methodAnnotation.addStringAttribute(DatatablesConstants.RQST_MAP_ANN_VAL_NAME, "/datatables/ajax"); methodAnnotation.addStringAttribute(DatatablesConstants.RQST_MAP_ANN_PROD_NAME, APPLICATION_JSON); annotations.add(methodAnnotation); annotations.add(new AnnotationMetadataBuilder(RESPONSE_BODY)); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(CRITERIA_PARAM_NAME); parameterNames.add(new JavaSymbolName(StringUtils.uncapitalize(entityName))); parameterNames.add(REQUEST_PARAM_NAME); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildFindAllDataMethodBody(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, findAllMethodName, FIND_ALL_RETURN, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance }