Example #1
0
 @Transient
 public ImageAnchor getLargeImageBean() {
   ImageAnchorBean bean = new ImageAnchorBean();
   bean.setTitle(getTitle());
   bean.setUrl(getUrl());
   bean.setSrc(getLargeImageUrl());
   Model model = getModel();
   if (model == null) {
     return bean;
   }
   ModelField mf = model.getField("largeImage");
   if (mf == null) {
     return bean;
   }
   Map<String, String> map = mf.getCustoms();
   String width = map.get(ModelField.IMAGE_WIDTH);
   if (StringUtils.isNotBlank(width)) {
     bean.setWidth(NumberUtils.createInteger(width));
   }
   String height = map.get(ModelField.IMAGE_HEIGHT);
   if (StringUtils.isNotBlank(height)) {
     bean.setHeight(NumberUtils.createInteger(height));
   }
   return bean;
 }
Example #2
0
  private void implementSetter(
      TreeLogger logger,
      MethodBuffer mb,
      JMethod method,
      ModelMagic manifest,
      HasModelFields models,
      Annotation[] annos) {

    JPrimitiveType primitive = method.getReturnType().isPrimitive();
    boolean isVoid = primitive == JPrimitiveType.VOID;
    boolean isFluent = ModelGeneratorGwt.isFluent(method);
    String name = ModelGeneratorGwt.fieldName(method, manifest);
    ModelField field = models.getOrMakeField(name);
    field.addSetter(
                X_Source.binaryToSource(method.getReturnType().getQualifiedBinaryName()),
                name,
                ModelGeneratorGwt.toTypes(method.getParameterTypes()))
            .fluent =
        isFluent;
    if (!isFluent && !isVoid) {
      mb.println("var value = getProperty(\"" + name + "\");");
    }
    JParameter[] params = method.getParameters();
    if (params.length != 1)
      throw new NotConfiguredCorrectly(
          "A setter method, " + method.getJsniSignature() + " must have exactly one parameter");
    mb.println("setProperty(\"" + name + "\", A);");
    if (!isVoid) mb.println("return " + (isFluent ? "this;" : "value;"));
  }
 /**
  * prepares the model for template generation
  *
  * @param resources
  */
 protected void preprocess(List<Resource> resources) {
   for (Resource resource : resources) {
     for (Model model : resource.getModels()) {
       //	apply keyword mapping
       for (ModelField modelField : model.getFields()) {
         modelField.setName(reservedWordMapper.translate(modelField.getName()));
       }
     }
   }
 }
  /**
   * Generates assembler classes if the API returns more than one object.
   *
   * @param resources
   * @param templateGroup
   */
  private void generateModelClassesForInput(
      List<Resource> resources, StringTemplateGroup templateGroup) {
    List<String> generatedClasses = new ArrayList<String>();
    for (Resource resource : resources) {
      if (resource.getEndPoints() != null) {
        for (Endpoint endpoint : resource.getEndPoints()) {
          if (endpoint.getOperations() != null) {
            for (EndpointOperation operation : endpoint.getOperations()) {
              ResourceMethod method =
                  operation.generateMethod(
                      endpoint, resource, dataTypeMappingProvider, nameGenerator);
              if (method.getInputModel() != null) {
                Model model = method.getInputModel();
                if (model != null) {
                  if (!generatedClasses.contains(model.getName())) {
                    List<String> imports = new ArrayList<String>();
                    imports.addAll(this.config.getDefaultModelImports());
                    for (ModelField param : model.getFields()) {
                      param.setName(reservedWordMapper.translate(param.getName()));
                      for (String importDef :
                          param
                              .getFieldDefinition(
                                  this.getDataTypeMappingProvider(), config, nameGenerator)
                              .getImportDefinitions()) {
                        if (!imports.contains(importDef)) {
                          imports.add(importDef);
                        }
                      }
                    }
                    StringTemplate template = templateGroup.getInstanceOf(MODEL_OBJECT_TEMPLATE);

                    template.setAttribute("fields", model.getFields());
                    template.setAttribute("imports", imports);
                    template.setAttribute("extends", config.getDefaultModelBaseClass());
                    template.setAttribute(
                        "annotationPackageName", languageConfig.getAnnotationPackageName());
                    template.setAttribute("className", model.getGenratedClassName());
                    template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
                    File aFile =
                        new File(
                            languageConfig.getModelClassLocation()
                                + model.getGenratedClassName()
                                + languageConfig.getClassFileExtension());
                    writeFile(aFile, template.toString(), "Input model class");
                    generatedClasses.add(model.getName());
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  private List<Field> findUserCustomedRequiredFields(
      Class<?> modelClass, List<ModelField> userCustomedFields) {

    List<Field> requiredField = new ArrayList<Field>();
    for (ModelField modelField : userCustomedFields) {
      if (modelField.isNotNull()) {
        String name = modelField.getName();
        Field field = ModelReflectionUtil.getModelField(name, modelClass);
        requiredField.add(field);
      }
    }
    return requiredField;
  }
  /**
   * Creates a wrapper model class that contains all model classes as list of objects. This class is
   * used for storing test data
   */
  private void generateWrapperClassForTestData(
      List<String> generatedClassNames, StringTemplateGroup templateGroup) {
    Model model = new Model();
    model.setName("TestData");
    model.setDescription(
        "Class used to store all the test data. This should not be used for any development");
    List<ModelField> modelFields = new ArrayList<ModelField>();
    model.setFields(modelFields);
    for (String className : generatedClassNames) {
      ModelField aParam = new ModelField();
      aParam.setName(this.getNameGenerator().applyMethodNamingPolicy(className) + "List");
      aParam.setParamType(this.getDataTypeMappingProvider().getListReturnTypeSignature(className));
      modelFields.add(aParam);
    }

    List<String> imports = new ArrayList<String>();
    imports.addAll(this.config.getDefaultModelImports());
    imports.addAll(this.getDataTypeMappingProvider().getListIncludes());
    for (ModelField param : model.getFields()) {
      for (String importDef :
          param
              .getFieldDefinition(this.getDataTypeMappingProvider(), config, nameGenerator)
              .getImportDefinitions()) {
        if (!imports.contains(importDef)) {
          imports.add(importDef);
        }
      }
    }
    StringTemplate template = templateGroup.getInstanceOf(MODEL_OBJECT_TEMPLATE);
    template.setAttribute("fields", model.getFields());
    template.setAttribute("imports", imports);
    template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
    template.setAttribute("extends", config.getDefaultModelBaseClass());
    template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
    template.setAttribute("className", model.getGenratedClassName());
    File aFile =
        new File(
            languageConfig.getModelClassLocation()
                + model.getGenratedClassName()
                + languageConfig.getClassFileExtension());
    writeFile(aFile, template.toString(), "Wrapper class for test data file");
  }
  /** Generates model classes. If the class is already generated then ignores the same. */
  private void generateModelClasses(List<Resource> resources, StringTemplateGroup templateGroup) {
    List<String> generatedClassNames = new ArrayList();

    for (Resource resource : resources) {
      for (Model model : resource.getModels()) {
        if (!generatedClassNames.contains(model.getName())
            && !this.getCodeGenRulesProvider().isModelIgnored(model.getName())) {
          List<String> imports = new ArrayList<String>();
          imports.addAll(this.config.getDefaultModelImports());
          for (ModelField param : model.getFields()) {
            for (String importDef :
                param
                    .getFieldDefinition(this.getDataTypeMappingProvider(), config, nameGenerator)
                    .getImportDefinitions()) {
              if (!imports.contains(importDef)) {
                imports.add(importDef);
              }
            }
          }
          StringTemplate template = templateGroup.getInstanceOf(MODEL_OBJECT_TEMPLATE);
          template.setAttribute("model", model);
          template.setAttribute("fields", model.getFields());
          template.setAttribute("imports", imports);
          template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
          template.setAttribute("extends", config.getDefaultModelBaseClass());
          template.setAttribute("className", model.getGenratedClassName());
          template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
          File aFile =
              new File(
                  languageConfig.getModelClassLocation()
                      + model.getGenratedClassName()
                      + languageConfig.getClassFileExtension());
          writeFile(aFile, template.toString(), "Model class");
          generatedClassNames.add(model.getName());
        }
      }
    }

    generateWrapperClassForTestData(generatedClassNames, templateGroup);
  }
Example #8
0
  private void grabAnnotations(
      TreeLogger logger,
      ModelMagic models,
      HasModelFields fields,
      JMethod method,
      Annotation[] annos,
      JClassType type) {

    GetterFor getter = method.getAnnotation(GetterFor.class);
    ClientToServer c2s = method.getAnnotation(ClientToServer.class);
    ServerToClient s2c = method.getAnnotation(ServerToClient.class);
    Persistent persist = method.getAnnotation(Persistent.class);
    Serializable serial = method.getAnnotation(Serializable.class);
    Named name = method.getAnnotation(Named.class);

    for (Annotation annotation : annos) {
      if (getter == null && annotation.annotationType() == GetterFor.class)
        getter = (GetterFor) annotation;
      else if (serial == null && annotation.annotationType() == Serializable.class)
        serial = (Serializable) annotation;
      else if (persist == null && annotation.annotationType() == Persistent.class)
        persist = (Persistent) annotation;
      else if (c2s == null && annotation.annotationType() == ClientToServer.class)
        c2s = (ClientToServer) annotation;
      else if (s2c == null && annotation.annotationType() == ServerToClient.class)
        s2c = (ServerToClient) annotation;
      else if (name == null && annotation.annotationType() == Named.class)
        name = (Named) annotation;
    }

    String fieldName;
    if (name == null) {
      fieldName = ModelGeneratorGwt.fieldName(method, models);
    } else {
      fieldName = name.value();
      if (X_Runtime.isDebug()) {
        logger.log(
            Type.TRACE,
            "Named method "
                + method.getJsniSignature()
                + " "
                + fieldName
                + ", from @Named attribute.  Heuristic name: "
                + ModelGeneratorGwt.fieldName(method, models));
      }
    }
    if ("".equals(fieldName)) fieldName = method.getName();
    ModelField field = fields.getOrMakeField(fieldName);

    if (field.getPersistent() == null) {
      field.setPersistent(persist);
    } else {
      assert persist == null || (persist.patchable() == field.getPersistent().patchable())
          : "Model annotation mismatch! Field "
              + field.getName()
              + " of type "
              + type.getQualifiedSourceName()
              + " contained multiple @Persistent annotations which did not match.  "
              + "You may have to override an annotated supertype method with the correct "
              + "@Persistent annotation.";
    }

    if (field.getSerializable() == null) {
      field.setSerializable(serial);
    } else {
      //      assert serial == null ||
      //        ( // this block is all assert, so it will compile out of production.
      //          serial.clientToServer() == field.getSerializable().clientToServer() &&
      //          serial.serverToClient() == field.getSerializable().serverToClient() &&
      //          serial.obfuscated() == field.getSerializable().obfuscated()
      //          ) : "Model annotation mismatch! Field "+field.getName()+" contained " +
      //          		"multiple @Serializable annotations which did not match.  You may " +
      //          		"have to override an annotated supertype method with the correct " +
      //          		"@Serializable annotation.";
    }
    if (field.getServerToClient() == null) {
      field.setServerToClient(s2c);
    } else {
      assert s2c == null || s2c.enabled() == field.getServerToClient().enabled()
          : "Model annotation mismatch! Field "
              + field.getName()
              + " was marked as "
              + "both "
              + "serverToClient"
              + " enabled and disabled.  Please correct this ambiguity;"
              + " your model is now undeterministic and may break unexpectedly.";
    }
    if (field.getClientToServer() == null) {
      field.setClientToServer(c2s);
    } else {
      assert c2s == null || c2s.enabled() == field.getClientToServer().enabled()
          : "Model annotation mismatch! Field "
              + field.getName()
              + " was marked as "
              + "both "
              + "clientToServer"
              + " enabled and disabled.  Please correct this ambiguity;"
              + " your model is now undeterministic and may break unexpectedly.";
    }
  }
Example #9
0
  public void build(
      TreeLogger logger, SourceBuilder<ModelMagic> builder, GeneratorContext ctx, JClassType type)
      throws UnableToCompleteException {

    ModelMagic models = builder.getPayload();
    ModelGenerator generator = new ModelGenerator(builder);
    // Step one; determine if we already have a concrete type or not.
    // TODO if JClassType is final, we need to wrap it using a delegate model.
    JClassType concrete;
    //    ClassBuffer cb = builder.getClassBuffer();
    JClassType root = models.getRootType(logger, ctx);
    if (type.isInterface() == null && type != root) {
      concrete = type;
      generator.setSuperClass(type.getQualifiedSourceName());
    } else {
      // We have an interface on our hands; search for an existing or
      // buildable model.
      // search for a supertype to inherit. Anything that extends Model,
      // does not implement any method we do implement, preferred type
      // being the one that implements the most interfaces possible
      final JClassType model;
      try {
        model = ctx.getTypeOracle().getType(Model.class.getName());
      } catch (NotFoundException e) {
        logger.log(
            Type.ERROR,
            "Cannot load "
                + Model.class.getName()
                + "; "
                + "make sure you have xapi-gwt-model:sources.jar on classpath.");
        throw new UnableToCompleteException();
      }
      concrete = model;
      for (JClassType supertype : concrete.getFlattenedSupertypeHierarchy()) {
        // Only interfaces explicitly extending Model become concrete.
        if (ModelGeneratorGwt.canBeSupertype(type, supertype)) {
          // prefer the concrete type with the most methods in common.
          concrete = supertype;
        }
      }
      if (concrete == null || concrete == model) {
        concrete = models.getRootType(logger, ctx);
        generator.setSuperClass(concrete.getQualifiedSourceName());
      } else {
        // We have to make sure this concrete supertype is created.
        if (!models.hasModel(concrete.getQualifiedSourceName())) {
          // Concrete type is not cached.  Build it now.
          RebindResult result =
              ModelGeneratorGwt.execImpl(logger, ctx, concrete.getQualifiedSourceName());
          generator.setSuperClass(result.getResultTypeName());
        }
      }
    }

    // This will probably become jsni, if we can avoid jso interface sickness...
    generator.createFactory(type.getQualifiedSourceName());

    HasModelFields fieldMap = new HasModelFields();
    fieldMap.setDefaultSerializable(type.getAnnotation(Serializable.class));

    for (JMethod method : methods.keySet()) {
      if (!toGenerate.contains(ModelGeneratorGwt.toSignature(method))) {
        logger.log(
            Type.TRACE, "Skipping method defined in supertype: " + method.getJsniSignature());
        continue;
      }

      Annotation[] annos = methods.get(method);
      String methodName = method.getName();
      String returnType = method.getReturnType().getQualifiedSourceName();
      String params = ModelGeneratorGwt.typeToParameterString(method.getParameterTypes());

      // TODO: check imports if we are safe to use simple name.
      returnType = method.getReturnType().getSimpleSourceName();
      IsType returns = X_Source.binaryToSource(method.getReturnType().getQualifiedBinaryName());
      IsType[] parameters = ModelGeneratorGwt.toTypes(method.getParameterTypes());

      GetterFor getter = method.getAnnotation(GetterFor.class);
      if (getter != null) {
        String name = getter.value();
        if (name.length() == 0) {
          name = ModelUtil.stripGetter(method.getName());
        }
        ModelField field = fieldMap.getOrMakeField(name);
        field.setType(returnType);
        assert parameters.length == 0
            : "A getter method cannot have parameters. "
                + "Generated code requires using getter methods without args.  You provided "
                + method.getJsniSignature();
        grabAnnotations(logger, models, fieldMap, method, annos, type);
        field.addGetter(returns, methodName);
        continue;
      }
      SetterFor setter = method.getAnnotation(SetterFor.class);
      if (setter != null) {
        String name = setter.value();
        if (name.length() == 0) name = ModelUtil.stripSetter(method.getName());
        grabAnnotations(logger, models, fieldMap, method, annos, type);
        continue;
      }

      if (method.getAnnotation(DeleterFor.class) != null) {
        implementAction(logger, generator, method, models, annos);
        continue;
      }

      // No annotation.  We have to guess the type.

      boolean isVoid = method.getReturnType().isPrimitive() == JPrimitiveType.VOID;
      boolean isGetter =
          methodName.startsWith("get")
              || methodName.startsWith("is")
              || methodName.startsWith("has");
      boolean isSetter, isAction;
      if (isGetter) {
        assert !isVoid
            : "Cannot have a void return type with method name "
                + methodName
                + "; getter prefixes get(), is() and has() must return a type.";
        isSetter = false;
        isAction = false;
      } else {
        isSetter =
            methodName.startsWith("set")
                || methodName.startsWith("add")
                || methodName.startsWith("put")
                || methodName.startsWith("rem")
                || methodName.startsWith("remove");
        if (isSetter) {
          isAction = false;
        } else {
          isAction = true;
        }
      }

      if (isVoid) {
        // definitely a setter / action method.
        if (isSetter) {
          MethodBuffer mb = generator.createMethod(returnType, methodName, params);
          implementSetter(logger, mb, method, models, fieldMap, annos);
        } else if (isAction) {
          implementAction(logger, generator, method, models, annos);
        } else {
          MethodBuffer mb = generator.createMethod(returnType, methodName, params);
          implementException(logger, mb, method);
        }
      } else {
        if (isGetter) {
          String name = ModelUtil.stripGetter(method.getName());
          ModelField field = fieldMap.getOrMakeField(name);
          field.setType(returnType);
          field.addGetter(returns, methodName);
          grabAnnotations(logger, models, fieldMap, method, annos, type);
        } else if (isSetter) {
          MethodBuffer mb = generator.createMethod(returnType, methodName, params);
          implementSetter(logger, mb, method, models, fieldMap, annos);
        } else if (isAction) {
          implementAction(logger, generator, method, models, annos);
        } else {
          MethodBuffer mb = generator.createMethod(returnType, methodName, params);
          implementException(logger, mb, method);
        }
      }
    }
    generator.generateModel(
        X_Source.toType(builder.getPackage(), builder.getClassBuffer().getSimpleName()), fieldMap);
  }
Example #10
0
  public static String genUpdateSQL(SqlModel model) {
    StringBuffer sber = new StringBuffer();
    String result = null;
    String[] columnNames = model.getColumnNames();

    // 获取主键对象模型
    ModelField primaryField = model.getModelField(model.getPrimaryFieldName());
    // 主键列名称
    String primaryColumnName = primaryField.getColumnName();
    if (null != model) {
      sber.append("UPDATE ");
      sber.append(model.getTableName());
      sber.append(" SET ");
      ModelField field = null;
      for (String fieldName : columnNames) {
        if ("id".equalsIgnoreCase(fieldName)) {
          continue;
        }
        if (primaryColumnName.equalsIgnoreCase(fieldName)) {
          continue;
        }
        field = model.getModelField(fieldName);
        if (null == field) {
          throw new NullPointerException("得到的字段为空! ");
        }

        if (0 == field.getFieldType()
            && StringUtils.isNotEmpty(field.getFieldValue())
            && !"null".equalsIgnoreCase(field.getFieldValue())) {
          sber.append(field.getColumnName());
          sber.append("=");
          sber.append("'");
          sber.append(field.getFieldValue());
          sber.append("'");
          sber.append(",");
        } else if (1 == field.getFieldType()
            && StringUtils.isNotEmpty(field.getFieldValue())
            && !"null".equalsIgnoreCase(field.getFieldValue())) {
          sber.append(field.getColumnName());
          sber.append("=");
          sber.append(field.getFieldValue());
          sber.append(",");
        } else {
        }
      }
      if (null != sber && sber.length() > 0 && sber.toString().endsWith(",")) {
        sber = sber.delete(sber.length() - 1, sber.length());
      }

      sber.append(" WHERE ");
      sber.append(primaryColumnName);
      sber.append("=");

      if ((null == primaryField || StringUtils.isEmpty(primaryField.getFieldValue()))
          && (null == model.getPrimaryFieldValue() || "".equals(model.getPrimaryFieldValue()))) {
        throw new NullPointerException("ID字段值为空!");
      }
      if (0 == primaryField.getFieldType()) {
        sber.append("'");
        sber.append(
            primaryField.getFieldValue() == null
                ? model.getPrimaryFieldValue()
                : primaryField.getFieldValue());
        sber.append("'");
      } else if (1 == primaryField.getFieldType()) {
        sber.append(
            primaryField.getFieldValue() == null
                ? model.getPrimaryFieldValue()
                : primaryField.getFieldValue());
      }
    }
    result = sber.toString();
    LOGGER.info("生成的SQL语句为:" + result);
    return result;
  }
  private void generateOutputWrappers(List<Resource> resources, StringTemplateGroup templateGroup) {
    List<String> generatedClasses = new ArrayList<String>();
    StringTemplate template = templateGroup.getInstanceOf(WRAPPER_OBJECT_TEMPLATE);
    if (template == null) {
      System.out.println("WrapperObject template not found to generate output wrappers");
      return;
    }

    for (Resource resource : resources) {
      if (resource.getEndPoints() != null) {
        for (Endpoint endpoint : resource.getEndPoints()) {
          if (endpoint.getOperations() != null) {
            for (EndpointOperation operation : endpoint.getOperations()) {
              ResourceMethod method =
                  operation.generateMethod(
                      endpoint, resource, dataTypeMappingProvider, nameGenerator);
              if (codeGenRulesProvider.isModelIgnored(
                  nameGenerator.applyMethodNamingPolicy(method.getReturnClassName()))) {
                continue;
              }
              if (method.getListWrapperModel() != null) {
                Model model = method.getListWrapperModel();
                method.setReturnClassName(model.getName());
                if (model != null) {
                  if (!generatedClasses.contains(model.getName())) {
                    List<String> imports = new ArrayList<String>();
                    imports.addAll(this.config.getDefaultModelImports());
                    for (ModelField param : model.getFields()) {
                      for (String importDef :
                          param
                              .getFieldDefinition(
                                  this.getDataTypeMappingProvider(), config, nameGenerator)
                              .getImportDefinitions()) {
                        if (!imports.contains(importDef)) {
                          imports.add(importDef);
                        }
                      }
                    }
                    template = templateGroup.getInstanceOf(WRAPPER_OBJECT_TEMPLATE);

                    template.setAttribute("fields", model.getFields());
                    template.setAttribute("imports", imports);
                    template.setAttribute("extends", config.getDefaultModelBaseClass());
                    template.setAttribute(
                        "annotationPackageName", languageConfig.getAnnotationPackageName());
                    template.setAttribute("className", model.getGenratedClassName());
                    template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
                    File aFile =
                        new File(
                            languageConfig.getModelClassLocation()
                                + model.getGenratedClassName()
                                + languageConfig.getClassFileExtension());
                    writeFile(aFile, template.toString(), "List wrapper model class");
                    generatedClasses.add(model.getName());
                  }
                }
              }
            }
          }
        }
      }
    }
  }
 /**
  * Generates an Enum class for method params that have an allowed values list.
  *
  * @param resources
  * @param templateGroup
  */
 private void generateEnumForAllowedValues(
     List<Resource> resources, StringTemplateGroup templateGroup) {
   List<String> generatedEnums = new ArrayList<String>();
   StringTemplate template;
   String valuePrefix, valueSuffix = "";
   String enumName;
   for (Resource resource : resources) {
     if (resource.getEndPoints() != null) {
       for (Endpoint endpoint : resource.getEndPoints()) {
         if (endpoint.getOperations() != null) {
           for (EndpointOperation operation : endpoint.getOperations()) {
             // ResourceMethod method = operation.generateMethod(endpoint, resource, config);
             if (operation.getParameters() != null) {
               for (ModelField operationParam : operation.getParameters()) {
                 // skipping the case where there is just one item - TODO process case of
                 // allowableValue like '0 to 1000'
                 if (operationParam.getAllowableValues() != null
                     && operationParam
                         .getAllowableValues()
                         .getClass()
                         .isAssignableFrom(AllowableListValues.class)) {
                   if (!generatedEnums.contains(operationParam.getName())) {
                     // generate enum
                     template = templateGroup.getInstanceOf(ENUM_OBJECT_TEMPLATE);
                     List<String> imports = new ArrayList<String>();
                     imports.addAll(this.config.getDefaultModelImports());
                     enumName = this.getNameGenerator().getEnumName(operationParam.getName());
                     template.setAttribute("className", enumName);
                     template.setAttribute("description", operationParam.getDescription());
                     template.setAttribute(
                         "enumValueType",
                         this.getDataTypeMappingProvider()
                             .getClassType(operationParam.getDataType(), true));
                     for (String allowableValue :
                         ((AllowableListValues) operationParam.getAllowableValues()).getValues()) {
                       if (operationParam.getDataType().equalsIgnoreCase("string")) {
                         valuePrefix = valueSuffix = "\"";
                       } else {
                         valuePrefix = valueSuffix = "";
                       }
                       ;
                       String namePrefix = "";
                       if (isNameStartsWithInteger(allowableValue)
                           && !canEnumNameStartsWithNumber()) {
                         namePrefix = "ENUM_";
                       }
                       template.setAttribute(
                           "values.{name,value}",
                           namePrefix
                               + this.getNameGenerator()
                                   .applyClassNamingPolicy(allowableValue.replaceAll("-", "_")),
                           this.getNameGenerator()
                               .applyMethodNamingPolicy(
                                   valuePrefix.concat(allowableValue).concat(valueSuffix)));
                     }
                     template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
                     File aFile =
                         new File(
                             languageConfig.getModelClassLocation()
                                 + enumName
                                 + languageConfig.getClassFileExtension());
                     writeFile(aFile, template.toString(), "Enum class");
                     generatedEnums.add(operationParam.getName());
                   }
                 }
               }
             }
           }
         }
       }
     }
   }
 }
  public ResourceMethod generateMethod(
      Endpoint endPoint,
      Resource resource,
      DataTypeMappingProvider dataTypeMapper,
      NamingPolicyProvider nameGenerator) {
    if (method == null) {
      method = new ResourceMethod();
      // add method description
      method.setTitle(this.getSummary());
      method.setDescription(this.getNotes());

      // add method name
      // get resource path for making web service call
      /**
       * Logic for method names 1. remove all path parameters 2. Remove format path parameter 3. For
       * POST add save 4. For PUT add update 5. For DELETE add delete 6. For GET add get 7.
       * Concatenate rest of the path with init caps 8.
       */
      String inputobjectName =
          nameGenerator.getInputObjectName(
              resource.generateClassName(nameGenerator), endPoint.getPath());

      String[] pathElements = endPoint.getPath().split("/");
      StringBuilder urlPath = new StringBuilder("");
      if (pathElements != null) {
        for (int i = 0; i < pathElements.length; i++) {
          String pathElement = pathElements[i];
          if (pathElement != null && pathElement.length() > 0) {
            int position = pathElement.indexOf("{");
            if (urlPath.length() > 0) {
              urlPath.append("+");
            }
            if (position < 0) {
              urlPath.append("\"/" + pathElement + "\"");
            } else if (position == 0) {
              urlPath.append("\"/\"+" + pathElement.substring(1, pathElement.length() - 1));
            } else {
              urlPath.append("\"/" + pathElement.replace("{format}", "json") + "\"");
            }
          }
        }
      }
      method.setResourcePath(endPoint.getPath());
      method.setName(nameGenerator.getMethodName(endPoint.getPath(), this.getNickname()));

      // create method argument
      /**
       * 1. API token need not be included as that is always added to the calls as HTTP headers 2.
       * We need to handle auth token specially, hence need to differentiate that 3. Query
       * parameters needs to be added as query string hence need to separate them out 4. Post
       * parameters are usually WordnikObjects, hence we need to handle them separately
       */
      List<String> argNames = new ArrayList<String>();
      if (this.getParameters() != null) {
        List<MethodArgument> arguments = new ArrayList<MethodArgument>();
        List<MethodArgument> queryParams = new ArrayList<MethodArgument>();
        List<MethodArgument> pathParams = new ArrayList<MethodArgument>();
        List<MethodArgument> headerParams = new ArrayList<MethodArgument>();

        method.setArguments(arguments);
        method.setQueryParameters(queryParams);
        method.setPathParameters(pathParams);
        method.setHeaderParameters(headerParams);

        for (ModelField modelField : this.getParameters()) {
          if (!argNames.contains(modelField.getName())) {
            argNames.add(modelField.getName());
            MethodArgument anArgument = new MethodArgument();
            anArgument.setAllowedValues(modelField.getAllowedValuesString());
            // check if arguments has auth token
            if (modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_HEADER)
                && modelField.getName().equals(AUTH_TOKEN_PARAM_NAME)) {
              method.setAuthToken(true);
              anArgument.setName(AUTH_TOKEN_ARGUMENT_NAME);
              anArgument.setDataType(
                  dataTypeMapper.getClassType(MethodArgument.ARGUMENT_STRING, true));
              anArgument.setDescription(modelField.getDescription());
              anArgument.setRequired(modelField.isRequired());
              anArgument.setDefaultValue(modelField.getDefaultValue());
              arguments.add(anArgument);
              headerParams.add(anArgument);
            } else if (modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_HEADER)
                && modelField.getName().equals(API_KEY_PARAM_NAME)) {
              anArgument.setName(API_KEY_PARAM_NAME);
              anArgument.setDataType(
                  dataTypeMapper.getClassType(MethodArgument.ARGUMENT_STRING, true));
              anArgument.setRequired(true);
              arguments.add(anArgument);
              headerParams.add(anArgument);
            } else if (modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_PATH)
                && !modelField.getName().equalsIgnoreCase(FORMAT_PARAM_NAME)) {
              anArgument.setName(modelField.getName());
              anArgument.setDataType(
                  dataTypeMapper.getClassType(MethodArgument.ARGUMENT_STRING, true));
              anArgument.setDescription(modelField.getDescription());
              anArgument.setRequired(true); // 	always true
              anArgument.setDefaultValue(modelField.getDefaultValue());
              arguments.add(anArgument);
              pathParams.add(anArgument);
            } else if (modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_QUERY)) {
              anArgument.setName(modelField.getName());
              anArgument.setDataType(
                  dataTypeMapper.getClassType(MethodArgument.ARGUMENT_STRING, true));
              anArgument.setDescription(modelField.getDescription());
              anArgument.setRequired(modelField.isRequired());
              anArgument.setDefaultValue(modelField.getDefaultValue());
              queryParams.add(anArgument);
              arguments.add(anArgument);
            } else if (modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_BODY)) {
              if (modelField.getName() == null) {
                modelField.setName(POST_PARAM_NAME);
              }
              anArgument.setName(modelField.getName());
              anArgument.setDataType(dataTypeMapper.getClassType(modelField.getDataType(), false));
              anArgument.setDescription(modelField.getDescription());
              anArgument.setRequired(modelField.isRequired());
              anArgument.setDefaultValue(modelField.getDefaultValue());
              arguments.add(anArgument);
              method.setPostObject(true);
            }

            if (modelField.isAllowMultiple()
                && dataTypeMapper.isPrimitiveType(modelField.getDataType())) {
              anArgument.setDataType(
                  dataTypeMapper.getListReturnTypeSignature(
                      dataTypeMapper.getClassType(modelField.getDataType(), false)));
            }
            anArgument.setInputModelClassArgument(inputobjectName, nameGenerator);
          }
        }
      }

      // check if input model with the given name is already generated for some other path
      boolean inputModelAlreadyGenerated = false;
      if (alreadyGeneratedModels.containsKey(inputobjectName)) {
        if (!alreadyGeneratedModels.get(inputobjectName).equals(endPoint.getPath())) {
          inputModelAlreadyGenerated = true;
        }
      }

      // check for number of arguments, if we have more than 4 then send the arguments as input
      // object
      if (method.getArguments() != null
          && method.getArguments().size() > ARG_COUNT_FOR_INPUT_MODEL
          && !inputModelAlreadyGenerated) {
        List<MethodArgument> arguments = new ArrayList<MethodArgument>();
        Model modelforMethodInput = new Model();
        modelforMethodInput.setName(inputobjectName);
        List<ModelField> fields = new ArrayList<ModelField>();
        for (MethodArgument argument : method.getArguments()) {
          if (!argument.getName().equals(POST_PARAM_NAME)) {
            ModelField aModelField = new ModelField();
            aModelField.setAllowedValues(argument.getAllowedValues());
            aModelField.setDescription(argument.getDescription());
            aModelField.setName(argument.getName());
            aModelField.setParamType(argument.getDataType());
            fields.add(aModelField);
          } else {
            arguments.add(argument);
          }
        }
        modelforMethodInput.setFields(fields);

        MethodArgument anArgument = new MethodArgument();
        anArgument.setDataType(inputobjectName);
        anArgument.setName(nameGenerator.applyMethodNamingPolicy(inputobjectName));
        arguments.add(anArgument);
        method.setArguments(arguments);
        method.setInputModel(modelforMethodInput);
        alreadyGeneratedModels.put(inputobjectName, endPoint.getPath());
      }

      List<String> argumentDefinitions = new ArrayList<String>();
      List<String> argumentNames = new ArrayList<String>();
      if (method.getArguments() != null && method.getArguments().size() > 0) {
        for (MethodArgument arg : method.getArguments()) {
          if (!arg.getName().equalsIgnoreCase(FORMAT_PARAM_NAME)) {
            argumentDefinitions.add(
                dataTypeMapper.getArgumentDefinition(arg.getDataType(), arg.getName()));
            argumentNames.add(arg.getName());
          }
        }
        method.setArgumentDefinitions(argumentDefinitions);
        method.setArgumentNames(argumentNames);
      }

      // get method type
      method.setMethodType(this.getHttpMethod());

      // get return value
      String returnType = dataTypeMapper.getClassType(responseClass, false);
      if ("".equals(returnType)) {
        method.setHasResponseValue(false);
      } else {
        method.setHasResponseValue(true);
      }
      // set the original response name, this is used in identifying if the respone is single valued
      // or multi valued
      method.setReturnValueFromOperationJson(responseClass);
      method.setReturnValue(dataTypeMapper.getClassType(responseClass, false));
      method.setReturnClassName(dataTypeMapper.getGenericType(responseClass));

      // if this is a list return type
      if (method
          .getReturnClassName()
          .equals(dataTypeMapper.getListReturnTypeSignature(responseClass))) {
        String returnValueTypeName = method.getReturnValue();
        Model listWrapperModel = new Model();
        listWrapperModel.setName(nameGenerator.getListWrapperName(returnValueTypeName));
        List<ModelField> fields = new ArrayList<ModelField>();
        ModelField aModelField = new ModelField();
        aModelField.setName(nameGenerator.applyMethodNamingPolicy(returnValueTypeName));
        aModelField.setParamType(responseClass);
        fields.add(aModelField);
        listWrapperModel.setFields(fields);
        method.setListWrapperModel(listWrapperModel);
      }

      // get description string for exception
      method.setExceptionDescription(calculateExceptionMessage());
    }
    return method;
  }