@Override
 public String getDocumentationUrl(Method method, Object content) {
   final Expose expose = AnnotationUtils.getAnnotation(method, Expose.class);
   // TODO can we support Mixins from here?
   //        final Class<?> mixin = provider.getConfig()
   //                .findMixInClassFor(bean.getClass());
   //        final Expose mixinExpose = getAnnotation(mixin, Expose.class);
   String methodName = method.getName();
   String propertyName;
   if (methodName.startsWith("get")) {
     propertyName = StringUtils.uncapitalize(StringUtils.removeStart(methodName, "get"));
   } else {
     propertyName = StringUtils.uncapitalize(StringUtils.removeStart(methodName, "is"));
   }
   return getExposedUrl(propertyName, vocabFromBean(content), termsFromBean(content), expose);
 }
  private MethodMetadata getCountByParentMethod() {
    if (parentProperty == null) {
      return null;
    }

    JavaSymbolName methodName = new JavaSymbolName("count" + plural + "ByParentId");

    final JavaType idType =
        KEY.equals(identifierField.getFieldType()) ? STRING : identifierField.getFieldType();
    final JavaType[] parameterTypes = {idType};

    final MethodMetadata method = getGovernorMethod(methodName, parameterTypes);
    if (method != null) {
      return method;
    }

    final String idParamName =
        StringUtils.uncapitalize(parentProperty.getFieldType().getSimpleTypeName()) + "Id";
    final List<JavaSymbolName> parameterNames = Arrays.asList(new JavaSymbolName(idParamName));

    MethodMetadataBuilder methodBuilder =
        new MethodMetadataBuilder(
            getId(),
            PUBLIC_ABSTRACT,
            methodName,
            LONG_PRIMITIVE,
            AnnotatedJavaType.convertFromJavaTypes(parameterTypes),
            parameterNames,
            BODY);

    return methodBuilder.build();
  }
  @Override
  public void systemService(
      final JavaType type,
      JavaSymbolName fieldName,
      final SystemService service,
      final boolean addPermissions) {

    final ClassOrInterfaceTypeDetails typeDetails = typeLocationService.getTypeDetails(type);
    Validate.notNull(typeDetails, "The type specified, '" + type + "' doesn't exist");

    if (fieldName == null) {
      fieldName =
          new JavaSymbolName(
              StringUtils.uncapitalize(service.getServiceType().getSimpleTypeName()));
    }

    final String physicalTypeIdentifier = typeDetails.getDeclaredByMetadataId();

    final List<AnnotationMetadataBuilder> annotations =
        Arrays.asList(new AnnotationMetadataBuilder(ROO_SYSTEM_SERVICE));

    final FieldMetadataBuilder fieldBuilder =
        new FieldMetadataBuilder(
            physicalTypeIdentifier, 0, annotations, fieldName, service.getServiceType());
    typeManagementService.addField(fieldBuilder.build());

    if (addPermissions) {
      final String moduleName = projectOperations.getFocusedModuleName();
      for (Permission permission : service.getPermissions()) {
        androidTypeService.addPermission(moduleName, permission.permissionName());
      }
    }
  }
Example #4
0
 /**
  * Remove the getter prefix ('is', 'get') from the the method name passed in.
  *
  * @param name the method name.
  * @return the method name without the prefix, may be <code>null</code> or empty if the name
  *     passed in was that way.
  */
 public static String stripGetterPrefix(String name) {
   if (StringUtils.isBlank(name)) {
     return name; // This should never happen.
   }
   String[] mName = StringUtils.splitByCharacterTypeCamelCase(name);
   StringBuilder sb = new StringBuilder();
   for (int i = 1; i < mName.length; i++) {
     sb.append(mName[i]);
   }
   return StringUtils.uncapitalize(sb.toString());
 }
 protected HashFunctionUtilsTestSupport(
     @Nonnull Class<?> utilsType, @Nonnull Class<? extends HashFunction> hashFunctionType) {
   _utilsType = utilsType;
   try {
     _constructor = hashFunctionType.getConstructor();
   } catch (final NoSuchMethodException e) {
     throw new RuntimeException(
         "Could not find required constructor of " + hashFunctionType.getName() + ".", e);
   }
   final String simpleName = _utilsType.getSimpleName();
   final String simpleNameWithoutUtilsInIt = simpleName.replace("Utils", "");
   _methodName = StringUtils.uncapitalize(simpleNameWithoutUtilsInIt) + "Of";
 }
