Esempio n. 1
0
  /**
   * Returns whether the given method is a 'getter' method.
   *
   * @param method a parameterless method that returns a non-void
   * @return the property name
   */
  protected String isGetter(final Method<?> method) {

    String methodName = method.getName();
    String propertyName;

    if (methodName.startsWith(ClassUtils.JAVABEAN_GET_PREFIX)) {
      propertyName = methodName.substring(ClassUtils.JAVABEAN_GET_PREFIX.length());

    } else if (methodName.startsWith(ClassUtils.JAVABEAN_IS_PREFIX)
        && boolean.class.equals(method.getQualifiedReturnType())) {

      // As per section 8.3.2 (Boolean properties) of The JavaBeans API specification, 'is'
      // only applies to boolean (little 'b')

      propertyName = methodName.substring(ClassUtils.JAVABEAN_IS_PREFIX.length());
    } else {
      return null;
    }

    if (!StringUtils.isCapitalized(propertyName)) {
      return null;
    }

    return StringUtils.decapitalize(propertyName);
  }
Esempio n. 2
0
  /**
   * Gets the private field representing the given <code>propertyName</code> within the given class.
   *
   * @return the private Field for this propertyName, or null if no such field (should not throw
   *     NoSuchFieldException)
   */
  protected Field<?> getPrivateField(final FieldHolder<?> fieldHolder, final String propertyName) {
    if (this.privateFieldConvention != null) {
      // Determine field name based on convention. MessageFormat arguments are:
      //
      // {0} = dateOfBirth, surname
      // {1} = DateOfBirth, Surname

      String[] arguments = new String[] {propertyName, StringUtils.capitalize(propertyName)};
      String fieldName;

      synchronized (this.privateFieldConvention) {
        fieldName =
            this.privateFieldConvention.format(arguments, new StringBuffer(), null).toString();
      }

      return fieldHolder.getField(fieldName);
    }

    Field<?> field = fieldHolder.getField(propertyName);

    // FORGE-402: support fields starting with capital letter

    if (field == null && !StringUtils.isCapitalized(propertyName)) {
      field = fieldHolder.getField(StringUtils.capitalize(propertyName));
    }

    return field;
  }
Esempio n. 3
0
  /** Generates the navigation menu based on scaffolded entities. */
  protected Resource<?> generateNavigation(final String targetDir) throws IOException {
    WebResourcesFacet web = this.project.getFacet(WebResourcesFacet.class);
    HtmlTag unorderedList = new HtmlTag("ul");

    ResourceFilter filter =
        new ResourceFilter() {
          @Override
          public boolean accept(Resource<?> resource) {
            FileResource<?> file = (FileResource<?>) resource;

            if (!file.isDirectory()
                || file.getName().equals("resources")
                || file.getName().equals("WEB-INF")
                || file.getName().equals("META-INF")) {
              return false;
            }

            return true;
          }
        };

    for (Resource<?> resource : web.getWebResource(targetDir + "/").listResources(filter)) {
      HtmlOutcomeTargetLink outcomeTargetLink = new HtmlOutcomeTargetLink();
      String outcome =
          targetDir.isEmpty() || targetDir.startsWith("/") ? targetDir : "/" + targetDir;
      outcomeTargetLink.putAttribute("outcome", outcome + "/" + resource.getName() + "/search");
      outcomeTargetLink.setValue(StringUtils.uncamelCase(resource.getName()));

      HtmlTag listItem = new HtmlTag("li");
      listItem.getChildren().add(outcomeTargetLink);
      unorderedList.getChildren().add(listItem);
    }

    Writer writer = new IndentedWriter(new StringWriter(), this.navigationTemplateIndent);
    unorderedList.write(writer);

    Map<Object, Object> context = CollectionUtils.newHashMap();
    context.put("appName", StringUtils.uncamelCase(this.project.getRoot().getName()));
    context.put("navigation", writer.toString().trim());
    context.put("targetDir", targetDir);

    if (this.navigationTemplate == null) {
      loadTemplates();
    }

    try {
      return ScaffoldUtil.createOrOverwrite(
          (FileResource<?>) getTemplateStrategy().getDefaultTemplate(),
          FreemarkerTemplateProcessor.processTemplate(context, navigationTemplate));
    } finally {
      writer.close();
    }
  }
