public static ICleanUpFix createCleanUp(
      CompilationUnit compilationUnit,
      IProblemLocation[] problems,
      boolean addOverrideAnnotation,
      boolean addOverrideInterfaceAnnotation,
      boolean addDeprecatedAnnotation,
      boolean rawTypeReferences) {

    ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement();
    if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) return null;

    if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReferences) return null;

    List /*<CompilationUnitRewriteOperation>*/ operations = new ArrayList();

    if (addOverrideAnnotation)
      createAddOverrideAnnotationOperations(
          compilationUnit, addOverrideInterfaceAnnotation, problems, operations);

    if (addDeprecatedAnnotation)
      createAddDeprecatedAnnotationOperations(compilationUnit, problems, operations);

    if (rawTypeReferences) createRawTypeReferenceOperations(compilationUnit, problems, operations);

    if (operations.size() == 0) return null;

    CompilationUnitRewriteOperation[] operationsArray =
        (CompilationUnitRewriteOperation[])
            operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
    return new Java50Fix(
        FixMessages.Java50Fix_add_annotations_change_name, compilationUnit, operationsArray);
  }
  private static boolean hasFatalError(CompilationUnit compilationUnit) {
    try {
      if (!((ICompilationUnit) compilationUnit.getJavaElement()).isStructureKnown()) return true;
    } catch (JavaModelException e) {
      JavaPlugin.log(e);
      return true;
    }

    IProblem[] problems = compilationUnit.getProblems();
    for (int i = 0; i < problems.length; i++) {
      if (problems[i].isError()) {
        if (!(problems[i] instanceof CategorizedProblem)) return true;

        CategorizedProblem categorizedProblem = (CategorizedProblem) problems[i];
        int categoryID = categorizedProblem.getCategoryID();

        if (categoryID == CategorizedProblem.CAT_BUILDPATH) return true;
        if (categoryID == CategorizedProblem.CAT_SYNTAX) return true;
        if (categoryID == CategorizedProblem.CAT_IMPORT) return true;
        if (categoryID == CategorizedProblem.CAT_TYPE) return true;
        if (categoryID == CategorizedProblem.CAT_MEMBER) return true;
        if (categoryID == CategorizedProblem.CAT_INTERNAL) return true;
      }
    }

    return false;
  }
  @Override
  public void run(IProgressMonitor monitor) throws CoreException {
    if (monitor == null) monitor = new NullProgressMonitor();
    try {
      monitor.beginTask("", 1); // $NON-NLS-1$
      monitor.setTaskName(CodeGenerationMessages.GenerateToStringOperation_description);

      AbstractTypeDeclaration declaration =
          (AbstractTypeDeclaration)
              ASTNodes.findDeclaration(fContext.getTypeBinding(), fRewrite.getRoot());
      ListRewrite rewriter =
          fRewrite
              .getASTRewrite()
              .getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
      if (fContext.getTypeBinding() != null && rewriter != null) {

        MethodDeclaration toStringMethod = fGenerator.generateToStringMethod();

        List<BodyDeclaration> list = declaration.bodyDeclarations();
        BodyDeclaration replace = findMethodToReplace(list, toStringMethod);
        if (replace == null
            || ((Boolean)
                    toStringMethod.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                .booleanValue()) insertMethod(toStringMethod, rewriter, replace);

        List<MethodDeclaration> helperMethods = fGenerator.generateHelperMethods();
        for (Iterator<MethodDeclaration> iterator = helperMethods.iterator();
            iterator.hasNext(); ) {
          MethodDeclaration method = iterator.next();
          replace = findMethodToReplace(list, method);
          if (replace == null
              || ((Boolean) method.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                  .booleanValue()) {
            insertMethod(method, rewriter, replace);
          }
        }

        JavaModelUtil.applyEdit(
            (ICompilationUnit) fUnit.getJavaElement(),
            fRewrite.createChange(true).getEdit(),
            false,
            monitor);
      }

    } finally {
      monitor.done();
    }
  }
  private static Java50Fix createFix(
      CompilationUnit compilationUnit, IProblemLocation problem, String annotation, String label) {
    ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement();
    if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) return null;

    ASTNode selectedNode = problem.getCoveringNode(compilationUnit);
    if (selectedNode == null) return null;

    ASTNode declaringNode = getDeclaringNode(selectedNode);
    if (!(declaringNode instanceof BodyDeclaration)) return null;

    BodyDeclaration declaration = (BodyDeclaration) declaringNode;

    AnnotationRewriteOperation operation = new AnnotationRewriteOperation(declaration, annotation);

    return new Java50Fix(label, compilationUnit, new CompilationUnitRewriteOperation[] {operation});
  }
예제 #5
0
  /**
   * Add a method's data, words and its mappings to the database. This method is called externally
   * from {@link MyASTVisitor}.
   *
   * @param method A AST node of MethodDeclaration type
   */
  public void addMethodToDb(MethodDeclaration method) {
    System.out.println("Processing method: " + method.getName());

    CompilationUnit unit = (CompilationUnit) method.getRoot();
    IPath path = unit.getJavaElement().getResource().getLocation();

    dbManager.insertMethod(
        new MethodData(
            method.resolveBinding().getKey(), method.getName().toString(), path.toString()));

    // Gets camel case split words
    List<String> words = TFIDFIndex.getTokens(method.toString());

    for (String word : words) {
      addWordToDb(word, method.resolveBinding().getKey());
    }
  }
  public static ICleanUpFix createCleanUp(
      CompilationUnit compilationUnit,
      boolean addOverrideAnnotation,
      boolean addOverrideInterfaceAnnotation,
      boolean addDeprecatedAnnotation,
      boolean rawTypeReference) {

    ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement();
    if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) return null;

    if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReference) return null;

    List /*<CompilationUnitRewriteOperation>*/ operations = new ArrayList();

    IProblem[] problems = compilationUnit.getProblems();
    IProblemLocation[] locations = new IProblemLocation[problems.length];
    for (int i = 0; i < problems.length; i++) {
      locations[i] = new ProblemLocation(problems[i]);
    }

    if (addOverrideAnnotation)
      createAddOverrideAnnotationOperations(
          compilationUnit, addOverrideInterfaceAnnotation, locations, operations);

    if (addDeprecatedAnnotation)
      createAddDeprecatedAnnotationOperations(compilationUnit, locations, operations);

    if (rawTypeReference) createRawTypeReferenceOperations(compilationUnit, locations, operations);

    if (operations.size() == 0) return null;

    String fixName;
    if (rawTypeReference) {
      fixName = FixMessages.Java50Fix_add_type_parameters_change_name;
    } else {
      fixName = FixMessages.Java50Fix_add_annotations_change_name;
    }

    CompilationUnitRewriteOperation[] operationsArray =
        (CompilationUnitRewriteOperation[])
            operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
    return new Java50Fix(fixName, compilationUnit, operationsArray);
  }
  /** {@inheritDoc} */
  public int computeNumberOfFixes(CompilationUnit compilationUnit) {
    try {
      ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement();
      if (!cu.isStructureKnown())
        return 0; // [clean up] 'Remove unnecessary $NLS-TAGS$' removes necessary ones in case of
      // syntax errors: https://bugs.eclipse.org/bugs/show_bug.cgi?id=285814 :
    } catch (JavaModelException e) {
      return 0;
    }

    int result = 0;
    IProblem[] problems = compilationUnit.getProblems();
    if (isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS))
      result += getNumberOfProblems(problems, IProblem.NonExternalizedStringLiteral);

    if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS))
      result += getNumberOfProblems(problems, IProblem.UnnecessaryNLSTag);

    return result;
  }
  @Override
  public IStatus satisfiesPreconditions() {
    ForStatement statement = getForStatement();
    CompilationUnit ast = (CompilationUnit) statement.getRoot();

    IJavaElement javaElement = ast.getJavaElement();
    if (javaElement == null) return ERROR_STATUS;

    if (!JavaModelUtil.is50OrHigher(javaElement.getJavaProject())) return ERROR_STATUS;

    if (!validateInitializers(statement)) return ERROR_STATUS;

    if (!validateExpression(statement)) return ERROR_STATUS;

    if (!validateUpdaters(statement)) return ERROR_STATUS;

    if (!validateBody(statement)) return ERROR_STATUS;

    return Status.OK_STATUS;
  }
  protected void handleCompilationUnit(ICompilationUnit cu) {
    monitor.worked(1);
    monitor.subTask(cu.getElementName());

    try {
      CompilationUnit unit = JavaASTUtil.parseCompilationUnit(cu, monitor);

      currentUnit = (ICompilationUnit) unit.getJavaElement();

      handleUnit(unit);

    } catch (Exception ex) {
      addErrorMsg("Failed to handle unit " + cu.getElementName() + ":" + ex.toString());
      PatternUIPlugin.logWarning("Failed to handle unit " + cu.getElementName(), ex);
    } catch (Throwable ex) {
      addErrorMsg("Failed to handle unit " + cu.getElementName() + ":" + ex.toString());
      PatternUIPlugin.logError("Failed to handle unit " + cu.getElementName(), ex);
    } finally {
      currentUnit = null;
    }
  }
