private void generateEventsHandler() throws Exception { if (domain.getCrudevent() != null || (domain.getEvent() != null && !domain.getEvent().isEmpty())) { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getEventPackage(domain), GeneratorHelper.getMasterHandlerClassName(domain)); classWriter.setInterface(true); if (domain.getCrudevent() != null) { for (final String before : GeneratorHelper.getBeforeEventName()) { classWriter.addExtend(before + domain.getName() + "Handler"); } for (final String after : GeneratorHelper.getAfterEventName()) { classWriter.addExtend(domain.getName() + after + "Handler"); } } if (domain.getEvent() != null) { for (final Event event : domain.getEvent()) { classWriter.addExtend(GeneratorHelper.getHandlerClassName(event)); } } classWriter.generateContentAndStore(); } }
private void createRobotServerMappingFile(List<Element> msgElements, String module) throws Exception { List<MessageObject> toGSMsgs = new ArrayList<MessageObject>(); for (Iterator i = msgElements.iterator(); i.hasNext(); ) { Element message = (Element) i.next(); MessageObject msg = new MessageObject(); String msgType = message.getAttributeValue("type"); msg.setType(msgType); msg.setClassName(GeneratorHelper.generateServerClassName(msgType)); String msgTypePrefix = msgType.substring(1, 2); toGSMsgs.add(msg); } if (toGSMsgs.size() == 0) { return; } VelocityContext context = new VelocityContext(); context.put("module", module); String mappingClassName = StringUtils.upperCaseFirstCharOnly(module) + "MsgMappingProvider"; context.put("classname", mappingClassName); if (toGSMsgs.size() > 0) { context.put("msgs", toGSMsgs); String outputFile = robotRootPath + "msg" + File.separator + mappingClassName + ".java"; GeneratorHelper.generate(context, robotMappingTemplate_game, outputFile); } }
private String makeTypeString(StringBuilder retVal, Column column) { int type = column.getColumnType(); String sqlType = null; // HB 09/09: PSQL specific type mapping switch (type) { case Types.CLOB: sqlType = "TEXT"; break; case Types.BLOB: sqlType = "BYTEA"; break; default: sqlType = GeneratorHelper.getSqlName(type); } if (sqlType == null) { throw new IllegalStateException("Unsupported field type " + type); } retVal.append(" "); if (column.isAutoincrement()) { retVal.append("SERIAL "); } else { retVal.append(sqlType); } if (GeneratorHelper.needsLength(type)) { retVal.append("(").append(column.getLength()).append(")"); } return retVal.toString(); }
/** * 生成服务器端文件,每个消息一个文件 * * @param messages * @throws Exception */ private void createServerFiles(List<Element> messages, String module) throws Exception { for (Iterator i = messages.iterator(); i.hasNext(); ) { Element msgElement = (Element) i.next(); MessageObject msgObj = new MessageObject(); String msgType = msgElement.getAttributeValue("type"); msgObj.setType(msgType); msgObj.setClassName(GeneratorHelper.generateServerClassName(msgType)); msgObj.setModule(module); msgObj.setComment(msgElement.getAttributeValue("comment")); msgObj.setHandleMethodName(GeneratorHelper.generateHandleMethodName(msgType)); if (msgElement.getAttributeValue("playerQueue") != null) { msgObj.setPlayerQueue( msgElement.getAttributeValue("playerQueue").equals("true") ? true : false); } if (msgElement.getAttributeValue("friendQueue") != null) { msgObj.setFriendQueue(msgElement.getAttribute("friendQueue").getValue().equals("true")); } if (msgElement.getAttributeValue("guildQueue") != null) { msgObj.setGuildQueue(msgElement.getAttribute("guildQueue").getValue().equals("true")); } List fElements = msgElement.getChildren("field", NAME_SPACE); setMsgObjFields(msgObj, fElements, false, false); VelocityContext context = new VelocityContext(); context.put("message", msgObj); context.put("list", msgObj.getFields()); String templateFileName = ""; String outputFile = ""; for (int j = 0; j < serverMsgTemplates.length; j++) { String templateName = serverMsgTemplates[j]; if (templateName.substring(0, 2).equalsIgnoreCase(msgType.substring(0, 2))) { templateFileName = templateName; char lastCharOfTempate = templateName.charAt(templateName.length() - 4); switch (lastCharOfTempate) { case 'g': // 放在GameServer outputFile = gameRootPath + msgObj.getModule() + File.separator + "msg" + File.separator + msgObj.getClassName() + ".java"; break; default: throw new RuntimeException("模板名称非法," + templateName); } GeneratorHelper.generate(context, templateFileName, outputFile); // JavaGeneratorHelper.generateJavaFile(msgObj, outputFile + "0"); } } msgs.put(msgObj.getClassName(), msgObj); } }
private ClassWriter generatePushCommandX(final Pushmethod method, final String type) throws Exception { final String className = method.getName().substring(0, 1).toUpperCase() + method.getName().substring(1) + "Command"; final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getCommandPackage(domain), className); final Parameter pushListener = new Parameter(); pushListener.setName("listener"); pushListener.setClazz("com.ponysdk.core.command.PushListener<" + type + ">"); final List<Parameter> parameters = method.getParameter(); final List<Parameter> clonedParameters = new ArrayList<Parameter>(parameters); clonedParameters.add(pushListener); final Constructor constructor = new Constructor(); constructor.setConstructorParameters(clonedParameters); constructor.setSuperConstructorParameters(Arrays.asList(pushListener)); classWriter.addConstructor(constructor); for (final Parameter param : parameters) { classWriter.addClassMembers(param); } classWriter.addConstants( "private static " + GeneratorHelper.getServiceFullClassName(domain) + " service;"); final StringBuilder template = new StringBuilder(); template.append("@Override\n"); template.append("public com.ponysdk.core.event.HandlerRegistration execute(){\n"); template.append(" if (service == null) {\n"); template.append( " service = com.ponysdk.core.service.PonyServiceRegistry.getPonyService(" + GeneratorHelper.getServiceFullClassName(domain) + ".class);"); template.append(" }\n"); if (method.getParameter().isEmpty()) template.append(" return service.%1$sRegistration(this);\n"); else template.append(" return service.%1$sRegistration(%2$s,this);\n"); template.append("}\n"); classWriter.addMethod( template.toString(), method.getName(), GeneratorHelper.getParameterNamesToString(method.getParameter())); return classWriter; }
public void createMessageFiles(String modelFileName) { try { System.out.println(modelFileName); msgs = new HashMap<String, MessageObject>(); fields = new HashMap<String, List<FieldObject>>(); String configFilePath = GeneratorHelper.getBuildPath(MODEL_DIC + modelFileName); SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(configFilePath); Element root = doc.getRootElement(); String module = root.getAttributeValue("module"); // 所属模块 List messages = root.getChildren("message", NAME_SPACE); // 消息体定义 List constants = null; Element constantsElement = root.getChild("constants", NAME_SPACE); if (constantsElement != null) { constants = root.getChild("constants", NAME_SPACE).getChildren(); // 常量定义 } else { constants = new ArrayList(); } this.replaceMacros(messages); createServerFiles(messages, module); createClientFile(messages, module, constants); createServerMappingFile(messages, module); createRobotServerMappingFile(messages, module); } catch (Exception e) { logger.error("", e); } }
private void generateEvent(final Event event) throws Exception { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getEventPackage(domain), GeneratorHelper.getEventClassName(event)); if (event.getParameter() != null) { for (final Parameter parameter : event.getParameter()) { classWriter.addClassMembers(parameter); } } classWriter.addExtend(GeneratorHelper.getBusinessEventExtends(event)); // Constant classWriter.addConstants( "public static final com.ponysdk.core.event.Event.Type<" + GeneratorHelper.getHandlerClassName(event) + "> TYPE = new com.ponysdk.core.event.Event.Type<" + GeneratorHelper.getHandlerClassName(event) + ">();"); // Build constructor final Parameter sourceComponentParameter = new Parameter(); sourceComponentParameter.setName("sourceComponent"); sourceComponentParameter.setClazz("java.lang.Object"); final List<Parameter> superConstructorParameters = new ArrayList<Parameter>(); superConstructorParameters.add(sourceComponentParameter); final List<Parameter> constructorParameters = new ArrayList<Parameter>(event.getParameter()); constructorParameters.add(0, sourceComponentParameter); final Constructor constructor = new Constructor(constructorParameters, superConstructorParameters); classWriter.addConstructor(constructor); // Build methods classWriter.addLine("@Override"); classWriter.addLine( "protected void dispatch(" + GeneratorHelper.getHandlerClassName(event) + " handler) {"); classWriter.addLine(" handler.on" + event.getName() + "(this);"); classWriter.addLine("}"); classWriter.addNewLine(); classWriter.addLine("@Override"); classWriter.addLine( "public com.ponysdk.core.event.Event.Type<" + GeneratorHelper.getHandlerClassName(event) + "> getAssociatedType() {"); classWriter.addLine(" return TYPE;"); classWriter.addLine("}"); // Adding classWriter.setGenerateGetter(true); classWriter.generateContentAndStore(); }
public void generateCRUDEvents() throws Exception { if (domain.getCrudevent() != null) { for (final String before : GeneratorHelper.getBeforeEventName()) { final Event event = new Event(); event.name = before + domain.getName(); event.parameter = domain.getCrudevent().getParameter(); generateEvent(event); generateHandler(event); } for (final String after : GeneratorHelper.getAfterEventName()) { final Event event = new Event(); event.name = domain.getName() + after; event.business = true; event.parameter = domain.getCrudevent().getParameter(); generateEvent(event); generateHandler(event); } } }
private void generateHandler(final Event event) throws Exception { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getEventPackage(domain), GeneratorHelper.getHandlerClassName(event)); classWriter.setInterface(true); classWriter.addExtend("com.ponysdk.core.event.EventHandler"); // Build event method classWriter.addLine( "public void on" + event.getName() + "(" + GeneratorHelper.getEventClassName(event) + " event);"); classWriter.generateContentAndStore(); }
/** * @param field * @param subFieldElements */ private void setSubFields(FieldObject field, List<Element> subFieldElements) { List<FieldObject> subFields = new ArrayList<FieldObject>(); fields.put(field.getType(), subFields); for (Element subElement : subFieldElements) { FieldObject subField = new FieldObject(); subField.setType(subElement.getAttributeValue("type")); subField.setClientType(subElement.getAttributeValue("clientType")); if (StringUtils.isEmpty(subField.getClientType())) { subField.setClientType(GeneratorHelper.getClientClassName(subField.getType()) + "Data"); } subField.setSmallName(subElement.getAttributeValue("name")); subField.setComment(subElement.getAttributeValue("comment")); if (subElement.getAttributeValue("list") != null) { subField.setList(subElement.getAttributeValue("list").equals("true") ? true : false); field.setHasListField(true); } subFields.add(subField); List<Element> subsubFieldElements = subElement.getChildren("field", NAME_SPACE); if (subsubFieldElements.size() > 0) { this.setSubFields(subField, subsubFieldElements); } // 如果不是系统定义的类型则说明是子消息 if (!new ArrayListWrapper(sysTypes).contains(subField.getType())) { subField.setIsNewType(true); if (subField.getType().indexOf("_") > 0) { subField.setType(GeneratorHelper.generateServerClassName(subField.getType())); } } } field.setSubFields(subFields); // 如果配置了子节点,而且类型中不存在包名,则说明是新定义的类型 if (field.getType().indexOf(".") == -1) { field.setNeedCreateType(true); } }
private void loadModelMacros(String marcoFileName) { try { String configFilePath = GeneratorHelper.getBuildPath(MODEL_DIC + marcoFileName); SAXBuilder builder = new SAXBuilder(); Document doc; doc = builder.build(configFilePath); Element root = doc.getRootElement(); List<Element> macroElements = root.getChildren("macro", NAME_SPACE); // 消息体定义 for (Element macroElement : macroElements) { macros.put(macroElement.getAttributeValue("id"), macroElement); } // 处理宏定义中引用其它宏的情况 for (Element macro : macros.values()) { List<Element> fieldList = macro.getChildren(); for (Element macroField : fieldList) { String otherMacroId = macroField.getAttributeValue("macro"); if (this.doReplaceMacros(macroField, otherMacroId)) { List<Element> childFields = macroField.getChildren(); if (childFields != null && childFields.size() > 0) { for (Element childField : childFields) { String otherMacroId2 = childField.getAttributeValue("macro"); if (this.doReplaceMacros(childField, otherMacroId2)) { List<Element> subChildFields = childField.getChildren(); if (subChildFields != null && subChildFields.size() > 0) { for (Element subField : subChildFields) { String otherMacroId3 = subField.getAttributeValue("macro"); if (this.doReplaceMacros(subField, otherMacroId3)) { List<Element> ssFields = subField.getChildren(); if (ssFields != null && ssFields.size() > 0) { for (Element sssField : ssFields) { String otherMacroId4 = sssField.getAttributeValue("macro"); this.doReplaceMacros(sssField, otherMacroId4); } } } } } } } } } } } } catch (Exception e) { logger.error("", e); } }
/** @param args */ public static void main(String[] args) { if (replaceDirectly) { FileUtil.cleanFolder(new File(dataPath), ".svn"); FileUtil.cleanFolder(new File(messagePath), ".svn"); FileUtil.delete(new File(messageTypePath + "MessageType.as")); } else { FileUtil.delete(new File(clientRootPath)); } Map<String, Object> context = new HashMap<String, Object>(); MessageGenerator generator = new MessageGenerator(); generator.loadModelMacros("macros.xml"); context.put("engine", generator); JsScriptHelper.executeScriptFile( GeneratorHelper.getBuildPath("msg/message_generator.js"), context); generator.createClientMessageType(); }
private void generateCommands() throws Exception { if (domain.getService() != null) { for (final Method method : domain.getService().getMethod()) { final String returnClass = GeneratorHelper.getClassName(method.getReturn()); final ClassWriter classWriter = generateCommandX(method, returnClass); if (returnClass.equals("void") && method.getReturn().getValue() == null) { classWriter.addExtend( "com.ponysdk.core.command.AbstractServiceCommand<java.lang.Object>"); } else { classWriter.addExtend( "com.ponysdk.core.command.AbstractServiceCommand<" + returnClass + ">"); } classWriter.generateContentAndStore(); } } }
private void generateHibernateDAO(final Dao dao) throws Exception { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getDAOPackage(domain), GeneratorHelper.getDAOClassName(domain)); classWriter.addExtend("com.ponysdk.hibernate.dao.HibernateDAO"); // Add static logger classWriter.addConstants( "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(" + GeneratorHelper.getDAOClassName(domain) + ".class);"); // Create constructor final List<Parameter> parameters = new ArrayList<Parameter>(); final Parameter sessionFactoryParameter = new Parameter(); sessionFactoryParameter.setName("sessionFactory"); sessionFactoryParameter.setClazz("org.hibernate.SessionFactory"); parameters.add(sessionFactoryParameter); final Constructor constructor = new Constructor(parameters, parameters); classWriter.addConstructor(constructor); // Create findById method classWriter.addNewLine(); classWriter.addLine("final public " + dao.getClazz() + " findById(final long id) {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine( " log.debug(\"getting " + domain.getName() + " instance with id: \" + id);"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" try {"); classWriter.addLine( " " + dao.getClazz() + " instance = (" + dao.getClazz() + ") sessionFactory.getCurrentSession().get(" + dao.getClazz() + ".class, id);"); classWriter.addLine(" return instance;"); classWriter.addLine(" } catch (final RuntimeException re) {"); classWriter.addLine(" log.error(\"getting " + domain.getName() + " by id failed\", re);"); classWriter.addLine(" throw re;"); classWriter.addLine(" }"); classWriter.addLine("}"); // Create findAll method classWriter.addNewLine(); classWriter.addLine("@SuppressWarnings(\"unchecked\")"); classWriter.addLine("public java.util.List<" + dao.getClazz() + "> findAll() {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine( " log.debug(\"finding " + domain.getName() + " instance by example\");"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" try {"); classWriter.addLine( " final java.util.List<" + dao.getClazz() + "> results = sessionFactory.getCurrentSession().createQuery(\"FROM " + domain.getName() + "\").list();"); classWriter.addLine(" return results;"); classWriter.addLine(" } catch (final RuntimeException re) {"); classWriter.addLine(" log.error(\"finding all " + domain.getName() + " failed\", re);"); classWriter.addLine(" throw re;"); classWriter.addLine(" }"); classWriter.addLine("}"); classWriter.generateContentAndStore(); }
/** * 设置消息对象的字段 * * @param msgObj * @param msgElement */ private void setMsgObjFields( MessageObject msgObj, List fElements, boolean isClient, boolean isCppClient) { for (Iterator j = fElements.iterator(); j.hasNext(); ) { Element fElement = (Element) j.next(); FieldObject field = new FieldObject(); field.setType(fElement.getAttributeValue("type")); field.setClientType(fElement.getAttributeValue("clientType")); if (StringUtils.isEmpty(field.getClientType())) { field.setClientType(GeneratorHelper.getClientClassName(field.getType()) + "Data"); } field.setSmallName(fElement.getAttributeValue("name")); field.setComment(fElement.getAttributeValue("comment")); if (fElement.getAttribute("defaultValue") != null) { String defaultValue = fElement.getAttributeValue("defaultValue"); if (StringUtils.isEmpty(defaultValue)) { if (!TYPE_STRING.equals(field.getType())) { defaultValue = "0"; } else { defaultValue = ""; } } if (TYPE_STRING.equals(field.getType())) { defaultValue = "\"" + defaultValue + "\""; } field.setDefaultValue("=" + defaultValue); } else { field.setDefaultValue(""); } List<Element> subFieldElements = fElement.getChildren("field", NAME_SPACE); if (fElement.getAttributeValue("bytes") != null) { field.setBytes(fElement.getAttributeValue("bytes").equals("true") ? true : false); } if (fElement.getAttributeValue("list") != null) { field.setList(fElement.getAttributeValue("list").equals("true") ? true : false); msgObj.setHasListField(true); } boolean isSubMsg = "true".equalsIgnoreCase(fElement.getAttributeValue("subMsg")); field.setSubMsg(isSubMsg); if (isSubMsg) { field.setSubMsgType(GeneratorHelper.generateServerClassName(field.getType())); msgObj.setListMsg(true); if (isCppClient) { field.setList(true); msgObj.setHasListField(true); field.setType("_LZOBEX_" + field.getType()); } } // 如果不是系统定义的类型则说明是子消息 if (!new ArrayListWrapper(sysTypes).contains(field.getType())) { if (!isCppClient || !field.isSubMsg()) { field.setIsNewType(true); if (!isClient && field.getType().indexOf("_") > 0) { field.setType(GeneratorHelper.generateServerClassName(field.getType())); } } } if (subFieldElements.size() > 0) { this.setSubFields(field, subFieldElements); } else { if (isClient && field.getIsNewType()) { // 客户端生成消息的时候要为其补全 field.setSubFields(fields.get(field.getType())); } if (!isClient && field.getList() && field.getIsNewType()) { String type = field.getType(); field.setSubFields(msgs.get(type).getFields()); } } if (field.isSubMsg() && !isCppClient) { msgObj.addSubMsg(field); } else { msgObj.addField(field); } } }
/** * 生成客户端数据模型 * * @param messages */ private void createClientModel(List<MessageObject> messages, String module) { Map<String, FieldObject> newTypeFields = new HashMap<String, FieldObject>(); for (MessageObject msgObj : messages) { List<FieldObject> fields = msgObj.getFields(); for (FieldObject fieldObject : fields) { if (fieldObject.getIsNewType()) { // 先遍历它的子类型 for (FieldObject subfieldObject : fieldObject.getSubFields()) { if (subfieldObject.getIsNewType()) { // 先遍历子类型的子类型 for (FieldObject subsubfieldObject : subfieldObject.getSubFields()) { if (subsubfieldObject.getIsNewType()) { // 先遍历子类型的子类型 for (FieldObject sssfieldObject : subsubfieldObject.getSubFields()) { if (sssfieldObject.getIsNewType()) { sssfieldObject.setType(sssfieldObject.getClientType()); if (sssfieldObject.getClientType().contains(".")) { sssfieldObject.setType( GeneratorHelper.getClientClassName(sssfieldObject.getType())); continue; } newTypeFields.put(sssfieldObject.getClientType(), sssfieldObject); } } subsubfieldObject.setType(subsubfieldObject.getClientType()); if (subsubfieldObject.getClientType().contains(".")) { subsubfieldObject.setType( GeneratorHelper.getClientClassName(subsubfieldObject.getType())); continue; } newTypeFields.put(subsubfieldObject.getClientType(), subsubfieldObject); } } // subfieldObject.setType(subfieldObject.getClientType()); if (subfieldObject.getClientType().contains(".")) { subfieldObject.setType( GeneratorHelper.getClientClassName(subfieldObject.getType())); continue; } newTypeFields.put(subfieldObject.getClientType(), subfieldObject); } } fieldObject.setType(fieldObject.getClientType()); if (fieldObject.getClientType().contains(".")) { fieldObject.setType(GeneratorHelper.getClientClassName(fieldObject.getType())); continue; } newTypeFields.put(fieldObject.getClientType(), fieldObject); } } } for (FieldObject fieldObject : newTypeFields.values()) { VelocityContext context = new VelocityContext(); context.put("modulename", module); context.put("model", fieldObject); String outputFilePath; if (replaceDirectly) { outputFilePath = dataPath + fieldObject.getType() + ".as"; } else { outputFilePath = clientRootPath + File.separator + module + File.separator + "data" + File.separator + fieldObject.getType() + ".as"; } try { GeneratorHelper.generate(context, clientModelTemplate, outputFilePath); } catch (Exception e) { e.printStackTrace(); } } }
/** * 生成客户端文件,每个模块一个文件 * * @param msgElements * @throws Exception */ private void createClientFile( List<Element> msgElements, String module, List<Element> contantElements) throws Exception { List<MessageObject> cgMsgs = new ArrayList<MessageObject>(); List<MessageObject> gcMsgs = new ArrayList<MessageObject>(); List<MessageObject> allClientMsgs = new ArrayList<MessageObject>(); for (Iterator i = msgElements.iterator(); i.hasNext(); ) { Element mElement = (Element) i.next(); MessageObject msgObj = new MessageObject(); String msgType = mElement.getAttributeValue("type"); fields.put(msgType, msgObj.getFields()); msgObj.setType(msgType); msgObj.setClassName(GeneratorHelper.generateServerClassName(msgType)); msgObj.setModule(mElement.getAttributeValue("module")); msgObj.setComment(mElement.getAttributeValue("comment")); msgObj.setHandleMethodName(GeneratorHelper.generateHandleMethodName(msgType)); List fElements = mElement.getChildren("field", NAME_SPACE); this.setMsgObjFields(msgObj, fElements, true, false); if (msgType.substring(0, 2).equalsIgnoreCase("cg")) { cgMsgs.add(msgObj); } else if (msgType.substring(0, 2).equalsIgnoreCase("gc")) { gcMsgs.add(msgObj); } if (msgType.contains("c") || msgType.contains("C")) { allClientMsgs.add(msgObj); } } this.createClientModel(allClientMsgs, module); List<ConstantObject> contants = new ArrayList<ConstantObject>(); for (Iterator i = contantElements.iterator(); i.hasNext(); ) { Element constantElement = (Element) i.next(); String constantName = constantElement.getAttributeValue("name"); String constantDesc = constantElement.getValue(); ConstantObject constantObj = new ConstantObject( constantName, constantDesc .replaceAll(File.separator + "n", "") .replaceAll(File.separator + "r", "") .trim()); contants.add(constantObj); } VelocityContext context = new VelocityContext(); context.put("module", StringUtils.upperCaseFirstCharOnly(module)); context.put("modulename", module); for (String templateFileName : clientMsgTemplates) { String outputFileNameSuffix = null; String templatePrefix = templateFileName.substring(0, 2); if (templatePrefix.equals("gc")) { if (gcMsgs.size() == 0) { continue; } context.put("msgs", gcMsgs); outputFileNameSuffix = "GCMessage.as"; } else if (templatePrefix.equals("cg")) { if (cgMsgs.size() == 0) { continue; } context.put("msgs", cgMsgs); outputFileNameSuffix = "CGMessage.as"; } context.put("constants", contants); String outputFilePath; if (replaceDirectly) { outputFilePath = messagePath + StringUtils.upperCaseFirstCharOnly(module) + outputFileNameSuffix; } else { outputFilePath = clientRootPath + File.separator + module + File.separator + "message" + File.separator + StringUtils.upperCaseFirstCharOnly(module) + outputFileNameSuffix; } GeneratorHelper.generate(context, templateFileName, outputFilePath); } }
/* * Services : MongoDBDAO */ private void generateMongoDBDAO(final Dao dao) throws Exception { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getDAOPackage(domain), GeneratorHelper.getDAOClassName(domain)); classWriter.addImport("com.fasterxml.jackson.databind.ObjectMapper"); classWriter.addImport("com.mongodb.BasicDBObject"); classWriter.addImport("com.mongodb.DBCollection"); classWriter.addImport("com.mongodb.DBObject"); classWriter.addImport("com.mongodb.DBCursor"); classWriter.addImport("java.util.List"); classWriter.addImport("java.util.ArrayList"); classWriter.addExtend("com.ponysdk.mongodb.dao.MongoDAO"); // Add static logger classWriter.addConstants( "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(" + GeneratorHelper.getDAOClassName(domain) + ".class);"); // Create constructor final List<Parameter> parameters = new ArrayList<Parameter>(); final Parameter sessionFactoryParameter = new Parameter(); sessionFactoryParameter.setName("sessionFactory"); sessionFactoryParameter.setClazz("org.hibernate.SessionFactory"); // parameters.add(sessionFactoryParameter); final Constructor constructor = new Constructor(parameters, parameters); classWriter.addConstructor(constructor); // Create findById method classWriter.addNewLine(); classWriter.addLine("final public " + dao.getClazz() + " findById(final long id) {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine( " log.debug(\"getting " + domain.getName() + " instance with id: \" + id);"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" try {"); classWriter.addLine( " DBCollection collection = db.getCollection(\"" + domain.getName().toLowerCase() + "\");"); classWriter.addLine(" BasicDBObject basicDBObject = new BasicDBObject(\"id\"," + "id);"); classWriter.addLine(" final DBObject foundInstance = collection.findOne(basicDBObject);"); classWriter.addLine(" " + dao.getClazz() + " instance = null;"); classWriter.addLine(" return toModel(foundInstance);"); classWriter.addLine(" } catch (final Exception re) {"); classWriter.addLine(" log.error(\"getting " + domain.getName() + " by id failed\", re);"); classWriter.addLine(" throw new RuntimeException(re);"); classWriter.addLine(" }"); classWriter.addLine("}"); classWriter.addLine("private " + dao.getClazz() + " toModel(DBObject dbObject) {"); classWriter.addLine(" if (dbObject == null) return null;"); classWriter.addLine(" final ObjectMapper mapper = new ObjectMapper();"); classWriter.addLine(" try{"); classWriter.addLine( " " + dao.getClazz() + " model = mapper.readValue(dbObject.toString(), " + dao.getClazz() + ".class);"); classWriter.addLine(" model.setID(dbObject.get(\"_id\"));"); classWriter.addLine(" return model;"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine(" log.error(\"toModel " + domain.getName() + " failed\", e);"); classWriter.addLine(" throw new RuntimeException(e);"); classWriter.addLine(" }"); classWriter.addLine("}"); // Create findAll method classWriter.addNewLine(); classWriter.addLine("@SuppressWarnings(\"unchecked\")"); classWriter.addLine("public java.util.List<" + dao.getClazz() + "> findAll() {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine(" log.debug(\"finding all " + domain.getName() + "\");"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" DBCursor cursor = null;"); classWriter.addLine(" try {"); classWriter.addLine( " DBCollection collection = db.getCollection(\"" + domain.getName().toLowerCase() + "\");"); classWriter.addLine(" cursor = collection.find();"); classWriter.addLine( " List<" + dao.getClazz() + "> result = new ArrayList<" + dao.getClazz() + ">();"); classWriter.addLine(" while(cursor.hasNext()){"); classWriter.addLine(" result.add(toModel(cursor.next()));"); classWriter.addLine(" }"); classWriter.addLine(" return result;"); classWriter.addLine(" } catch (final RuntimeException re) {"); classWriter.addLine(" log.error(\"finding all " + domain.getName() + " failed\", re);"); classWriter.addLine(" throw re;"); classWriter.addLine(" } finally{"); classWriter.addLine(" cursor.close();"); classWriter.addLine(" }"); classWriter.addLine("}"); // Create find by query method classWriter.addNewLine(); classWriter.addLine("@SuppressWarnings(\"unchecked\")"); classWriter.addLine("@Override"); classWriter.addLine("public java.util.List<" + dao.getClazz() + "> find(Object query) {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine(" log.debug(\"finding " + domain.getName() + " by query\");"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" DBCursor cursor = null;"); classWriter.addLine(" try {"); classWriter.addLine( " DBCollection collection = db.getCollection(\"" + domain.getName().toLowerCase() + "\");"); classWriter.addLine(" cursor = collection.find((DBObject)query);"); classWriter.addLine( " List<" + dao.getClazz() + "> result = new ArrayList<" + dao.getClazz() + ">();"); classWriter.addLine(" while(cursor.hasNext()){"); classWriter.addLine(" result.add(toModel(cursor.next()));"); classWriter.addLine(" }"); classWriter.addLine(" return result;"); classWriter.addLine(" } catch (final RuntimeException re) {"); classWriter.addLine(" log.error(\"find " + domain.getName() + " failed\", re);"); classWriter.addLine(" throw re;"); classWriter.addLine(" } finally{"); classWriter.addLine(" cursor.close();"); classWriter.addLine(" }"); classWriter.addLine("}"); classWriter.generateContentAndStore(); }
private void generateCRUDMethos() throws Exception { // Insert CRUD methods if (domain.getService() != null && domain.getService().getCrudmethod() != null) { // Return final Return crudReturn = new Return(); crudReturn.setClazz(domain.getService().getCrudmethod().getClazz()); // Parameters final Parameter crudParameter = new Parameter(); crudParameter.setClazz(domain.getService().getCrudmethod().getClazz()); crudParameter.setName(GeneratorHelper.getFirstCharToLower(domain.getName())); final Parameter crudIDParameter = new Parameter(); crudIDParameter.setClazz("long"); crudIDParameter.setName(GeneratorHelper.getFirstCharToLower(domain.getName()) + "ID"); // Add CRUD methods final Method createMethod = createCRUDMethod("create" + domain.getName(), crudParameter, crudReturn); final Method readMethod = createCRUDMethod("read" + domain.getName(), crudIDParameter, crudReturn); final Method updateMethod = createCRUDMethod("update" + domain.getName(), crudParameter, crudReturn); final Method deleteMethod = createCRUDMethod("delete" + domain.getName(), crudIDParameter, new Return()); // Create the implementation class of these CRUD methods if the HibernateDAO is set if (domain.getService().getDao() != null) { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getServerServicePackage(domain), GeneratorHelper.getServiceImplClassName(domain)); classWriter.addImplements(GeneratorHelper.getServiceClassName(domain)); classWriter.setGenerateGetter(true); classWriter.setGenerateSetter(true); // Add static logger classWriter.addConstants( "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(" + GeneratorHelper.getServiceImplClassName(domain) + ".class);"); // Add service HibernateDAO object final Parameter daoParameter = new Parameter(); daoParameter.setClazz( GeneratorHelper.getDAOPackage(domain) + "." + GeneratorHelper.getDAOClassName(domain)); daoParameter.setName( GeneratorHelper.getFirstCharToLower(GeneratorHelper.getDAOClassName(domain))); classWriter.addClassMembers(daoParameter); for (final Method method : domain.getService().getMethod()) { final String resultClass = GeneratorHelper.getClassName(method.getReturn()); classWriter.addNewLine(); classWriter.addLine("@Override"); classWriter.addLine( "public " + resultClass + " " + method.getName() + "(" + GeneratorHelper.getParameterToString(method.getParameter()) + ") throws Exception {"); if (!"void".equals(resultClass)) { classWriter.addLine(" return null;"); } classWriter.addLine("}"); } final String domainClass = domain.getName(); final String domainDAOParameter = GeneratorHelper.getFirstCharToLower(GeneratorHelper.getDAOClassName(domain)); final String domainParameter = GeneratorHelper.getFirstCharToLower(domain.getName()); final String domainParameterID = domainParameter + "ID"; /* * CRUD method implementation */ // Create classWriter.addLine("@Override"); classWriter.addLine( "public " + GeneratorHelper.getClassName(createMethod.getReturn()) + " " + createMethod.getName() + " (" + GeneratorHelper.getParameterToString(createMethod.getParameter()) + ") throws Exception {"); classWriter.addLine(" " + domainDAOParameter + ".beginTransaction();"); classWriter.addLine(" try {"); classWriter.addLine(" " + domainDAOParameter + ".save(" + domainParameter + ");"); classWriter.addLine(" " + domainDAOParameter + ".commit();"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine( " log.error(\"final Cannot create " + domainClass + " in database\", e);"); classWriter.addLine(" " + domainDAOParameter + ".rollback();"); classWriter.addLine( " throw new Exception(\"Cannot create " + domainClass + " in database\", e);"); classWriter.addLine(" }"); classWriter.addLine(" return " + domainParameter + ";"); classWriter.addLine("}"); // Read classWriter.addLine("@Override"); classWriter.addLine( "public " + GeneratorHelper.getClassName(createMethod.getReturn()) + " " + readMethod.getName() + " (" + GeneratorHelper.getParameterToString(readMethod.getParameter()) + ") throws Exception {"); classWriter.addLine( " " + GeneratorHelper.getClassName(createMethod.getReturn()) + " " + domainParameter + " = null;"); classWriter.addLine(" " + domainDAOParameter + ".beginTransaction();"); classWriter.addLine(" try {"); classWriter.addLine( " " + domainParameter + " = " + domainDAOParameter + ".findById(" + domainParameterID + ");"); classWriter.addLine(" " + domainDAOParameter + ".commit();"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine( " log.error(\"final Cannot find " + domain.getName() + " in database\", e);"); classWriter.addLine(" " + domainDAOParameter + ".rollback();"); classWriter.addLine( " throw new Exception(\"Cannot find " + domain.getName() + " in database\", e);"); classWriter.addLine(" }"); classWriter.addLine(" return " + domainParameter + ";"); classWriter.addLine("}"); // Update classWriter.addLine("@Override"); classWriter.addLine( "public " + GeneratorHelper.getClassName(updateMethod.getReturn()) + " " + updateMethod.getName() + " (" + GeneratorHelper.getParameterToString(updateMethod.getParameter()) + ") throws Exception {"); classWriter.addLine(" " + domainDAOParameter + ".beginTransaction();"); classWriter.addLine(" try {"); classWriter.addLine( " " + domainDAOParameter + ".saveOrUpdate(" + domainParameter + ");"); classWriter.addLine(" " + domainDAOParameter + ".commit();"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine( " log.error(\"final Cannot update " + domainClass + " in database\", e);"); classWriter.addLine(" " + domainDAOParameter + ".rollback();"); classWriter.addLine( " throw new Exception(\"Cannot update " + domainClass + " in database\", e);"); classWriter.addLine(" }"); classWriter.addLine(" return " + domainParameter + ";"); classWriter.addLine("}"); // Delete classWriter.addLine("@Override"); classWriter.addLine( "public " + GeneratorHelper.getClassName(deleteMethod.getReturn()) + " " + deleteMethod.getName() + " (" + GeneratorHelper.getParameterToString(deleteMethod.getParameter()) + ") throws Exception {"); classWriter.addLine(" " + domainDAOParameter + ".beginTransaction();"); classWriter.addLine(" try {"); classWriter.addLine( " " + GeneratorHelper.getClassName(createMethod.getReturn()) + " " + domainParameter + " = " + domainDAOParameter + ".findById(" + domainParameterID + ");"); classWriter.addLine(" " + domainDAOParameter + ".delete(" + domainParameter + ");"); classWriter.addLine(" " + domainDAOParameter + ".commit();"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine( " log.error(\"final Cannot delete " + domain.getName() + " in database\", e);"); classWriter.addLine(" " + domainDAOParameter + ".rollback();"); classWriter.addLine( " throw new Exception(\"Cannot delete " + domain.getName() + " in database\", e);"); classWriter.addLine(" }"); classWriter.addLine("}"); classWriter.generateContentAndStore(); } domain.getService().getMethod().add(createMethod); domain.getService().getMethod().add(readMethod); domain.getService().getMethod().add(updateMethod); domain.getService().getMethod().add(deleteMethod); } }
private void generateService() throws Exception { final String className = GeneratorHelper.getServiceClassName(domain); final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getServicePackage(domain), className); classWriter.setInterface(true); classWriter.addExtend("com.ponysdk.core.service.PonyService"); if (domain.getService() != null) { for (final Method method : domain.getService().getMethod()) { final String returnClass = GeneratorHelper.getClassName(method.getReturn()); classWriter.addLine( "public " + returnClass + " " + method.getName() + "(" + GeneratorHelper.getParameterToString(method.getParameter()) + ") throws Exception;"); } for (final Pushmethod method : domain.getService().getPushmethod()) { if (method.getParameter().isEmpty()) { classWriter.addLine( "public com.ponysdk.core.event.HandlerRegistration " + method.getName() + "Registration(com.ponysdk.core.command.PushListener<" + method.getType() + "> listener);"); } else { classWriter.addLine( "public com.ponysdk.core.event.HandlerRegistration " + method.getName() + "Registration(" + GeneratorHelper.getParameterToString(method.getParameter()) + ", com.ponysdk.core.command.PushListener<" + method.getType() + "> listener);"); } } final Dao dao = domain.getService().getDao(); if (dao != null) { switch (dao.getDaoLayer()) { case HIBERNATE: generateHibernateDAO(dao); break; case MONGODB: generateMongoDBDAO(dao); break; default: System.err.println( dao.getDaoLayer() + " HibernateDAO generation ignored for class" + domain.getService().getDao().getClazz() + ". Only " + DaoLayer.HIBERNATE + " is supported"); } } } classWriter.generateContentAndStore(); }
private ClassWriter generateCommandX(final Method method, final String resultClass) throws Exception { final String className = method.getName().substring(0, 1).toUpperCase() + method.getName().substring(1) + "Command"; final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getCommandPackage(domain), className); final Constructor constructor = new Constructor(); final Parameter eventBusParameter = new Parameter(); eventBusParameter.setName("eventBus"); eventBusParameter.setClazz("com.ponysdk.core.event.EventBus"); final List<Parameter> parameters = method.getParameter(); final List<Parameter> clonedParameters = new ArrayList<Parameter>(); for (final Parameter parameter : parameters) { final Parameter clonedParameter = new Parameter(); clonedParameter.setClazz(parameter.getClazz()); clonedParameter.setName(parameter.getName()); clonedParameter.setCollection(parameter.getCollection()); clonedParameters.add(clonedParameter); } final Constructor constructor2 = new Constructor(); constructor2.setConstructorParameters(new ArrayList<Parameter>(clonedParameters)); clonedParameters.add(0, eventBusParameter); constructor.setConstructorParameters(clonedParameters); constructor.setSuperConstructorParameters(Arrays.asList(eventBusParameter)); classWriter.addConstructor(constructor); classWriter.addConstructor(constructor2); for (final Parameter param : parameters) { classWriter.addClassMembers(param); } classWriter.addConstants( "private static " + GeneratorHelper.getServiceFullClassName(domain) + " service;"); final StringBuilder template = new StringBuilder(); template.append("@Override\n"); if (resultClass.equals("void") && method.getReturn().getValue() == null) { template.append("protected java.lang.Void execute0() throws Exception {\n"); } else { template.append("protected " + resultClass + " execute0() throws Exception {\n"); } template.append(" if (service == null) {\n"); template.append( " service = com.ponysdk.core.service.PonyServiceRegistry.getPonyService(" + GeneratorHelper.getServiceFullClassName(domain) + ".class);"); template.append(" }\n"); if (resultClass.equals("void") && method.getReturn().getValue() == null) { template.append(" service.%1$s(%2$s);\n"); template.append(" return null;\n"); } else { template.append(" return service.%1$s(%2$s);\n"); } template.append("}\n"); classWriter.addMethod( template.toString(), method.getName(), GeneratorHelper.getParameterNamesToString(method.getParameter())); return classWriter; }