Esempio n. 4
0
  /**
   * Returns whether the given method is a 'setter' method.
   *
   * @param method a single-parametered method. May return non-void (ie. for Fluent interfaces)
   * @return the property name
   */
  protected String isSetter(final Method<?> method) {
    String methodName = method.getName();

    if (!methodName.startsWith(ClassUtils.JAVABEAN_SET_PREFIX)) {
      return null;
    }

    String propertyName = methodName.substring(ClassUtils.JAVABEAN_SET_PREFIX.length());

    if (!StringUtils.isCapitalized(propertyName)) {
      return null;
    }

    return StringUtils.decapitalize(propertyName);
  }
Esempio n. 5
0
 protected void createInitializers(final JavaClassSource entity)
     throws FacetNotFoundException, FileNotFoundException {
   boolean dirtyBit = false;
   for (FieldSource<JavaClassSource> field : entity.getFields()) {
     if (field.hasAnnotation(OneToOne.class)) {
       AnnotationSource<JavaClassSource> oneToOne = field.getAnnotation(OneToOne.class);
       if (oneToOne.getStringValue("mappedBy") == null
           && oneToOne.getStringValue("cascade") == null) {
         oneToOne.setEnumValue("cascade", CascadeType.ALL);
         dirtyBit = true;
       }
       String methodName = "new" + StringUtils.capitalize(field.getName());
       if (!entity.hasMethodSignature(methodName)) {
         entity
             .addMethod()
             .setName(methodName)
             .setReturnTypeVoid()
             .setPublic()
             .setBody("this." + field.getName() + " = new " + field.getType().getName() + "();");
         dirtyBit = true;
       }
     }
   }
   for (MethodSource<JavaClassSource> method : entity.getMethods()) {
     if (method.hasAnnotation(OneToOne.class)) {
       AnnotationSource<JavaClassSource> oneToOne = method.getAnnotation(OneToOne.class);
       if (oneToOne.getStringValue("mappedBy") == null
           && oneToOne.getStringValue("cascade") == null) {
         oneToOne.setEnumValue("cascade", CascadeType.ALL);
         dirtyBit = true;
       }
       String fieldName = StringUtils.camelCase(method.getName().substring(3));
       String methodName = "new" + StringUtils.capitalize(fieldName);
       if (!entity.hasMethodSignature(methodName)) {
         entity
             .addMethod()
             .setName(methodName)
             .setReturnTypeVoid()
             .setPublic()
             .setBody("this." + fieldName + " = new " + method.getReturnType().getName() + "();");
         dirtyBit = true;
       }
     }
   }
   if (dirtyBit) {
     this.project.getFacet(JavaSourceFacet.class).saveJavaSource(entity);
   }
 }
  public StaticXmlWidget processWidget(
      StaticXmlWidget widget,
      String elementName,
      Map<String, String> attributes,
      StaticXmlMetawidget metawidget) {

    if (widget instanceof ValueHolder) {

      // (do not overwrite existing, if any)

      if (widget.getAttribute("id") == null) {

        ValueHolder valueWidget = (ValueHolder) widget;
        String valueExpression = valueWidget.getValue();

        if (valueExpression != null && !"".equals(valueExpression)) {
          valueExpression = StaticFacesUtils.unwrapExpression(valueExpression);
          widget.putAttribute(
              "id", StringUtils.camelCase(valueExpression, StringUtils.SEPARATOR_DOT_CHAR));
        }
      }
    }

    return widget;
  }
  public boolean setValue(Object value, View view) {

    // TextView
    //
    // (don't use instanceof, because CheckBox instanceof TextView)

    if (TextView.class.equals(view.getClass())) {
      ((TextView) view).setText(StringUtils.quietValueOf(value));
      return true;
    }

    // Unknown

    return false;
  }
  @Override
  protected ComponentContainer createSectionWidget(
      ComponentContainer previousSectionWidget,
      String section,
      Map<String, String> attributes,
      ComponentContainer container,
      VaadinMetawidget metawidget) {

    TabSheet tabSheet;

    // Whole new tabbed pane?

    if (previousSectionWidget == null) {

      tabSheet = new TabSheet();
      tabSheet.setWidth("100%");

      // Add to parent container

      Map<String, String> tabbedPaneAttributes = CollectionUtils.newHashMap();
      tabbedPaneAttributes.put(LABEL, "");
      tabbedPaneAttributes.put(LARGE, TRUE);
      getDelegate().layoutWidget(tabSheet, PROPERTY, tabbedPaneAttributes, container, metawidget);
    } else {
      tabSheet = (TabSheet) previousSectionWidget.getParent();
    }

    // New tab

    Panel tabPanel = new Panel();

    // Tab name (possibly localized)

    String localizedSection = metawidget.getLocalizedKey(StringUtils.camelCase(section));

    if (localizedSection == null) {
      localizedSection = section;
    }

    tabSheet.addTab(tabPanel, localizedSection, null);

    return tabPanel;
  }
