private MethodMetadataBuilder getCreateMethod(String declaredById, JavaType targetType) {
   InvocableMemberBodyBuilder invocableMemberBodyBuilder =
       InvocableMemberBodyBuilder.getInstance();
   invocableMemberBodyBuilder.append("return new " + targetType.getSimpleTypeName() + "();");
   MethodMetadataBuilder createMethodBuilder =
       new MethodMetadataBuilder(
           declaredById,
           Modifier.PUBLIC,
           new JavaSymbolName("create"),
           targetType,
           invocableMemberBodyBuilder);
   JavaType wildEntityType =
       new JavaType(
           targetType.getFullyQualifiedTypeName(),
           0,
           DataType.VARIABLE,
           JavaType.WILDCARD_EXTENDS,
           null);
   JavaType classParameterType =
       new JavaType(
           JavaType.CLASS.getFullyQualifiedTypeName(),
           0,
           DataType.TYPE,
           null,
           Arrays.asList(wildEntityType));
   createMethodBuilder.addParameter("clazz", classParameterType);
   return createMethodBuilder;
 }
Ejemplo n.º 2
0
 public static String getProxyRendererType(
     final JavaPackage topLevelPackage, final JavaType javaType) {
   return GwtType.EDIT_RENDERER.getPath().packageName(topLevelPackage)
       + "."
       + javaType.getSimpleTypeName()
       + "Renderer";
 }
Ejemplo n.º 3
0
  @Override
  protected ItdTypeDetailsProvidingMetadataItem getMetadata(
      final String metadataIdentificationString,
      final JavaType aspectName,
      final PhysicalTypeMetadata governorPhysicalTypeMetadata,
      final String itdFilename) {
    // Acquire bean info (we need getters details, specifically)
    final JavaType javaType = JsonMetadata.getJavaType(metadataIdentificationString);
    final LogicalPath path = JsonMetadata.getPath(metadataIdentificationString);

    // We need to parse the annotation, if it is not present we will simply
    // get the default annotation values
    final JsonAnnotationValues annotationValues =
        new JsonAnnotationValues(governorPhysicalTypeMetadata);

    String plural = javaType.getSimpleTypeName() + "s";
    final PluralMetadata pluralMetadata =
        (PluralMetadata) getMetadataService().get(PluralMetadata.createIdentifier(javaType, path));
    if (pluralMetadata != null) {
      plural = pluralMetadata.getPlural();
    }

    return new JsonMetadata(
        metadataIdentificationString,
        aspectName,
        governorPhysicalTypeMetadata,
        plural,
        annotationValues);
  }
  /** {@inheritDoc} */
  public void annotateType(final JavaType type, final JavaPackage javaPackage) {
    // TODO check for existing controller

    // Use Roo's Assert type for null checks
    Validate.notNull(type, "Java type required");
    Validate.notNull(javaPackage, "Java package required, web mvc all command package required");

    // Obtain ClassOrInterfaceTypeDetails for this java type
    ClassOrInterfaceTypeDetails entityDetails = typeLocationService.getTypeDetails(type);

    // Test if the annotation already exists on the target type
    if (entityDetails != null
        && MemberFindingUtils.getAnnotationOfType(
                entityDetails.getAnnotations(), new JavaType(RooEnvers.class.getName()))
            == null) {
      ClassOrInterfaceTypeDetailsBuilder classOrInterfaceTypeDetailsBuilder =
          new ClassOrInterfaceTypeDetailsBuilder(entityDetails);

      // Create JavaType instance for the add-ons trigger annotation
      JavaType rooEnvers = new JavaType(RooEnvers.class.getName());

      // Create Annotation metadata
      AnnotationMetadataBuilder annotationBuilder = new AnnotationMetadataBuilder(rooEnvers);

      // Add annotation to target type
      classOrInterfaceTypeDetailsBuilder.addAnnotation(annotationBuilder.build());

      // Save changes to disk
      typeManagementService.createOrUpdateTypeOnDisk(classOrInterfaceTypeDetailsBuilder.build());
    }

    // Get details for existing controller
    JavaType typeController =
        new JavaType(
            javaPackage.getFullyQualifiedPackageName()
                + "."
                + type.getSimpleTypeName()
                + "Controller");
    ClassOrInterfaceTypeDetails typeControllerDetails =
        typeLocationService.getTypeDetails(typeController);

    // Add annotation @RooEnversController to existing controller
    ClassOrInterfaceTypeDetailsBuilder classOrInterfaceTypeDetailsBuilder =
        new ClassOrInterfaceTypeDetailsBuilder(typeControllerDetails);
    JavaType rooEnversController =
        new JavaType("de.eightbitboy.roo.envers.controller.RooEnversController");

    final List<AnnotationAttributeValue<?>> rooEnversControllerAttributes =
        new ArrayList<AnnotationAttributeValue<?>>();
    rooEnversControllerAttributes.add(new ClassAttributeValue(new JavaSymbolName("type"), type));

    AnnotationMetadataBuilder annotationBuilder =
        new AnnotationMetadataBuilder(rooEnversController, rooEnversControllerAttributes);
    classOrInterfaceTypeDetailsBuilder.addAnnotation(annotationBuilder.build());

    typeManagementService.createOrUpdateTypeOnDisk(classOrInterfaceTypeDetailsBuilder.build());
  }
 private MethodMetadataBuilder getIdMethod(
     String declaredById, JavaType targetType, MethodMetadata idAccessor) {
   InvocableMemberBodyBuilder invocableMemberBodyBuilder =
       InvocableMemberBodyBuilder.getInstance();
   invocableMemberBodyBuilder.append(
       "return "
           + StringUtils.uncapitalize(targetType.getSimpleTypeName())
           + "."
           + idAccessor.getMethodName()
           + "();");
   MethodMetadataBuilder getIdMethod =
       new MethodMetadataBuilder(
           declaredById,
           Modifier.PUBLIC,
           new JavaSymbolName("getId"),
           GwtUtils.convertPrimitiveType(idAccessor.getReturnType(), true),
           invocableMemberBodyBuilder);
   getIdMethod.addParameter(StringUtils.uncapitalize(targetType.getSimpleTypeName()), targetType);
   return getIdMethod;
 }
