Exemplo n.º 1
0
  /** {@inheritDoc} */
  public Object execute(CommandLine commandLine) throws Exception {
    String project = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    String propertiesOption = commandLine.getValue(Options.PROPERTIES_OPTION);
    String[] properties = {};
    if (propertiesOption != null) {
      properties = StringUtils.split(propertiesOption, ',');
    }
    int offset = getOffset(commandLine);

    // validate supplied fields.
    ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);
    IType type = TypeUtils.getType(src, offset);
    for (int ii = 0; ii < properties.length; ii++) {
      if (!type.getField(properties[ii]).exists()) {
        throw new RuntimeException(
            Services.getMessage("field.not.found", properties[ii], type.getElementName()));
      }
    }

    // check if constructor already exists.
    IMethod method = null;
    if (properties.length == 0) {
      method = type.getMethod(type.getElementName(), null);
    } else {
      String[] fieldSigs = new String[properties.length];
      for (int ii = 0; ii < properties.length; ii++) {
        fieldSigs[ii] = type.getField(properties[ii]).getTypeSignature();
      }
      method = type.getMethod(type.getElementName(), fieldSigs);
    }
    if (method.exists()) {
      throw new RuntimeException(
          Services.getMessage(
              "constructor.already.exists",
              type.getElementName() + " (" + buildParams(type, properties) + ")"));
    }

    // find the sibling to insert before.
    IJavaElement sibling = null;
    IMethod[] methods = type.getMethods();
    for (int ii = 0; ii < methods.length; ii++) {
      if (methods[ii].isConstructor()) {
        sibling = ii < methods.length - 1 ? methods[ii + 1] : null;
      }
    }
    // insert before any other methods or inner classes if any.
    if (sibling == null) {
      if (methods.length > 0) {
        sibling = methods[0];
      } else {
        IType[] types = type.getTypes();
        sibling = types != null && types.length > 0 ? types[0] : null;
      }
    }

    HashMap<String, Object> values = new HashMap<String, Object>();
    values.put("type", type.getElementName());
    boolean hasProperties = properties != null && properties.length > 0;
    values.put("fields", hasProperties ? properties : null);
    values.put("params", hasProperties ? buildParams(type, properties) : StringUtils.EMPTY);

    PluginResources resources = (PluginResources) Services.getPluginResources(PluginResources.NAME);
    String constructor = TemplateUtils.evaluate(resources, TEMPLATE, values);
    Position position =
        TypeUtils.getPosition(type, type.createMethod(constructor, sibling, false, null));
    JavaUtils.format(
        src, CodeFormatter.K_COMPILATION_UNIT, position.getOffset(), position.getLength());

    return null;
  }