Esempio n. 9
0
  private void setPrimaryKeyMetaData(Map<Object, Object> context, final JavaClassSource entity) {
    String pkName = "id";
    String pkType = "Long";
    String nullablePkType = "Long";
    for (MemberSource<JavaClassSource, ?> m : entity.getMembers()) {
      if (m.hasAnnotation(Id.class)) {
        if (m instanceof Field) {
          Field<?> field = (Field<?>) m;
          pkName = field.getName();
          pkType = field.getType().getQualifiedName();
          nullablePkType = pkType;
          break;
        }

        MethodSource<?> method = (MethodSource<?>) m;
        pkName = method.getName().substring(3);
        if (method.getName().startsWith("get")) {
          pkType = method.getReturnType().getQualifiedName();
        } else {
          pkType = method.getParameters().get(0).getType().getQualifiedName();
        }
        nullablePkType = pkType;
        break;
      }
    }

    if (Types.isJavaLang(pkType)) {
      nullablePkType = Types.toSimpleName(pkType);
    } else if ("int".equals(pkType)) {
      nullablePkType = Integer.class.getSimpleName();
    } else if ("short".equals(pkType)) {
      nullablePkType = Short.class.getSimpleName();
    } else if ("byte".equals(pkType)) {
      nullablePkType = Byte.class.getSimpleName();
    } else if ("long".equals(pkType)) {
      nullablePkType = Long.class.getSimpleName();
    }

    context.put("primaryKey", pkName);
    context.put("primaryKeyCC", StringUtils.capitalize(pkName));
    context.put("primaryKeyType", pkType);
    context.put("nullablePrimaryKeyType", nullablePkType);
  }
  @Override
  protected void addSectionWidget(
      String section, int level, JComponent container, SwingMetawidget metawidget) {

    JPanel separatorPanel = new JPanel();
    separatorPanel.setBorder(BORDER_SECTION);
    separatorPanel.setLayout(new java.awt.GridBagLayout());
    separatorPanel.setOpaque(false);

    // Section name (possibly localized)

    String localizedSection = metawidget.getLocalizedKey(StringUtils.camelCase(section));

    if (localizedSection == null) {
      localizedSection = section;
    }

    GridBagConstraints labelConstraints = new GridBagConstraints();

    GridBagConstraints separatorConstraints = new GridBagConstraints();
    separatorConstraints.fill = GridBagConstraints.HORIZONTAL;
    separatorConstraints.weightx = 1.0;

    if (mAlignment == SwingConstants.RIGHT) {
      separatorConstraints.gridx = 0;
      labelConstraints.gridx = 1;
      labelConstraints.insets = INSETS_SECTION_LABEL_RIGHT;
    } else {
      labelConstraints.insets = INSETS_SECTION_LABEL_LEFT;
    }

    separatorPanel.add(new JLabel(localizedSection), labelConstraints);
    separatorPanel.add(new JSeparator(SwingConstants.HORIZONTAL), separatorConstraints);

    // Add to parent container

    Map<String, String> separatorPanelAttributes = CollectionUtils.newHashMap();
    separatorPanelAttributes.put(LABEL, "");
    separatorPanelAttributes.put(WIDE, TRUE);
    getDelegate()
        .layoutWidget(separatorPanel, PROPERTY, separatorPanelAttributes, container, metawidget);
  }