Ejemplo n.º 6
0
 public static JavaType convertGovernorTypeNameIntoKeyTypeName(
     final JavaType governorType, final GwtType type, final ProjectMetadata projectMetadata) {
   String destinationPackage = type.getPath().packageName(projectMetadata);
   String typeName;
   if (type.isMirrorType()) {
     String simple = governorType.getSimpleTypeName();
     typeName = destinationPackage + "." + simple + type.getSuffix();
   } else {
     typeName = destinationPackage + "." + type.getTemplate();
   }
   return new JavaType(typeName);
 }
 private MethodMetadataBuilder getVersionMethod(
     String declaredById, JavaType targetType, MethodMetadata versionAccessor) {
   InvocableMemberBodyBuilder invocableMemberBodyBuilder =
       InvocableMemberBodyBuilder.getInstance();
   invocableMemberBodyBuilder.append(
       "return "
           + StringUtils.uncapitalize(targetType.getSimpleTypeName())
           + "."
           + versionAccessor.getMethodName()
           + "();");
   MethodMetadataBuilder getIdMethodBuilder =
       new MethodMetadataBuilder(
           declaredById,
           Modifier.PUBLIC,
           new JavaSymbolName("getVersion"),
           JavaType.OBJECT,
           invocableMemberBodyBuilder);
   getIdMethodBuilder.addParameter(
       StringUtils.uncapitalize(targetType.getSimpleTypeName()), targetType);
   return getIdMethodBuilder;
 }
 /**
  * Sets up the mock {@link RepositoryJpaLocator} and {@link PersistenceMemberLocator} to return a
  * mock repository for our test entity.
  */
 private void setUpMockRepository() {
   final ClassOrInterfaceTypeDetails mockRepositoryDetails =
       mock(ClassOrInterfaceTypeDetails.class);
   final FieldMetadata mockFieldMetadata = mock(FieldMetadata.class);
   final JavaType mockRepositoryType = mock(JavaType.class);
   when(mockRepositoryType.getSimpleTypeName()).thenReturn("ClinicRepo");
   when(mockIdType.getFullyQualifiedTypeName()).thenReturn(Long.class.getName());
   when(mockRepositoryDetails.getName()).thenReturn(mockRepositoryType);
   when(mockFieldMetadata.getFieldType()).thenReturn(mockIdType);
   when(mockRepositoryLocator.getRepositories(mockTargetEntity))
       .thenReturn(Arrays.asList(mockRepositoryDetails));
 }
Ejemplo n.º 9
0
 public String getSetValuePickerMethod() {
   return "\tpublic void "
       + getSetValuePickerMethodName()
       + "(Collection<"
       + (isCollection()
           ? type.getParameters().get(0).getSimpleTypeName()
           : type.getSimpleTypeName())
       + "> values) {\n"
       + "\t\t"
       + getName()
       + ".setAcceptableValues(values);\n"
       + "\t}\n";
 }