예제 #10
0
  /**
   * This method analyzes a set of local variable renames inside one cu. It checks whether any new
   * compile errors have been introduced by the rename(s) and whether the correct node(s) has/have
   * been renamed.
   *
   * @param analyzePackages the LocalAnalyzePackages containing the information about the local
   *     renames
   * @param cuChange the TextChange containing all local variable changes to be applied.
   * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
   * @param recovery whether statements and bindings recovery should be performed when parsing the
   *     changed CU
   * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are
   *     found
   * @throws CoreException thrown if there was an error greating the preview content of the change
   */
  public static RefactoringStatus analyzeLocalRenames(
      LocalAnalyzePackage[] analyzePackages,
      TextChange cuChange,
      CompilationUnit oldCUNode,
      boolean recovery)
      throws CoreException {

    RefactoringStatus result = new RefactoringStatus();
    ICompilationUnit compilationUnit = (ICompilationUnit) oldCUNode.getJavaElement();

    String newCuSource = cuChange.getPreviewContent(new NullProgressMonitor());
    CompilationUnit newCUNode =
        new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL)
            .parse(newCuSource, compilationUnit, true, recovery, null);

    result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
    if (result.hasError()) return result;

    for (int i = 0; i < analyzePackages.length; i++) {
      ASTNode enclosing =
          getEnclosingBlockOrMethodOrLambda(
              analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);

      // get new declaration
      IRegion newRegion =
          RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
      ASTNode newDeclaration =
          NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
      Assert.isTrue(newDeclaration instanceof Name);

      VariableDeclaration declaration = getVariableDeclaration((Name) newDeclaration);
      Assert.isNotNull(declaration);

      SimpleName[] problemNodes =
          ProblemNodeFinder.getProblemNodes(
              enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
      result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
    }
    return result;
  }