Esempio n. 11
0
  @Override
  public StaticJavaWidget buildWidget(
      String elementName, Map<String, String> attributes, StaticJavaMetawidget metawidget) {
    // Drill down

    if (ENTITY.equals(elementName)) {
      return null;
    }

    // Suppress

    if (TRUE.equals(attributes.get(HIDDEN))) {
      return new StaticJavaStub();
    }

    String type = WidgetBuilderUtils.getActualClassOrType(attributes);
    Class<?> clazz = ClassUtils.niceForName(type);
    String name = attributes.get(NAME);

    // String

    if (String.class.equals(clazz)) {
      StaticJavaStub toReturn = new StaticJavaStub();
      toReturn
          .getChildren()
          .add(
              new JavaStatement(
                  "String " + name + " = this.search.get" + StringUtils.capitalize(name) + "()"));
      JavaStatement ifNotEmpty =
          new JavaStatement("if (" + name + " != null && !\"\".equals(" + name + "))");
      ifNotEmpty
          .getChildren()
          .add(
              new JavaStatement(
                  "predicatesList.add(builder.like(root.<String>get(\""
                      + name
                      + "\"), '%' + "
                      + name
                      + " + '%'))"));
      toReturn.getChildren().add(ifNotEmpty);
      return toReturn;
    }

    // int

    if (int.class.equals(clazz)) {
      StaticJavaStub toReturn = new StaticJavaStub();
      toReturn
          .getChildren()
          .add(
              new JavaStatement(
                  "int " + name + " = this.search.get" + StringUtils.capitalize(name) + "()"));
      JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != 0)");
      ifNotEmpty
          .getChildren()
          .add(
              new JavaStatement(
                  "predicatesList.add(builder.equal(root.get(\"" + name + "\")," + name + "))"));
      toReturn.getChildren().add(ifNotEmpty);
      return toReturn;
    }

    // Lookup

    if (attributes.containsKey(FACES_LOOKUP)) {
      StaticJavaStub toReturn = new StaticJavaStub();
      JavaStatement getValue =
          new JavaStatement(
              ClassUtils.getSimpleName(type)
                  + " "
                  + name
                  + " = this.search.get"
                  + StringUtils.capitalize(name)
                  + "()");
      getValue.putImport(type);
      toReturn.getChildren().add(getValue);
      JavaStatement ifNotEmpty =
          new JavaStatement("if (" + name + " != null && " + name + ".getId() != null)");
      ifNotEmpty
          .getChildren()
          .add(
              new JavaStatement(
                  "predicatesList.add(builder.equal(root.get(\"" + name + "\")," + name + "))"));
      toReturn.getChildren().add(ifNotEmpty);
      return toReturn;
    }

    // We tried searching against N_TO_MANY relationships, but had the following problems:
    //
    // 1. Difficult to make JPA Criteria Builder search for 'a Set having all of the following
    // items'. For 'a Set
    // having the following item' can do:
    // predicatesList.add(root.join("customers").in(this.search.getCustomer()));
    // 2. Cumbersome to have a new class for this.search that only has a single Customer, as opposed
    // to a Set
    // 3. Difficult to make JSF's h:selectOne* bind to a Set
    // 4. Difficult to make JSF's h:selectMany* appear as a single item dropdown
    //
    // So we've left it out for now

    return new StaticJavaStub();
  }