Ejemplo n.º 10
0
 private String getSetEditor() {
   String typeName = OBJECT.getFullyQualifiedTypeName();
   if (type.getParameters().size() > 0) {
     typeName = type.getParameters().get(0).getSimpleTypeName();
   }
   if (typeName.endsWith(GwtType.PROXY.getSuffix())) {
     typeName = typeName.substring(0, typeName.length() - GwtType.PROXY.getSuffix().length());
   }
   return typeName
       + (type.getSimpleTypeName().equals("Set")
           ? GwtType.SET_EDITOR.getSuffix()
           : GwtType.LIST_EDITOR.getSuffix());
 }
Ejemplo n.º 11
0
  /**
   * Asserts that the given preferred mapping provided by the user gives rise to the expected folder
   * name and mapping to use in the annotation
   *
   * @param preferredMapping
   * @param expectedFolder
   * @param expectedMapping
   */
  private void assertFolderAndMapping(
      final String preferredMapping, final String expectedFolder, final String expectedMapping) {
    // Set up
    final JavaType mockController = mock(JavaType.class);
    when(mockController.getSimpleTypeName()).thenReturn("FooController");

    // Invoke
    final Pair<String, String> pair =
        JspOperationsImpl.getFolderAndMapping(preferredMapping, mockController);

    // Check
    assertEquals(expectedFolder, pair.getKey());
    assertEquals(expectedMapping, pair.getValue());
  }
 private MethodMetadataBuilder getDomainTypeMethod(String declaredById, JavaType targetType) {
   InvocableMemberBodyBuilder invocableMemberBodyBuilder =
       InvocableMemberBodyBuilder.getInstance();
   invocableMemberBodyBuilder.append("return " + targetType.getSimpleTypeName() + ".class;");
   JavaType returnType =
       new JavaType(
           JavaType.CLASS.getFullyQualifiedTypeName(),
           0,
           DataType.TYPE,
           null,
           Arrays.asList(targetType));
   return new MethodMetadataBuilder(
       declaredById,
       Modifier.PUBLIC,
       new JavaSymbolName("getDomainType"),
       returnType,
       invocableMemberBodyBuilder);
 }
 private TemplateDataDictionary buildStandardDataDictionary(
     final GwtType type, final String moduleName) {
   final JavaType javaType = new JavaType(getFullyQualifiedTypeName(type, moduleName));
   final TemplateDataDictionary dataDictionary = TemplateDictionary.create();
   for (final GwtType reference : type.getReferences()) {
     addReference(dataDictionary, reference, moduleName);
   }
   dataDictionary.setVariable("className", javaType.getSimpleTypeName());
   dataDictionary.setVariable("packageName", javaType.getPackage().getFullyQualifiedPackageName());
   dataDictionary.setVariable(
       "placePackage",
       GwtPath.SCAFFOLD_PLACE.packageName(projectOperations.getTopLevelPackage(moduleName)));
   dataDictionary.setVariable(
       "sharedScaffoldPackage",
       GwtPath.SHARED_SCAFFOLD.packageName(projectOperations.getTopLevelPackage(moduleName)));
   dataDictionary.setVariable(
       "sharedGaePackage",
       GwtPath.SHARED_GAE.packageName(projectOperations.getTopLevelPackage(moduleName)));
   return dataDictionary;
 }