Example #6
0
 /**
  * 把骆驼命名法的变量,变为大写字母变小写且之前加下划线
  *
  * @param str
  * @return
  */
 public static String toUnderline(String str) {
   str = StringUtils.uncapitalize(str);
   char[] letters = str.toCharArray();
   StringBuilder sb = new StringBuilder();
   for (char letter : letters) {
     if (Character.isUpperCase(letter)) {
       sb.append("_" + letter + "");
     } else {
       sb.append(letter + "");
     }
   }
   return StringUtils.lowerCase(sb.toString());
 }
  private Optional<String> getCompatibleStepNameFrom(Method testMethod) {
    Annotation[] annotations = testMethod.getAnnotations();
    for (Annotation annotation : annotations) {
      if (isACompatibleStep(annotation)) {
        try {
          String annotationType = annotation.annotationType().getSimpleName();
          String annotatedValue =
              (String) annotation.getClass().getMethod("value").invoke(annotation);
          if (StringUtils.isEmpty(annotatedValue)) {
            return Optional.absent();
          } else {
            return Optional.of(annotationType + " " + StringUtils.uncapitalize(annotatedValue));
          }

        } catch (Exception ignoredException) {
        }
      }
    }
    return Optional.absent();
  }
 /**
  * Attempts to locate the field which is represented by the presented property name.
  *
  * <p>Not every JavaBean getter or setter actually backs to a field with an identical name. In
  * such cases, null will be returned.
  *
  * @param memberDetails the member holders to scan (required)
  * @param propertyName the property name (required)
  * @return the field if found, or null if it could not be found
  */
 public static FieldMetadata getFieldForPropertyName(
     final MemberDetails memberDetails, final JavaSymbolName propertyName) {
   Validate.notNull(memberDetails, "Member details required");
   Validate.notNull(propertyName, "Property name required");
   for (final MemberHoldingTypeDetails holder : memberDetails.getDetails()) {
     FieldMetadata result = holder.getDeclaredField(propertyName);
     if (result != null) {
       return result;
     }
     // To get here means we couldn't find the property using the exact
     // same case;
     // try to scan with a lowercase first character (see ROO-203)
     result =
         holder.getDeclaredField(
             new JavaSymbolName(StringUtils.uncapitalize(propertyName.getSymbolName())));
     if (result != null) {
       return result;
     }
   }
   return null;
 }
  private MethodMetadata getFindEntriesByParentMethod() {
    if (parentProperty == null) {
      return null;
    }

    JavaSymbolName methodName =
        new JavaSymbolName("find" + domainType.getSimpleTypeName() + "EntriesByParentId");

    final JavaType idType =
        KEY.equals(identifierField.getFieldType()) ? STRING : identifierField.getFieldType();
    final JavaType[] parameterTypes = {idType, INT_PRIMITIVE, INT_PRIMITIVE};

    final MethodMetadata method = getGovernorMethod(methodName, parameterTypes);
    if (method != null) {
      return method;
    }

    final String idParamName =
        StringUtils.uncapitalize(parentProperty.getFieldType().getSimpleTypeName()) + "Id";
    final List<JavaSymbolName> parameterNames =
        Arrays.asList(
            new JavaSymbolName(idParamName),
            new JavaSymbolName("firstResult"),
            new JavaSymbolName("maxResults"));
    final JavaType returnType =
        new JavaType(
            LIST.getFullyQualifiedTypeName(), 0, DataType.TYPE, null, Arrays.asList(domainType));

    final MethodMetadataBuilder methodBuilder =
        new MethodMetadataBuilder(
            getId(),
            PUBLIC_ABSTRACT,
            methodName,
            returnType,
            AnnotatedJavaType.convertFromJavaTypes(parameterTypes),
            parameterNames,
            BODY);

    return methodBuilder.build();
  }
 /**
  * 注解到对象复制,只复制能匹配上的方法。
  *
  * @param annotation
  * @param object
  */
 public static void annotationToObject(Object annotation, Object object) {
   if (annotation != null) {
     Class<?> annotationClass = annotation.getClass();
     Class<?> objectClass = object.getClass();
     for (Method m : objectClass.getMethods()) {
       if (StringUtils.startsWith(m.getName(), "set")) {
         try {
           String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3));
           Object obj = annotationClass.getMethod(s).invoke(annotation);
           if (obj != null && !"".equals(obj.toString())) {
             if (object == null) {
               object = objectClass.newInstance();
             }
             m.invoke(object, obj);
           }
         } catch (Exception e) {
           // 忽略所有设置失败方法
         }
       }
     }
   }
 }
  private TemplateDataDictionary buildMirrorDataDictionary(
      final GwtType type,
      final ClassOrInterfaceTypeDetails mirroredType,
      final ClassOrInterfaceTypeDetails proxy,
      final Map<GwtType, JavaType> mirrorTypeMap,
      final Map<JavaSymbolName, GwtProxyProperty> clientSideTypeMap,
      final String moduleName) {
    final JavaType proxyType = proxy.getName();
    final JavaType javaType = mirrorTypeMap.get(type);

    final TemplateDataDictionary dataDictionary = TemplateDictionary.create();

    // Get my locator and
    final JavaType entity = mirroredType.getName();
    final String entityName = entity.getFullyQualifiedTypeName();
    final String metadataIdentificationString = mirroredType.getDeclaredByMetadataId();
    final JavaType idType = persistenceMemberLocator.getIdentifierType(entity);
    Validate.notNull(idType, "Identifier type is not available for entity '" + entityName + "'");

    final MethodParameter entityParameter = new MethodParameter(entity, "proxy");
    final ClassOrInterfaceTypeDetails request = gwtTypeService.lookupRequestFromProxy(proxy);

    final MemberTypeAdditions persistMethodAdditions =
        layerService.getMemberTypeAdditions(
            metadataIdentificationString,
            CustomDataKeys.PERSIST_METHOD.name(),
            entity,
            idType,
            LAYER_POSITION,
            entityParameter);
    Validate.notNull(
        persistMethodAdditions, "Persist method is not available for entity '" + entityName + "'");
    final String persistMethodSignature = getRequestMethodCall(request, persistMethodAdditions);
    dataDictionary.setVariable("persistMethodSignature", persistMethodSignature);

    final MemberTypeAdditions removeMethodAdditions =
        layerService.getMemberTypeAdditions(
            metadataIdentificationString,
            CustomDataKeys.REMOVE_METHOD.name(),
            entity,
            idType,
            LAYER_POSITION,
            entityParameter);
    Validate.notNull(
        removeMethodAdditions, "Remove method is not available for entity '" + entityName + "'");
    final String removeMethodSignature = getRequestMethodCall(request, removeMethodAdditions);
    dataDictionary.setVariable("removeMethodSignature", removeMethodSignature);

    final MemberTypeAdditions countMethodAdditions =
        layerService.getMemberTypeAdditions(
            metadataIdentificationString,
            CustomDataKeys.COUNT_ALL_METHOD.name(),
            entity,
            idType,
            LAYER_POSITION);
    Validate.notNull(
        countMethodAdditions, "Count method is not available for entity '" + entityName + "'");
    dataDictionary.setVariable("countEntitiesMethod", countMethodAdditions.getMethodName());

    for (final GwtType reference : type.getReferences()) {
      addReference(dataDictionary, reference, mirrorTypeMap);
    }

    addImport(dataDictionary, proxyType.getFullyQualifiedTypeName());

    final String pluralMetadataKey =
        PluralMetadata.createIdentifier(
            mirroredType.getName(),
            PhysicalTypeIdentifier.getPath(mirroredType.getDeclaredByMetadataId()));
    final PluralMetadata pluralMetadata = (PluralMetadata) metadataService.get(pluralMetadataKey);
    final String plural = pluralMetadata.getPlural();

    final String simpleTypeName = mirroredType.getName().getSimpleTypeName();
    final JavaPackage topLevelPackage = projectOperations.getTopLevelPackage(moduleName);
    dataDictionary.setVariable("className", javaType.getSimpleTypeName());
    dataDictionary.setVariable("packageName", javaType.getPackage().getFullyQualifiedPackageName());
    dataDictionary.setVariable("placePackage", GwtPath.SCAFFOLD_PLACE.packageName(topLevelPackage));
    dataDictionary.setVariable(
        "scaffoldUiPackage", GwtPath.SCAFFOLD_UI.packageName(topLevelPackage));
    dataDictionary.setVariable(
        "sharedScaffoldPackage", GwtPath.SHARED_SCAFFOLD.packageName(topLevelPackage));
    dataDictionary.setVariable("uiPackage", GwtPath.MANAGED_UI.packageName(topLevelPackage));
    dataDictionary.setVariable("name", simpleTypeName);
    dataDictionary.setVariable("pluralName", plural);
    dataDictionary.setVariable("nameUncapitalized", StringUtils.uncapitalize(simpleTypeName));
    dataDictionary.setVariable("proxy", proxyType.getSimpleTypeName());
    dataDictionary.setVariable("pluralName", plural);
    dataDictionary.setVariable(
        "proxyRenderer", GwtProxyProperty.getProxyRendererType(topLevelPackage, proxyType));

    String proxyFields = null;
    GwtProxyProperty primaryProperty = null;
    GwtProxyProperty secondaryProperty = null;
    GwtProxyProperty dateProperty = null;
    final Set<String> importSet = new HashSet<String>();

    for (final GwtProxyProperty gwtProxyProperty : clientSideTypeMap.values()) {
      // Determine if this is the primary property.
      if (primaryProperty == null) {
        // Choose the first available field.
        primaryProperty = gwtProxyProperty;
      } else if (gwtProxyProperty.isString() && !primaryProperty.isString()) {
        // Favor String properties over other types.
        secondaryProperty = primaryProperty;
        primaryProperty = gwtProxyProperty;
      } else if (secondaryProperty == null) {
        // Choose the next available property.
        secondaryProperty = gwtProxyProperty;
      } else if (gwtProxyProperty.isString() && !secondaryProperty.isString()) {
        // Favor String properties over other types.
        secondaryProperty = gwtProxyProperty;
      }

      // Determine if this is the first date property.
      if (dateProperty == null && gwtProxyProperty.isDate()) {
        dateProperty = gwtProxyProperty;
      }

      if (gwtProxyProperty.isProxy() || gwtProxyProperty.isCollectionOfProxy()) {
        if (proxyFields != null) {
          proxyFields += ", ";
        } else {
          proxyFields = "";
        }
        proxyFields += "\"" + gwtProxyProperty.getName() + "\"";
      }

      dataDictionary.addSection("fields").setVariable("field", gwtProxyProperty.getName());
      if (!isReadOnly(gwtProxyProperty.getName(), mirroredType)) {
        dataDictionary
            .addSection("editViewProps")
            .setVariable("prop", gwtProxyProperty.forEditView());
      }

      final TemplateDataDictionary propertiesSection = dataDictionary.addSection("properties");
      propertiesSection.setVariable("prop", gwtProxyProperty.getName());
      propertiesSection.setVariable(
          "propId", proxyType.getSimpleTypeName() + "_" + gwtProxyProperty.getName());
      propertiesSection.setVariable("propGetter", gwtProxyProperty.getGetter());
      propertiesSection.setVariable("propType", gwtProxyProperty.getType());
      propertiesSection.setVariable("propFormatter", gwtProxyProperty.getFormatter());
      propertiesSection.setVariable("propRenderer", gwtProxyProperty.getRenderer());
      propertiesSection.setVariable("propReadable", gwtProxyProperty.getReadableName());

      if (!isReadOnly(gwtProxyProperty.getName(), mirroredType)) {
        final TemplateDataDictionary editableSection =
            dataDictionary.addSection("editableProperties");
        editableSection.setVariable("prop", gwtProxyProperty.getName());
        editableSection.setVariable(
            "propId", proxyType.getSimpleTypeName() + "_" + gwtProxyProperty.getName());
        editableSection.setVariable("propGetter", gwtProxyProperty.getGetter());
        editableSection.setVariable("propType", gwtProxyProperty.getType());
        editableSection.setVariable("propFormatter", gwtProxyProperty.getFormatter());
        editableSection.setVariable("propRenderer", gwtProxyProperty.getRenderer());
        editableSection.setVariable("propBinder", gwtProxyProperty.getBinder());
        editableSection.setVariable("propReadable", gwtProxyProperty.getReadableName());
      }

      dataDictionary.setVariable("proxyRendererType", proxyType.getSimpleTypeName() + "Renderer");

      if (gwtProxyProperty.isProxy()
          || gwtProxyProperty.isEnum()
          || gwtProxyProperty.isCollectionOfProxy()) {
        final TemplateDataDictionary section =
            dataDictionary.addSection(
                gwtProxyProperty.isEnum() ? "setEnumValuePickers" : "setProxyValuePickers");
        section.setVariable("setValuePicker", gwtProxyProperty.getSetValuePickerMethod());
        section.setVariable("setValuePickerName", gwtProxyProperty.getSetValuePickerMethodName());
        section.setVariable("valueType", gwtProxyProperty.getValueType().getSimpleTypeName());
        section.setVariable("rendererType", gwtProxyProperty.getProxyRendererType());
        if (gwtProxyProperty.isProxy() || gwtProxyProperty.isCollectionOfProxy()) {
          String propTypeName =
              StringUtils.uncapitalize(
                  gwtProxyProperty.isCollectionOfProxy()
                      ? gwtProxyProperty
                          .getPropertyType()
                          .getParameters()
                          .get(0)
                          .getSimpleTypeName()
                      : gwtProxyProperty.getPropertyType().getSimpleTypeName());
          propTypeName = propTypeName.substring(0, propTypeName.indexOf("Proxy"));
          section.setVariable("requestInterface", propTypeName + "Request");
          section.setVariable(
              "findMethod", "find" + StringUtils.capitalize(propTypeName) + "Entries(0, 50)");
        }
        maybeAddImport(dataDictionary, importSet, gwtProxyProperty.getPropertyType());
        maybeAddImport(dataDictionary, importSet, gwtProxyProperty.getValueType());
        if (gwtProxyProperty.isCollectionOfProxy()) {
          maybeAddImport(
              dataDictionary, importSet, gwtProxyProperty.getPropertyType().getParameters().get(0));
          maybeAddImport(dataDictionary, importSet, gwtProxyProperty.getSetEditorType());
        }
      }
    }

    dataDictionary.setVariable("proxyFields", proxyFields);

    // Add a section for the mobile properties.
    if (primaryProperty != null) {
      dataDictionary.setVariable("primaryProp", primaryProperty.getName());
      dataDictionary.setVariable("primaryPropGetter", primaryProperty.getGetter());
      dataDictionary.setVariable(
          "primaryPropBuilder", primaryProperty.forMobileListView("primaryRenderer"));
      final TemplateDataDictionary section = dataDictionary.addSection("mobileProperties");
      section.setVariable("prop", primaryProperty.getName());
      section.setVariable("propGetter", primaryProperty.getGetter());
      section.setVariable("propType", primaryProperty.getType());
      section.setVariable("propRenderer", primaryProperty.getRenderer());
      section.setVariable("propRendererName", "primaryRenderer");
    } else {
      dataDictionary.setVariable("primaryProp", "id");
      dataDictionary.setVariable("primaryPropGetter", "getId");
      dataDictionary.setVariable("primaryPropBuilder", "");
    }
    if (secondaryProperty != null) {
      dataDictionary.setVariable(
          "secondaryPropBuilder", secondaryProperty.forMobileListView("secondaryRenderer"));
      final TemplateDataDictionary section = dataDictionary.addSection("mobileProperties");
      section.setVariable("prop", secondaryProperty.getName());
      section.setVariable("propGetter", secondaryProperty.getGetter());
      section.setVariable("propType", secondaryProperty.getType());
      section.setVariable("propRenderer", secondaryProperty.getRenderer());
      section.setVariable("propRendererName", "secondaryRenderer");
    } else {
      dataDictionary.setVariable("secondaryPropBuilder", "");
    }
    if (dateProperty != null) {
      dataDictionary.setVariable("datePropBuilder", dateProperty.forMobileListView("dateRenderer"));
      final TemplateDataDictionary section = dataDictionary.addSection("mobileProperties");
      section.setVariable("prop", dateProperty.getName());
      section.setVariable("propGetter", dateProperty.getGetter());
      section.setVariable("propType", dateProperty.getType());
      section.setVariable("propRenderer", dateProperty.getRenderer());
      section.setVariable("propRendererName", "dateRenderer");
    } else {
      dataDictionary.setVariable("datePropBuilder", "");
    }
    return dataDictionary;
  }
  public String buildUiXml(
      final String templateContents,
      final String destFile,
      final List<MethodMetadata> proxyMethods) {
    FileReader fileReader = null;
    try {
      final DocumentBuilder builder = XmlUtils.getDocumentBuilder();
      builder.setEntityResolver(
          new EntityResolver() {
            public InputSource resolveEntity(final String publicId, final String systemId)
                throws SAXException, IOException {
              if (systemId.equals("http://dl.google.com/gwt/DTD/xhtml.ent")) {
                return new InputSource(
                    FileUtils.getInputStream(GwtScaffoldMetadata.class, "templates/xhtml.ent"));
              }

              // Use the default behaviour
              return null;
            }
          });

      InputSource source = new InputSource();
      source.setCharacterStream(new StringReader(templateContents));

      final Document templateDocument = builder.parse(source);

      if (!new File(destFile).exists()) {
        return transformXml(templateDocument);
      }

      source = new InputSource();
      fileReader = new FileReader(destFile);
      source.setCharacterStream(fileReader);
      final Document existingDocument = builder.parse(source);

      // Look for the element holder denoted by the 'debugId' attribute
      // first
      Element existingHoldingElement =
          XmlUtils.findFirstElement(
              "//*[@debugId='" + "boundElementHolder" + "']",
              existingDocument.getDocumentElement());
      Element templateHoldingElement =
          XmlUtils.findFirstElement(
              "//*[@debugId='" + "boundElementHolder" + "']",
              templateDocument.getDocumentElement());

      // If holding element isn't found then the holding element is either
      // not widget based or using the old convention of 'id' so look for
      // the element holder with an 'id' attribute
      if (existingHoldingElement == null) {
        existingHoldingElement =
            XmlUtils.findFirstElement(
                "//*[@id='" + "boundElementHolder" + "']", existingDocument.getDocumentElement());
      }
      if (templateHoldingElement == null) {
        templateHoldingElement =
            XmlUtils.findFirstElement(
                "//*[@id='" + "boundElementHolder" + "']", templateDocument.getDocumentElement());
      }

      if (existingHoldingElement != null) {
        final Map<String, Element> templateElementMap = new LinkedHashMap<String, Element>();
        for (final Element element : XmlUtils.findElements("//*[@id]", templateHoldingElement)) {
          templateElementMap.put(element.getAttribute("id"), element);
        }

        final Map<String, Element> existingElementMap = new LinkedHashMap<String, Element>();
        for (final Element element : XmlUtils.findElements("//*[@id]", existingHoldingElement)) {
          existingElementMap.put(element.getAttribute("id"), element);
        }

        if (existingElementMap.keySet().containsAll(templateElementMap.values())) {
          return transformXml(existingDocument);
        }

        final List<Element> elementsToAdd = new ArrayList<Element>();
        for (final Map.Entry<String, Element> entry : templateElementMap.entrySet()) {
          if (!existingElementMap.keySet().contains(entry.getKey())) {
            elementsToAdd.add(entry.getValue());
          }
        }

        final List<Element> elementsToRemove = new ArrayList<Element>();
        for (final Map.Entry<String, Element> entry : existingElementMap.entrySet()) {
          if (!templateElementMap.keySet().contains(entry.getKey())) {
            elementsToRemove.add(entry.getValue());
          }
        }

        for (final Element element : elementsToAdd) {
          final Node importedNode = existingDocument.importNode(element, true);
          existingHoldingElement.appendChild(importedNode);
        }

        for (final Element element : elementsToRemove) {
          existingHoldingElement.removeChild(element);
        }

        if (elementsToAdd.size() > 0) {
          final List<Element> sortedElements = new ArrayList<Element>();
          for (final MethodMetadata method : proxyMethods) {
            final String propertyName =
                StringUtils.uncapitalize(
                    BeanInfoUtils.getPropertyNameForJavaBeanMethod(method).getSymbolName());
            final Element element =
                XmlUtils.findFirstElement(
                    "//*[@id='" + propertyName + "']", existingHoldingElement);
            if (element != null) {
              sortedElements.add(element);
            }
          }
          for (final Element el : sortedElements) {
            if (el.getParentNode() != null && el.getParentNode().equals(existingHoldingElement)) {
              existingHoldingElement.removeChild(el);
            }
          }
          for (final Element el : sortedElements) {
            existingHoldingElement.appendChild(el);
          }
        }

        return transformXml(existingDocument);
      }

      return transformXml(templateDocument);
    } catch (final Exception e) {
      throw new IllegalStateException(e);
    } finally {
      IOUtils.closeQuietly(fileReader);
    }
  }