Esempio n. 12
0
    /**
     * Parses the given literal value into the given returnType. Supports all standard annotation
     * types (JLS 9.7).
     */
    private Object parse(String literalValue, Class<?> returnType) throws ClassNotFoundException {
      // Primitives

      if (byte.class.equals(returnType)) {
        return Byte.valueOf(literalValue);
      }
      if (short.class.equals(returnType)) {
        return Short.valueOf(literalValue);
      }
      if (int.class.equals(returnType)) {
        return Integer.valueOf(literalValue);
      }
      if (long.class.equals(returnType)) {
        String valueToUse = literalValue;
        if (valueToUse.endsWith("l") || valueToUse.endsWith("L")) {
          valueToUse = valueToUse.substring(0, valueToUse.length() - 1);
        }
        return Long.valueOf(valueToUse);
      }
      if (float.class.equals(returnType)) {
        String valueToUse = literalValue;
        if (valueToUse.endsWith("f") || valueToUse.endsWith("F")) {
          valueToUse = valueToUse.substring(0, valueToUse.length() - 1);
        }
        return Float.valueOf(valueToUse);
      }
      if (double.class.equals(returnType)) {
        String valueToUse = literalValue;
        if (valueToUse.endsWith("d") || valueToUse.endsWith("D")) {
          valueToUse = literalValue.substring(0, valueToUse.length() - 1);
        }
        return Double.valueOf(valueToUse);
      }
      if (boolean.class.equals(returnType)) {
        return Boolean.valueOf(literalValue);
      }
      if (char.class.equals(returnType)) {
        return Character.valueOf(literalValue.charAt(1));
      }

      // Arrays

      if (returnType.isArray()) {
        String[] values = literalValue.substring(1, literalValue.length() - 1).split(",");
        int length = values.length;
        Class<?> componentType = returnType.getComponentType();
        Object array = Array.newInstance(componentType, length);

        for (int loop = 0; loop < length; loop++) {
          Array.set(array, loop, parse(values[loop], componentType));
        }

        return array;
      }

      // Enums

      if (returnType.isEnum()) {
        Enum<?>[] constants = (Enum<?>[]) returnType.getEnumConstants();

        String valueToUse = StringUtils.substringAfterLast(literalValue, '.');

        for (Enum<?> inst : constants) {
          if (inst.name().equals(valueToUse)) {
            return inst;
          }
        }

        return null;
      }

      // Strings

      if (String.class.equals(returnType)) {
        return literalValue.substring(1, literalValue.length() - 1);
      }

      // Classes

      if (Class.class.equals(returnType)) {
        String resolvedType = StringUtils.substringBefore(literalValue, ".class");
        resolvedType =
            ((JavaSource<?>) this.annotationSource.getOrigin()).resolveType(resolvedType);
        return Class.forName(resolvedType);
      }

      // Annotations

      if (Annotation.class.isAssignableFrom(returnType)) {
        String resolvedType = StringUtils.substringAfter(literalValue, "@");
        resolvedType =
            ((JavaSource<?>) this.annotationSource.getOrigin()).resolveType(resolvedType);

        return AnnotationProxy.newInstance(this.annotationSource);
      }

      // Unknown

      throw new UnsupportedOperationException(returnType.getSimpleName());
    }
  @Override
  public String convertForward(SV value) {

    return StringUtils.quietValueOf(value);
  }
  public String getAsString(FacesContext context, UIComponent component, Object value) {

    return StringUtils.quietValueOf(value);
  }