Ejemplo n.º 14
0
  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();
  }
  @Override
  public void view(
      final JavaType type,
      final String viewName,
      final String identifier,
      final JavaSymbolName fieldName,
      final Dimension height,
      final Dimension width) {

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

    final JavaType viewType =
        new JavaType(viewName.contains(".") ? viewName : WIDGET_PACKAGE + "." + viewName);

    final String layout =
        RequestFactoryUtils.getStringAnnotationValue(typeDetails, ROO_ACTIVITY, "value", "");
    if (!StringUtils.isEmpty(layout)) {
      final DocumentBuilder builder = newDocumentBuilder();
      final String layoutPath =
          pathResolver.getFocusedIdentifier(Path.ROOT, LAYOUT_PATH + SEP + layout + XML_EXTENSION);

      InputStream inputStream = null;
      Document document = null;
      try {
        inputStream = fileManager.getInputStream(layoutPath);
        document = builder.parse(inputStream);
      } catch (final Exception e) {
        LOGGER.severe("Error reading layout XML: " + e.getMessage());
      } finally {
        IOUtils.closeQuietly(inputStream);
      }

      if (document != null) {
        final Element root = document.getDocumentElement();

        final Element viewElem = document.createElement(viewType.getSimpleTypeName());
        final String id = StringUtils.isEmpty(identifier) ? fieldName.getSymbolName() : identifier;
        viewElem.setAttribute("android:id", ID_PREFIX + id);
        viewElem.setAttribute("android:layout_height", height.value());
        viewElem.setAttribute("android:layout_width", width.value());
        root.appendChild(viewElem);

        fileManager.createOrUpdateTextFileIfRequired(
            layoutPath, XmlUtils.nodeToString(document), true);
      }
    }

    final String physicalTypeIdentifier = typeDetails.getDeclaredByMetadataId();

    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    final AnnotationMetadataBuilder annotationBuilder = new AnnotationMetadataBuilder(ROO_VIEW);
    if (!StringUtils.isEmpty(identifier)) {
      annotationBuilder.addStringAttribute("value", identifier);
    }
    annotations.add(annotationBuilder);

    final FieldMetadataBuilder fieldBuilder =
        new FieldMetadataBuilder(physicalTypeIdentifier, 0, annotations, fieldName, viewType);
    typeManagementService.addField(fieldBuilder.build());
  }
  public GwtTemplateDataHolder getMirrorTemplateTypeDetails(
      final ClassOrInterfaceTypeDetails mirroredType,
      final Map<JavaSymbolName, GwtProxyProperty> clientSideTypeMap,
      final String moduleName) {
    final ClassOrInterfaceTypeDetails proxy = gwtTypeService.lookupProxyFromEntity(mirroredType);
    final ClassOrInterfaceTypeDetails request =
        gwtTypeService.lookupRequestFromEntity(mirroredType);
    final JavaPackage topLevelPackage = projectOperations.getTopLevelPackage(moduleName);
    final Map<GwtType, JavaType> mirrorTypeMap =
        GwtUtils.getMirrorTypeMap(mirroredType.getName(), topLevelPackage);
    mirrorTypeMap.put(GwtType.PROXY, proxy.getName());
    mirrorTypeMap.put(GwtType.REQUEST, request.getName());

    final Map<GwtType, ClassOrInterfaceTypeDetails> templateTypeDetailsMap =
        new LinkedHashMap<GwtType, ClassOrInterfaceTypeDetails>();
    final Map<GwtType, String> xmlTemplates = new LinkedHashMap<GwtType, String>();
    for (final GwtType gwtType : GwtType.getMirrorTypes()) {
      if (gwtType.getTemplate() == null) {
        continue;
      }
      TemplateDataDictionary dataDictionary =
          buildMirrorDataDictionary(
              gwtType, mirroredType, proxy, mirrorTypeMap, clientSideTypeMap, moduleName);
      gwtType.dynamicallyResolveFieldsToWatch(clientSideTypeMap);
      gwtType.dynamicallyResolveMethodsToWatch(
          mirroredType.getName(), clientSideTypeMap, topLevelPackage);
      templateTypeDetailsMap.put(
          gwtType,
          getTemplateDetails(
              dataDictionary, gwtType.getTemplate(), mirrorTypeMap.get(gwtType), moduleName));

      if (gwtType.isCreateUiXml()) {
        dataDictionary =
            buildMirrorDataDictionary(
                gwtType, mirroredType, proxy, mirrorTypeMap, clientSideTypeMap, moduleName);
        final String contents =
            getTemplateContents(gwtType.getTemplate() + "UiXml", dataDictionary);
        xmlTemplates.put(gwtType, contents);
      }
    }

    final Map<String, String> xmlMap = new LinkedHashMap<String, String>();
    final List<ClassOrInterfaceTypeDetails> typeDetails =
        new ArrayList<ClassOrInterfaceTypeDetails>();
    for (final GwtProxyProperty proxyProperty : clientSideTypeMap.values()) {
      if (!proxyProperty.isCollection() || proxyProperty.isCollectionOfProxy()) {
        continue;
      }

      TemplateDataDictionary dataDictionary = TemplateDictionary.create();
      dataDictionary.setVariable("packageName", GwtPath.MANAGED_UI.packageName(topLevelPackage));
      dataDictionary.setVariable(
          "scaffoldUiPackage", GwtPath.SCAFFOLD_UI.packageName(topLevelPackage));
      final JavaType collectionTypeImpl =
          getCollectionImplementation(proxyProperty.getPropertyType());
      addImport(dataDictionary, collectionTypeImpl);
      addImport(dataDictionary, proxyProperty.getPropertyType());

      final String collectionType = proxyProperty.getPropertyType().getSimpleTypeName();
      final String boundCollectionType =
          proxyProperty.getPropertyType().getParameters().get(0).getSimpleTypeName();

      dataDictionary.setVariable("collectionType", collectionType);
      dataDictionary.setVariable("collectionTypeImpl", collectionTypeImpl.getSimpleTypeName());
      dataDictionary.setVariable("boundCollectionType", boundCollectionType);

      final JavaType collectionEditorType =
          new JavaType(
              GwtPath.MANAGED_UI.packageName(topLevelPackage)
                  + "."
                  + boundCollectionType
                  + collectionType
                  + "Editor");
      typeDetails.add(
          getTemplateDetails(dataDictionary, "CollectionEditor", collectionEditorType, moduleName));

      dataDictionary = TemplateDictionary.create();
      dataDictionary.setVariable("packageName", GwtPath.MANAGED_UI.packageName(topLevelPackage));
      dataDictionary.setVariable(
          "scaffoldUiPackage", GwtPath.SCAFFOLD_UI.packageName(topLevelPackage));
      dataDictionary.setVariable("collectionType", collectionType);
      dataDictionary.setVariable("collectionTypeImpl", collectionTypeImpl.getSimpleTypeName());
      dataDictionary.setVariable("boundCollectionType", boundCollectionType);
      addImport(dataDictionary, proxyProperty.getPropertyType());

      final String contents = getTemplateContents("CollectionEditor" + "UiXml", dataDictionary);
      final String packagePath =
          projectOperations
              .getPathResolver()
              .getFocusedIdentifier(
                  Path.SRC_MAIN_JAVA, GwtPath.MANAGED_UI.getPackagePath(topLevelPackage));
      xmlMap.put(
          packagePath + "/" + boundCollectionType + collectionType + "Editor.ui.xml", contents);
    }

    return new GwtTemplateDataHolder(templateTypeDetailsMap, xmlTemplates, typeDetails, xmlMap);
  }
  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;
  }
