/** Create fields for injections inside main class */
  protected void generateFields() {
    for (Iterator<Element> iterator = mElements.iterator(); iterator.hasNext(); ) {
      Element element = iterator.next();

      if (!element.used) {
        iterator.remove();
        continue;
      }

      // remove duplicate field
      PsiField[] fields = mClass.getFields();
      boolean duplicateField = false;
      for (PsiField field : fields) {
        String name = field.getName();
        if (name != null && name.equals(element.getFieldName())) {
          duplicateField = true;
          break;
        }
      }

      if (duplicateField) {
        iterator.remove();
        continue;
      }

      mClass.add(
          mFactory.createFieldFromText(
              "private " + element.name + " " + element.getFieldName() + ";", mClass));
    }
  }
  private static PsiField createField(
      PsiLocalVariable local, PsiType forcedType, String fieldName, boolean includeInitializer) {
    @NonNls StringBuilder pattern = new StringBuilder();
    pattern.append("private int ");
    pattern.append(fieldName);
    if (local.getInitializer() == null) {
      includeInitializer = false;
    }
    if (includeInitializer) {
      pattern.append("=0");
    }
    pattern.append(";");
    final Project project = local.getProject();
    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    try {
      PsiField field = factory.createFieldFromText(pattern.toString(), null);

      field.getTypeElement().replace(factory.createTypeElement(forcedType));
      if (includeInitializer) {
        PsiExpression initializer =
            RefactoringUtil.convertInitializerToNormalExpression(
                local.getInitializer(), forcedType);
        field.getInitializer().replace(initializer);
      }

      for (PsiAnnotation annotation : local.getModifierList().getAnnotations()) {
        field.getModifierList().add(annotation.copy());
      }
      return field;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  private void buildDelegate() {
    final PsiManager manager = sourceClass.getManager();
    final PsiElementFactory factory =
        JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    @NonNls final StringBuilder fieldBuffer = new StringBuilder();
    final String delegateVisibility = calculateDelegateVisibility();
    if (delegateVisibility.length() > 0) fieldBuffer.append(delegateVisibility).append(' ');
    fieldBuffer.append("final ");
    final String fullyQualifiedName = getQualifiedName();
    fieldBuffer.append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append(' ');
    fieldBuffer.append(delegateFieldName);
    fieldBuffer.append(" = new ").append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append('(');
    if (requiresBackpointer) {
      fieldBuffer.append("this");
    }

    fieldBuffer.append(");");
    try {
      final String fieldString = fieldBuffer.toString();
      final PsiField field = factory.createFieldFromText(fieldString, sourceClass);
      final PsiElement newField = sourceClass.add(field);
      codeStyleManager.reformat(
          JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(newField));
    } catch (IncorrectOperationException e) {
      logger.error(e);
    }
  }
Example #4
0
  @Override
  protected void run() throws Throwable {
    int fieldCount = 0;
    PsiMethod initViewMethod = getInitView();
    StringBuilder methodBuild = new StringBuilder("private void initView() {");
    for (ViewPart viewPart : viewPartList) {
      if (!viewPart.isSelected() || fieldExist(viewPart)) {
        continue;
      }
      mClass.add(mFactory.createFieldFromText(viewPart.getDeclareString(false, false), mClass));
      if (initViewMethod != null) {
        initViewMethod
            .getBody()
            .add(mFactory.createStatementFromText(viewPart.getFindViewString(), mClass));
      } else {
        if (isViewHolder) {
          methodBuild.append(viewPart.getFindViewStringForViewHolder("convertView"));
        } else if (isAddRootView && !TextUtils.isEmpty(rootViewStr)) {
          methodBuild.append(viewPart.getFindViewStringWithRootView(rootViewStr));
        } else {
          methodBuild.append(viewPart.getFindViewString());
        }
        fieldCount++;
      }
    }
    methodBuild.append("}");
    if (fieldCount > 0) {
      mClass.add(mFactory.createMethodFromText(methodBuild.toString(), mClass));
    }
    addInitViewAfterOnCreate();

    // reformat class
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject);
    styleManager.optimizeImports(psiFile);
    styleManager.shortenClassReferences(mClass);
    new ReformatCodeProcessor(mProject, mClass.getContainingFile(), null, false)
        .runWithoutProgress();
  }
  @Override
  public void generate() {
    PsiClass butterKnifeInjectAnnotation =
        JavaPsiFacade.getInstance(prj)
            .findClass("butterknife.InjectView", new EverythingGlobalScope(prj));
    if (butterKnifeInjectAnnotation == null) return;
    for (AndroidView v : mIds) {
      String sb =
          "@butterknife.InjectView("
              + v.getId()
              + ")"
              + " "
              + v.getName()
              + " "
              + v.getFieldName()
              + ";";
      cls.add(elementFactory.createFieldFromText(sb, cls));
    }

    JavaCodeStyleManager.getInstance(prj).shortenClassReferences(cls);
    new ReformatAndOptimizeImportsProcessor(prj, cls.getContainingFile(), false)
        .runWithoutProgress();
  }
    @Override
    protected void doFix(Project project, ProblemDescriptor descriptor) {
      final PsiElement element = descriptor.getPsiElement();
      final PsiClass aClass = ClassUtils.getContainingStaticClass(element);
      if (aClass == null) {
        return;
      }
      final PsiElement parent = element.getParent();
      if (!(parent instanceof PsiReferenceExpression)) {
        return;
      }
      final PsiReferenceExpression methodExpression = (PsiReferenceExpression) parent;
      final PsiElement grandParent = methodExpression.getParent();
      if (!(grandParent instanceof PsiMethodCallExpression)) {
        return;
      }
      final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) grandParent;
      final PsiExpressionList list = methodCallExpression.getArgumentList();
      final PsiExpression[] expressions = list.getExpressions();
      @NonNls
      final StringBuilder fieldText =
          new StringBuilder(
              "private static final java.util.regex.Pattern PATTERN = java.util.regex.Pattern.compile(");
      final int expressionsLength = expressions.length;
      if (expressionsLength > 0) {
        fieldText.append(expressions[0].getText());
      }
      @NonNls final String methodName = methodExpression.getReferenceName();
      final boolean literalReplacement = "replace".equals(methodName);
      if (literalReplacement) {
        fieldText.append(", java.util.regex.Pattern.LITERAL");
      }
      fieldText.append(");");

      @NonNls final StringBuilder expressionText = new StringBuilder("PATTERN.");
      final PsiExpression qualifier = methodExpression.getQualifierExpression();
      @NonNls final String qualifierText = (qualifier == null) ? "this" : qualifier.getText();
      if ("split".equals(methodName)) {
        expressionText.append(methodName);
        expressionText.append('(');
        expressionText.append(qualifierText);
        for (int i = 1; i < expressionsLength; i++) {
          expressionText.append(',').append(expressions[i].getText());
        }
        expressionText.append(')');
      } else {
        expressionText.append("matcher(").append(qualifierText).append(").");
        if (literalReplacement) {
          expressionText.append("replaceAll");
        } else {
          expressionText.append(methodName);
        }
        expressionText.append('(');
        if (literalReplacement) {
          expressionText.append("java.util.regex.Matcher.quoteReplacement(");
        }
        if (expressionsLength > 1) {
          expressionText.append(expressions[1].getText());
          for (int i = 2; i < expressionsLength; i++) {
            expressionText.append(',').append(expressions[i].getText());
          }
        }
        if (literalReplacement) {
          expressionText.append(')');
        }
        expressionText.append(')');
      }

      final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
      final PsiField newField = factory.createFieldFromText(fieldText.toString(), element);
      final PsiElement field = aClass.add(newField);
      final PsiExpression newExpression =
          factory.createExpressionFromText(expressionText.toString(), element);
      PsiMethodCallExpression newMethodCallExpression =
          (PsiMethodCallExpression) methodCallExpression.replace(newExpression);
      newMethodCallExpression =
          CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(newMethodCallExpression);
      final PsiReferenceExpression reference = getReference(newMethodCallExpression);
      HighlightUtils.showRenameTemplate(aClass, (PsiNameIdentifierOwner) field, reference);
    }