Esempio n. 15
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  private List<Resource<?>> generateFromEntity(
      String targetDir, final Resource<?> template, final JavaClassSource entity) {
    resetMetaWidgets();

    // Track the list of resources generated

    List<Resource<?>> result = new ArrayList<>();
    try {
      JavaSourceFacet java = this.project.getFacet(JavaSourceFacet.class);
      WebResourcesFacet web = this.project.getFacet(WebResourcesFacet.class);
      JPAFacet<PersistenceCommonDescriptor> jpa = this.project.getFacet(JPAFacet.class);

      loadTemplates();
      Map<Object, Object> context = CollectionUtils.newHashMap();
      context.put("entity", entity);
      String ccEntity = StringUtils.decapitalize(entity.getName());
      context.put("ccEntity", ccEntity);
      context.put("rmEntity", ccEntity + "ToDelete");
      setPrimaryKeyMetaData(context, entity);

      // Prepare qbeMetawidget
      this.qbeMetawidget.setPath(entity.getQualifiedName());
      StringWriter stringWriter = new StringWriter();
      this.qbeMetawidget.write(stringWriter, this.backingBeanTemplateQbeMetawidgetIndent);
      context.put("qbeMetawidget", stringWriter.toString().trim());

      // Prepare removeEntityMetawidget
      this.rmEntityMetawidget.setPath(entity.getQualifiedName());
      stringWriter = new StringWriter();
      this.rmEntityMetawidget.write(stringWriter, this.backingBeanTemplateRmEntityMetawidgetIndent);
      context.put("rmEntityMetawidget", stringWriter.toString().trim());

      // Prepare Java imports
      Set<String> qbeMetawidgetImports = this.qbeMetawidget.getImports();
      Set<String> rmEntityMetawidgetImports = this.rmEntityMetawidget.getImports();
      Set<String> metawidgetImports = CollectionUtils.newHashSet();
      metawidgetImports.addAll(qbeMetawidgetImports);
      metawidgetImports.addAll(rmEntityMetawidgetImports);
      metawidgetImports.remove(entity.getQualifiedName());
      context.put(
          "metawidgetImports",
          CollectionUtils.toString(metawidgetImports, ";\r\nimport ", true, false));

      // Prepare JPA Persistence Unit
      context.put("persistenceUnitName", jpa.getConfig().getOrCreatePersistenceUnit().getName());

      // Create the Backing Bean for this entity
      JavaClassSource viewBean =
          Roaster.parse(
              JavaClassSource.class,
              FreemarkerTemplateProcessor.processTemplate(context, this.backingBeanTemplate));
      viewBean.setPackage(java.getBasePackage() + "." + DEFAULT_FACES_PACKAGE);
      result.add(
          ScaffoldUtil.createOrOverwrite(java.getJavaResource(viewBean), viewBean.toString()));

      // Set new context for view generation
      context = getTemplateContext(targetDir, template);
      String beanName = StringUtils.decapitalize(viewBean.getName());
      context.put("beanName", beanName);
      context.put("ccEntity", ccEntity);
      context.put("entityName", StringUtils.uncamelCase(entity.getName()));
      setPrimaryKeyMetaData(context, entity);

      // Prepare entityMetawidget
      this.entityMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + "." + ccEntity));
      this.entityMetawidget.setPath(entity.getQualifiedName());
      this.entityMetawidget.setReadOnly(false);
      this.entityMetawidget.setStyle(null);

      // Generate create
      writeEntityMetawidget(
          context, this.createTemplateEntityMetawidgetIndent, this.createTemplateNamespaces);

      result.add(
          ScaffoldUtil.createOrOverwrite(
              web.getWebResource(targetDir + "/" + ccEntity + "/create.xhtml"),
              FreemarkerTemplateProcessor.processTemplate(context, this.createTemplate)));

      // Generate view
      this.entityMetawidget.setReadOnly(true);
      writeEntityMetawidget(
          context, this.viewTemplateEntityMetawidgetIndent, this.viewTemplateNamespaces);

      result.add(
          ScaffoldUtil.createOrOverwrite(
              web.getWebResource(targetDir + "/" + ccEntity + "/view.xhtml"),
              FreemarkerTemplateProcessor.processTemplate(context, this.viewTemplate)));

      // Generate search
      this.searchMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + ".example"));
      this.searchMetawidget.setPath(entity.getQualifiedName());
      this.beanMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + ".pageItems"));
      this.beanMetawidget.setPath(viewBean.getQualifiedName() + "/pageItems");
      writeSearchAndBeanMetawidget(
          context,
          this.searchTemplateSearchMetawidgetIndent,
          this.searchTemplateBeanMetawidgetIndent,
          this.searchTemplateNamespaces);

      result.add(
          ScaffoldUtil.createOrOverwrite(
              web.getWebResource(targetDir + "/" + ccEntity + "/search.xhtml"),
              FreemarkerTemplateProcessor.processTemplate(context, this.searchTemplate)));

      // Generate navigation
      result.add(generateNavigation(targetDir));

      // Need ViewUtils and forge.taglib.xml for forgeview:asList
      JavaClassSource viewUtils =
          Roaster.parse(
              JavaClassSource.class,
              FreemarkerTemplateProcessor.processTemplate(context, this.viewUtilsTemplate));
      viewUtils.setPackage(viewBean.getPackage());
      result.add(
          ScaffoldUtil.createOrOverwrite(java.getJavaResource(viewUtils), viewUtils.toString()));

      context.put("viewPackage", viewBean.getPackage());
      result.add(
          ScaffoldUtil.createOrOverwrite(
              web.getWebResource("WEB-INF/classes/META-INF/forge.taglib.xml"),
              FreemarkerTemplateProcessor.processTemplate(context, this.taglibTemplate)));

      createInitializers(entity);
    } catch (Exception e) {
      throw new RuntimeException("Error generating default scaffolding: " + e.getMessage(), e);
    }
    return result;
  }