예제 #11
0
  protected void initConstantStringAuditor() {
    // parse editor content and extract resource-bundle access strings

    // get the type of the currently loaded resource
    ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor.getEditorInput());

    if (typeRoot == null) {
      return;
    }

    CompilationUnit cu = ASTutilsUI.getAstRoot(typeRoot);

    if (cu == null) {
      return;
    }

    manager = ResourceBundleManager.getManager(cu.getJavaElement().getResource().getProject());

    // determine the element at the position of the cursur
    csf = new ResourceAuditVisitor(null, manager.getProject().getName());
    cu.accept(csf);
  }
 /**
  * Adds the specified tag to the source member defined by the member name and signature
  *
  * @param unit
  * @param membername
  * @param signature
  * @param tagname
  * @param remove
  * @throws CoreException
  * @throws MalformedTreeException
  * @throws BadLocationException
  */
 private void updateTagInSource(
     ICompilationUnit unit, String membername, String signature, String tagname, boolean remove)
     throws CoreException, MalformedTreeException, BadLocationException {
   ASTParser parser = ASTParser.newParser(AST.JLS4);
   parser.setSource(unit);
   CompilationUnit cunit = (CompilationUnit) parser.createAST(new NullProgressMonitor());
   assertNotNull("the ast compilation unit cannot be null", cunit);
   cunit.recordModifications();
   ASTRewrite rewrite = ASTRewrite.create(cunit.getAST());
   cunit.accept(new SourceChangeVisitor(membername, signature, tagname, remove, rewrite));
   ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
   IPath path = cunit.getJavaElement().getPath();
   try {
     bm.connect(path, LocationKind.IFILE, null);
     ITextFileBuffer tfb = bm.getTextFileBuffer(path, LocationKind.IFILE);
     IDocument document = tfb.getDocument();
     TextEdit edits = rewrite.rewriteAST(document, null);
     edits.apply(document);
     tfb.commit(new NullProgressMonitor(), true);
   } finally {
     bm.disconnect(path, LocationKind.IFILE, null);
   }
 }