Example #13
0
  public static Map<String, UiConfigImpl> getUiConfigs(Class<?> entityClass) {
    Map<String, UiConfigImpl> map = cache.get(entityClass);
    if (map == null || AppInfo.getStage() == Stage.DEVELOPMENT) {
      GenericGenerator genericGenerator =
          AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(
                  entityClass, GenericGenerator.class)
              .get("id");
      boolean idAssigned =
          genericGenerator != null && "assigned".equals(genericGenerator.strategy());
      Map<String, NaturalId> naturalIds =
          AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(entityClass, NaturalId.class);
      Set<String> hides = new HashSet<String>();
      map = new HashMap<String, UiConfigImpl>();
      PropertyDescriptor[] pds =
          org.springframework.beans.BeanUtils.getPropertyDescriptors(entityClass);
      for (PropertyDescriptor pd : pds) {
        String propertyName = pd.getName();
        if (pd.getReadMethod() == null
            || pd.getWriteMethod() == null
                && pd.getReadMethod().getAnnotation(UiConfig.class) == null) continue;
        Class<?> declaredClass = pd.getReadMethod().getDeclaringClass();
        Version version = pd.getReadMethod().getAnnotation(Version.class);
        if (version == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) version = f.getAnnotation(Version.class);
          } catch (Exception e) {
          }
        if (version != null) continue;
        Transient trans = pd.getReadMethod().getAnnotation(Transient.class);
        if (trans == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) trans = f.getAnnotation(Transient.class);
          } catch (Exception e) {
          }
        SearchableProperty searchableProperty =
            pd.getReadMethod().getAnnotation(SearchableProperty.class);
        if (searchableProperty == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) searchableProperty = f.getAnnotation(SearchableProperty.class);
          } catch (Exception e) {
          }
        SearchableId searchableId = pd.getReadMethod().getAnnotation(SearchableId.class);
        if (searchableId == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) searchableId = f.getAnnotation(SearchableId.class);
          } catch (Exception e) {
          }
        UiConfig uiConfig = pd.getReadMethod().getAnnotation(UiConfig.class);
        if (uiConfig == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) uiConfig = f.getAnnotation(UiConfig.class);
          } catch (Exception e) {
          }

        if (uiConfig != null && uiConfig.hidden()) continue;
        if ("new".equals(propertyName)
            || !idAssigned && "id".equals(propertyName)
            || "class".equals(propertyName)
            || "fieldHandler".equals(propertyName)
            || pd.getReadMethod() == null
            || hides.contains(propertyName)) continue;
        Column columnannotation = pd.getReadMethod().getAnnotation(Column.class);
        if (columnannotation == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) columnannotation = f.getAnnotation(Column.class);
          } catch (Exception e) {
          }
        Basic basic = pd.getReadMethod().getAnnotation(Basic.class);
        if (basic == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) basic = f.getAnnotation(Basic.class);
          } catch (Exception e) {
          }
        Lob lob = pd.getReadMethod().getAnnotation(Lob.class);
        if (lob == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) lob = f.getAnnotation(Lob.class);
          } catch (Exception e) {
          }
        UiConfigImpl uci = new UiConfigImpl(pd.getPropertyType(), uiConfig);
        if (idAssigned && propertyName.equals("id")) uci.addCssClass("required checkavailable");
        if (Attributable.class.isAssignableFrom(entityClass) && pd.getName().equals("attributes")) {
          uci.setType("attributes");
        }
        if (trans != null) {
          uci.setExcludedFromCriteria(true);
          uci.setExcludedFromLike(true);
          uci.setExcludedFromOrdering(true);
        }
        if (lob != null) {
          uci.setExcludedFromCriteria(true);
          if (uci.getMaxlength() == 0) uci.setMaxlength(2 * 1024 * 1024);
        }
        if (columnannotation != null && !columnannotation.nullable()
            || basic != null && !basic.optional()) uci.setRequired(true);
        if (columnannotation != null && columnannotation.length() != 255 && uci.getMaxlength() == 0)
          uci.setMaxlength(columnannotation.length());
        if (lob != null || uci.getMaxlength() > 255) uci.setExcludedFromOrdering(true);
        Class<?> returnType = pd.getPropertyType();
        if (returnType.isEnum()) {
          uci.setType("enum");
          try {
            returnType.getMethod("getName");
            uci.setListKey("name");
          } catch (NoSuchMethodException e) {
            uci.setListKey("top");
          }
          try {
            returnType.getMethod("getDisplayName");
            uci.setListValue("displayName");
          } catch (NoSuchMethodException e) {
            uci.setListValue(uci.getListKey());
          }
          map.put(propertyName, uci);
          continue;
        } else if (Persistable.class.isAssignableFrom(returnType)) {
          JoinColumn joincolumnannotation = pd.getReadMethod().getAnnotation(JoinColumn.class);
          if (joincolumnannotation == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) joincolumnannotation = f.getAnnotation(JoinColumn.class);
            } catch (Exception e) {
            }
          if (joincolumnannotation != null && !joincolumnannotation.nullable())
            uci.setRequired(true);
          ManyToOne manyToOne = pd.getReadMethod().getAnnotation(ManyToOne.class);
          if (manyToOne == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) manyToOne = f.getAnnotation(ManyToOne.class);
            } catch (Exception e) {
            }
          if (manyToOne != null && !manyToOne.optional()) uci.setRequired(true);
          uci.setType("listpick");
          uci.setExcludeIfNotEdited(true);
          if (StringUtils.isBlank(uci.getPickUrl())) {
            String url = AutoConfigPackageProvider.getEntityUrl(returnType);
            StringBuilder sb =
                url != null
                    ? new StringBuilder(url)
                    : new StringBuilder("/")
                        .append(StringUtils.uncapitalize(returnType.getSimpleName()));
            sb.append("/pick");
            Set<String> columns = new LinkedHashSet<String>();
            columns.addAll(
                AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(returnType, NaturalId.class)
                    .keySet());
            Map<String, UiConfigImpl> configs = getUiConfigs(returnType);
            for (String column : "fullname,name,code".split(","))
              if (configs.containsKey(column)
                  && (!columns.contains("fullname") && column.equals("name")
                      || !column.equals("name"))) columns.add(column);
            for (Map.Entry<String, UiConfigImpl> entry : configs.entrySet())
              if (entry.getValue().isShownInPick()) columns.add(entry.getKey());
            if (!columns.isEmpty()) {
              sb.append("?columns=" + StringUtils.join(columns, ','));
            }
            uci.setPickUrl(sb.toString());
          }
          map.put(propertyName, uci);
          continue;
        }
        if (returnType == Integer.TYPE
            || returnType == Short.TYPE
            || returnType == Long.TYPE
            || returnType == Double.TYPE
            || returnType == Float.TYPE
            || Number.class.isAssignableFrom(returnType)) {
          if (returnType == Integer.TYPE
              || returnType == Integer.class
              || returnType == Short.TYPE
              || returnType == Short.class) {
            uci.setInputType("number");
            uci.addCssClass("integer");

          } else if (returnType == Long.TYPE || returnType == Long.class) {
            uci.setInputType("number");
            uci.addCssClass("long");
          } else if (returnType == Double.TYPE
              || returnType == Double.class
              || returnType == Float.TYPE
              || returnType == Float.class
              || returnType == BigDecimal.class) {
            uci.setInputType("number");
            uci.addCssClass("double");
          }
          Set<String> cssClasses = uci.getCssClasses();
          if (cssClasses.contains("double") && !uci.getDynamicAttributes().containsKey("step"))
            uci.getDynamicAttributes().put("step", "0.01");
          if (cssClasses.contains("positive") && !uci.getDynamicAttributes().containsKey("min")) {
            uci.getDynamicAttributes().put("min", "1");
            if (cssClasses.contains("double")) uci.getDynamicAttributes().put("min", "0.01");
            if (cssClasses.contains("zero")) uci.getDynamicAttributes().put("min", "0");
          }
        } else if (Date.class.isAssignableFrom(returnType)) {
          Temporal temporal = pd.getReadMethod().getAnnotation(Temporal.class);
          if (temporal == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) temporal = f.getAnnotation(Temporal.class);
            } catch (Exception e) {
            }
          String temporalType = "date";
          if (temporal != null)
            if (temporal.value() == TemporalType.TIMESTAMP) temporalType = "datetime";
            else if (temporal.value() == TemporalType.TIME) temporalType = "time";
          uci.addCssClass(temporalType);
          // uci.setInputType(temporalType);
          if (StringUtils.isBlank(uci.getCellEdit())) uci.setCellEdit("click," + temporalType);
        } else if (String.class == returnType
            && pd.getName().toLowerCase().contains("email")
            && !pd.getName().contains("Password")) {
          uci.setInputType("email");
          uci.addCssClass("email");
        } else if (returnType == Boolean.TYPE || returnType == Boolean.class) {
          uci.setType("checkbox");
        }
        if (columnannotation != null && columnannotation.unique()) uci.setUnique(true);
        if (searchableProperty != null || searchableId != null) uci.setSearchable(true);

        if (naturalIds.containsKey(pd.getName())) {
          uci.setRequired(true);
          if (naturalIds.size() == 1) uci.addCssClass("checkavailable");
        }
        map.put(propertyName, uci);
      }
      List<Map.Entry<String, UiConfigImpl>> list =
          new ArrayList<Map.Entry<String, UiConfigImpl>>(map.entrySet());
      Collections.sort(list, comparator);
      Map<String, UiConfigImpl> sortedMap = new LinkedHashMap<String, UiConfigImpl>();
      for (Map.Entry<String, UiConfigImpl> entry : list)
        sortedMap.put(entry.getKey(), entry.getValue());
      map = sortedMap;
      cache.put(entityClass, Collections.unmodifiableMap(map));
    }
    return map;
  }
  private TemplateDataDictionary buildDictionary(final GwtType type, final String moduleName) {
    final Set<ClassOrInterfaceTypeDetails> proxies =
        typeLocationService.findClassesOrInterfaceDetailsWithAnnotation(RooJavaType.ROO_GWT_PROXY);
    final TemplateDataDictionary dataDictionary = buildStandardDataDictionary(type, moduleName);
    switch (type) {
      case APP_ENTITY_TYPES_PROCESSOR:
        for (final ClassOrInterfaceTypeDetails proxy : proxies) {
          if (!GwtUtils.scaffoldProxy(proxy)) {
            continue;
          }
          final String proxySimpleName = proxy.getName().getSimpleTypeName();
          final ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy);
          if (entity != null) {
            final String entitySimpleName = entity.getName().getSimpleTypeName();

            dataDictionary.addSection("proxys").setVariable("proxy", proxySimpleName);

            final String entity1 =
                new StringBuilder("\t\tif (")
                    .append(proxySimpleName)
                    .append(".class.equals(clazz)) {\n\t\t\tprocessor.handle")
                    .append(entitySimpleName)
                    .append("((")
                    .append(proxySimpleName)
                    .append(") null);\n\t\t\treturn;\n\t\t}")
                    .toString();
            dataDictionary.addSection("entities1").setVariable("entity", entity1);

            final String entity2 =
                new StringBuilder("\t\tif (proxy instanceof ")
                    .append(proxySimpleName)
                    .append(") {\n\t\t\tprocessor.handle")
                    .append(entitySimpleName)
                    .append("((")
                    .append(proxySimpleName)
                    .append(") proxy);\n\t\t\treturn;\n\t\t}")
                    .toString();
            dataDictionary.addSection("entities2").setVariable("entity", entity2);

            final String entity3 =
                new StringBuilder("\tpublic abstract void handle")
                    .append(entitySimpleName)
                    .append("(")
                    .append(proxySimpleName)
                    .append(" proxy);")
                    .toString();
            dataDictionary.addSection("entities3").setVariable("entity", entity3);
            addImport(dataDictionary, proxy.getName().getFullyQualifiedTypeName());
          }
        }
        break;
      case MASTER_ACTIVITIES:
        for (final ClassOrInterfaceTypeDetails proxy : proxies) {
          if (!GwtUtils.scaffoldProxy(proxy)) {
            continue;
          }
          final String proxySimpleName = proxy.getName().getSimpleTypeName();
          final ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy);
          if (entity != null && !Modifier.isAbstract(entity.getModifier())) {
            final String entitySimpleName = entity.getName().getSimpleTypeName();
            final TemplateDataDictionary section = dataDictionary.addSection("entities");
            section.setVariable("entitySimpleName", entitySimpleName);
            section.setVariable("entityFullPath", proxySimpleName);
            addImport(dataDictionary, entitySimpleName, GwtType.LIST_ACTIVITY, moduleName);
            addImport(dataDictionary, proxy.getName().getFullyQualifiedTypeName());
            addImport(dataDictionary, entitySimpleName, GwtType.LIST_VIEW, moduleName);
            addImport(dataDictionary, entitySimpleName, GwtType.MOBILE_LIST_VIEW, moduleName);
          }
        }
        break;
      case APP_REQUEST_FACTORY:
        for (final ClassOrInterfaceTypeDetails proxy : proxies) {
          if (!GwtUtils.scaffoldProxy(proxy)) {
            continue;
          }
          final ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy);
          if (entity != null && !Modifier.isAbstract(entity.getModifier())) {
            final String entitySimpleName = entity.getName().getSimpleTypeName();
            final ClassOrInterfaceTypeDetails request =
                gwtTypeService.lookupRequestFromProxy(proxy);
            if (request != null) {
              final String requestExpression =
                  new StringBuilder("\t")
                      .append(request.getName().getSimpleTypeName())
                      .append(" ")
                      .append(StringUtils.uncapitalize(entitySimpleName))
                      .append("Request();")
                      .toString();
              dataDictionary.addSection("entities").setVariable("entity", requestExpression);
              addImport(dataDictionary, request.getName().getFullyQualifiedTypeName());
            }
          }
          dataDictionary.setVariable(
              "sharedScaffoldPackage",
              GwtPath.SHARED_SCAFFOLD.packageName(
                  projectOperations.getTopLevelPackage(moduleName)));
        }

        if (projectOperations.isFeatureInstalledInFocusedModule(FeatureNames.GAE)) {
          dataDictionary.showSection("gae");
        }
        break;
      case LIST_PLACE_RENDERER:
        for (final ClassOrInterfaceTypeDetails proxy : proxies) {
          if (!GwtUtils.scaffoldProxy(proxy)) {
            continue;
          }
          final ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy);
          if (entity != null) {
            final String entitySimpleName = entity.getName().getSimpleTypeName();
            final String proxySimpleName = proxy.getName().getSimpleTypeName();
            final TemplateDataDictionary section = dataDictionary.addSection("entities");
            section.setVariable("entitySimpleName", entitySimpleName);
            section.setVariable("entityFullPath", proxySimpleName);
            addImport(dataDictionary, proxy.getName().getFullyQualifiedTypeName());
          }
        }
        break;
      case DETAILS_ACTIVITIES:
        for (final ClassOrInterfaceTypeDetails proxy : proxies) {
          if (!GwtUtils.scaffoldProxy(proxy)) {
            continue;
          }
          final ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy);
          if (entity != null) {
            final String proxySimpleName = proxy.getName().getSimpleTypeName();
            final String entitySimpleName = entity.getName().getSimpleTypeName();
            final String entityExpression =
                new StringBuilder("\t\t\tpublic void handle")
                    .append(entitySimpleName)
                    .append("(")
                    .append(proxySimpleName)
                    .append(" proxy) {\n")
                    .append("\t\t\t\tsetResult(new ")
                    .append(entitySimpleName)
                    .append(
                        "ActivitiesMapper(requests, placeController).getActivity(proxyPlace));\n\t\t\t}")
                    .toString();
            dataDictionary.addSection("entities").setVariable("entity", entityExpression);
            addImport(dataDictionary, proxy.getName().getFullyQualifiedTypeName());
            addImport(
                dataDictionary,
                GwtType.ACTIVITIES_MAPPER
                        .getPath()
                        .packageName(projectOperations.getTopLevelPackage(moduleName))
                    + "."
                    + entitySimpleName
                    + GwtType.ACTIVITIES_MAPPER.getSuffix());
          }
        }
        break;
      case MOBILE_ACTIVITIES:
        // Do nothing
        break;
    }

    return dataDictionary;
  }
 private String toJavaFieldName(final String key) {
   return StringUtils.uncapitalize(toJavaName(key));
 }
  @SuppressWarnings({"resource", "rawtypes", "unchecked"})
  public static void main(String[] args) throws Exception {
    Configuration cfg = new Configuration();
    // 设置FreeMarker的模版文件位置
    cfg.setClassForTemplateLoading(
        SourceCodeFrameworkBuilder.class, "/lab/s2jh/tool/builder/freemarker");
    cfg.setDefaultEncoding("UTF-8");
    String rootPath = args[0];

    Set<String> entityNames = new HashSet<String>();

    String entityListFile = rootPath + "entity_list.properties";
    BufferedReader reader = new BufferedReader(new FileReader(entityListFile));
    String line;
    while ((line = reader.readLine()) != null) {
      if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
        entityNames.add(line);
      }
    }

    new File(rootPath + "\\codes").mkdir();
    new File(rootPath + "\\codes\\integrate").mkdir();
    new File(rootPath + "\\codes\\standalone").mkdir();

    for (String entityName : entityNames) {

      String integrateRootPath = rootPath + "\\codes\\integrate\\";
      String standaloneRootPath = rootPath + "\\codes\\standalone\\";

      String rootPackage = StringUtils.substringBetween(entityName, "[", "]");
      String rootPackagePath = StringUtils.replace(rootPackage, ".", "\\");

      String className = StringUtils.substringAfterLast(entityName, ".");
      String classFullName =
          StringUtils.replaceEach(entityName, new String[] {"[", "]"}, new String[] {"", ""});

      String modelName = StringUtils.substringBetween(entityName, "].", ".entity");
      String modelPath = StringUtils.replace(modelName, ".", "/");
      modelPath = "/" + modelPath;
      String modelPackagePath = StringUtils.replace(modelName, ".", "\\");
      modelPackagePath = "\\" + modelPackagePath;

      Map<String, Object> root = new HashMap<String, Object>();
      String nameField = propertyToField(StringUtils.uncapitalize(className)).toLowerCase();
      root.put("model_name", modelName);
      root.put("model_path", modelPath);
      root.put("entity_name", className);
      root.put("entity_name_uncapitalize", StringUtils.uncapitalize(className));
      root.put("entity_name_field", nameField);
      root.put("root_package", rootPackage + "." + modelName);
      root.put("action_package", rootPackage);
      root.put("table_name", "T_TODO_" + className.toUpperCase());
      root.put("base", "${base}");
      Class entityClass = Class.forName(classFullName);
      root.put("id_type", entityClass.getMethod("getId").getReturnType().getSimpleName());
      MetaData classEntityComment = (MetaData) entityClass.getAnnotation(MetaData.class);
      if (classEntityComment != null) {
        root.put("model_title", classEntityComment.value());
      } else {
        root.put("model_title", entityName);
      }
      debug("Entity Data Map=" + root);

      Set<Field> fields = new HashSet<Field>();

      Field[] curfields = entityClass.getDeclaredFields();
      for (Field field : curfields) {
        fields.add(field);
      }

      Class superClass = entityClass.getSuperclass();
      while (superClass != null && !superClass.equals(BaseEntity.class)) {
        Field[] superfields = superClass.getDeclaredFields();
        for (Field field : superfields) {
          fields.add(field);
        }
        superClass = superClass.getSuperclass();
      }

      // 定义用于OneToOne关联对象的Fetch参数
      Map<String, String> fetchJoinFields = Maps.newHashMap();
      List<EntityCodeField> entityFields = new ArrayList<EntityCodeField>();
      int cnt = 1;
      for (Field field : fields) {
        if ((field.getModifiers() & Modifier.FINAL) != 0 || "id".equals(field.getName())) {
          continue;
        }
        debug(" - Field=" + field);
        Class fieldType = field.getType();

        EntityCodeField entityCodeField = null;
        if (fieldType.isEnum()) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(80);
          entityCodeField.setListAlign("center");
        } else if (fieldType == Boolean.class) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(60);
          entityCodeField.setListAlign("center");
        } else if (PersistableEntity.class.isAssignableFrom(fieldType)) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setFieldType("Entity");

        } else if (Number.class.isAssignableFrom(fieldType)) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(60);
          entityCodeField.setListAlign("right");
        } else if (fieldType == String.class) {
          entityCodeField = new EntityCodeField();

          // 根据Hibernate注解的字符串类型和长度设定是否列表显示
          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          Column fieldColumn = getMethod.getAnnotation(Column.class);
          if (fieldColumn != null) {
            int length = fieldColumn.length();
            if (length > 255) {
              entityCodeField.setList(false);
              entityCodeField.setListWidth(length);
            }
          }
          Lob fieldLob = getMethod.getAnnotation(Lob.class);
          if (fieldLob != null) {
            entityCodeField.setList(false);
            entityCodeField.setListWidth(Integer.MAX_VALUE);
          }
        } else if (fieldType == Date.class) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);

          // 根据Json注解设定合理的列宽
          entityCodeField.setListWidth(120);
          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          JsonSerialize fieldJsonSerialize = getMethod.getAnnotation(JsonSerialize.class);
          if (fieldJsonSerialize != null) {
            if (DateJsonSerializer.class.equals(fieldJsonSerialize.using())) {
              entityCodeField.setListWidth(80);
            }
          }
          entityCodeField.setListAlign("center");
        }

        if (entityCodeField != null) {
          if (fieldType.isEnum()) {
            entityCodeField.setEnumField(true);
          }
          if (StringUtils.isBlank(entityCodeField.getFieldType())) {
            entityCodeField.setFieldType(fieldType.getSimpleName());
          }
          entityCodeField.setFieldName(field.getName());
          EntityAutoCode entityAutoCode = field.getAnnotation(EntityAutoCode.class);
          if (entityAutoCode != null) {
            entityCodeField.setListHidden(entityAutoCode.listHidden());
            entityCodeField.setEdit(entityAutoCode.edit());
            entityCodeField.setList(entityAutoCode.listHidden() || entityAutoCode.listShow());
            entityCodeField.setOrder(entityAutoCode.order());
          } else {
            entityCodeField.setTitle(field.getName());
            entityCodeField.setOrder(cnt++);
          }

          MetaData entityMetaData = field.getAnnotation(MetaData.class);
          if (entityMetaData != null) {
            entityCodeField.setTitle(entityMetaData.value());
          }

          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          JsonProperty fieldJsonProperty = getMethod.getAnnotation(JsonProperty.class);
          if (fieldJsonProperty != null) {
            entityCodeField.setList(true);
          }

          if (entityCodeField.getList() || entityCodeField.getListHidden()) {
            JoinColumn fieldJoinColumn = getMethod.getAnnotation(JoinColumn.class);
            if (fieldJoinColumn != null) {
              if (fieldJoinColumn.nullable() == false) {
                fetchJoinFields.put(field.getName(), "INNER");
              } else {
                fetchJoinFields.put(field.getName(), "LEFT");
              }
            }
          }

          entityFields.add(entityCodeField);
        }
      }
      Collections.sort(entityFields);
      root.put("entityFields", entityFields);
      if (fetchJoinFields.size() > 0) {
        root.put("fetchJoinFields", fetchJoinFields);
      }

      integrateRootPath = integrateRootPath + rootPackagePath + modelPackagePath;
      // process(cfg.getTemplate("Entity.ftl"), root, integrateRootPath + "\\entity\\", className +
      // ".java");
      process(
          cfg.getTemplate("Dao.ftl"), root, integrateRootPath + "\\dao\\", className + "Dao.java");
      process(
          cfg.getTemplate("Service.ftl"),
          root,
          integrateRootPath + "\\service\\",
          className + "Service.java");
      process(
          cfg.getTemplate("Controller.ftl"),
          root,
          integrateRootPath + "\\web\\action\\",
          className + "Controller.java");
      process(
          cfg.getTemplate("Test.ftl"),
          root,
          integrateRootPath + "\\test\\service\\",
          className + "ServiceTest.java");
      process(
          cfg.getTemplate("JSP_Index.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-index.jsp");
      process(
          cfg.getTemplate("JSP_Input_Tabs.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-inputTabs.jsp");
      process(
          cfg.getTemplate("JSP_Input_Basic.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-inputBasic.jsp");
      process(
          cfg.getTemplate("JSP_View_Tabs.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-viewTabs.jsp");
      process(
          cfg.getTemplate("JSP_View_Basic.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-viewBasic.jsp");

      standaloneRootPath =
          standaloneRootPath + rootPackagePath + modelPackagePath + "\\" + className;
      // process(cfg.getTemplate("Entity.ftl"), root, standaloneRootPath + "\\entity\\", className +
      // ".java");
      process(
          cfg.getTemplate("Dao.ftl"), root, standaloneRootPath + "\\dao\\", className + "Dao.java");
      process(
          cfg.getTemplate("Service.ftl"),
          root,
          standaloneRootPath + "\\service\\",
          className + "Service.java");
      process(
          cfg.getTemplate("Controller.ftl"),
          root,
          standaloneRootPath + "\\web\\action\\",
          className + "Controller.java");
      process(
          cfg.getTemplate("Test.ftl"),
          root,
          standaloneRootPath + "\\test\\service\\",
          className + "ServiceTest.java");
      process(
          cfg.getTemplate("JSP_Index.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-index.jsp");
      process(
          cfg.getTemplate("JSP_Input_Tabs.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-inputTabs.jsp");
      process(
          cfg.getTemplate("JSP_Input_Basic.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-inputBasic.jsp");
      process(
          cfg.getTemplate("JSP_View_Tabs.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-viewTabs.jsp");
      process(
          cfg.getTemplate("JSP_View_Basic.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-viewBasic.jsp");
    }
  }
 @Override
 public String getName() {
   return StringUtils.uncapitalize(getClass().getSimpleName());
 }
Example #18
0
  @SuppressWarnings("unchecked")
  @Before
  public void setUp() {
    // type
    Type typeModel =
        new SimpleType(
            TypeCategory.ENTITY,
            "com.mysema.query.DomainClass",
            "com.mysema.query",
            "DomainClass",
            false,
            false);
    type = new EntityType(typeModel);

    // property
    type.addProperty(new Property(type, "entityField", type, new String[0]));
    type.addProperty(
        new Property(
            type,
            "collection",
            new ClassType(TypeCategory.COLLECTION, Collection.class, typeModel),
            new String[0]));
    type.addProperty(
        new Property(
            type,
            "listField",
            new ClassType(TypeCategory.LIST, List.class, typeModel),
            new String[0]));
    type.addProperty(
        new Property(
            type,
            "setField",
            new ClassType(TypeCategory.SET, Set.class, typeModel),
            new String[0]));
    type.addProperty(
        new Property(
            type,
            "arrayField",
            new ClassType(TypeCategory.ARRAY, String[].class, typeModel),
            new String[0]));
    type.addProperty(
        new Property(
            type,
            "mapField",
            new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel),
            new String[0]));
    type.addProperty(
        new Property(
            type,
            "superTypeField",
            new TypeExtends(new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel)),
            new String[0]));
    type.addProperty(
        new Property(
            type,
            "extendsTypeField",
            new TypeSuper(new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel)),
            new String[0]));

    for (Class<?> cl :
        Arrays.asList(
            Boolean.class,
            Comparable.class,
            Integer.class,
            Date.class,
            java.sql.Date.class,
            java.sql.Time.class)) {
      Type classType = new ClassType(TypeCategory.get(cl.getName()), cl);
      type.addProperty(
          new Property(
              type, StringUtils.uncapitalize(cl.getSimpleName()), classType, new String[0]));
    }

    // constructor
    Parameter firstName =
        new Parameter("firstName", new ClassType(TypeCategory.STRING, String.class));
    Parameter lastName =
        new Parameter("lastName", new ClassType(TypeCategory.STRING, String.class));
    type.addConstructor(new Constructor(Arrays.asList(firstName, lastName)));
  }
 @Override
 public String transform(final String input) {
   return StringUtils.uncapitalize(input);
 }