Ejemplo n.º 18
0
 /**
  * Determines whether the presented entity is a test class or not.
  *
  * @param entity the type to test
  * @return true if the entity is likely not a test class, otherwise false
  */
 public static boolean isEntityReasonablyNamed(final JavaType entity) {
   Validate.notNull(entity, "Entity required");
   return !entity.getSimpleTypeName().startsWith("Test")
       && !entity.getSimpleTypeName().endsWith("TestCase")
       && !entity.getSimpleTypeName().endsWith("Test");
 }
  /** @return the find (by ID) method (may return null) */
  public MethodMetadata getFindMethod() {
    if ("".equals(crudAnnotationValues.getFindMethod())) {
      return null;
    }

    // Method definition to find or build
    final String idFieldName = identifierField.getFieldName().getSymbolName();
    final JavaSymbolName methodName =
        new JavaSymbolName(crudAnnotationValues.getFindMethod() + destination.getSimpleTypeName());
    final JavaType parameterType = identifierField.getFieldType();
    final List<JavaSymbolName> parameterNames = Arrays.asList(new JavaSymbolName(idFieldName));
    final JavaType returnType = destination;

    // Locate user-defined method
    final MethodMetadata userMethod = getGovernorMethod(methodName, parameterType);
    if (userMethod != null) {
      Assert.isTrue(
          userMethod.getReturnType().equals(returnType),
          "Method '"
              + methodName
              + "' on '"
              + returnType
              + "' must return '"
              + returnType.getNameIncludingTypeParameters()
              + "'");
      return userMethod;
    }

    // Create method
    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    if (isGaeEnabled) {
      addTransactionalAnnotation(annotations);
    }

    final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();

    if (JavaType.STRING.equals(identifierField.getFieldType())) {
      bodyBuilder.appendFormalLine(
          "if (" + idFieldName + " == null || " + idFieldName + ".length() == 0) return null;");
    } else if (!identifierField.getFieldType().isPrimitive()) {
      bodyBuilder.appendFormalLine("if (" + idFieldName + " == null) return null;");
    }

    bodyBuilder.appendFormalLine(
        "return "
            + ENTITY_MANAGER_METHOD_NAME
            + "().find("
            + returnType.getSimpleTypeName()
            + ".class, "
            + idFieldName
            + ");");

    final MethodMetadataBuilder methodBuilder =
        new MethodMetadataBuilder(
            getId(),
            Modifier.PUBLIC | Modifier.STATIC,
            methodName,
            returnType,
            AnnotatedJavaType.convertFromJavaTypes(parameterType),
            parameterNames,
            bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    return methodBuilder.build();
  }