コード例 #1
0
  @Test
  public void testAddDummyHandlerSmellInfoForExtraRule_PrintStackTrace() throws Exception {
    Method method =
        DummyHandlerVisitor.class.getDeclaredMethod(
            "addDummyHandlerSmellInfo", MethodInvocation.class);
    method.setAccessible(true);

    // 確認初始值
    setEmptySetting();
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());

    // ePrintStackTrace case
    dummyHandlerPatternsInXML = new String[] {SmellSettings.EXTRARULE_ePrintStackTrace};
    setNewSettingsWithExtraRules(dummyHandlerPatternsInXML);
    //   分別測試:全部例子、符合例子、不符合例子 是否有抓出
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(10, dummyHandlerVisitor.getDummyList().size());

    MethodInvocation mi = null;
    mi =
        ASTNodeFinder.getMethodInvocationByMethodNameAndCode(
                compilationUnit, "true_printStackTrace_protected", "e.printStackTrace()")
            .get(0);
    method.invoke(dummyHandlerVisitor, mi);
    assertEquals(11, dummyHandlerVisitor.getDummyList().size());
  }
コード例 #2
0
  /** 測試當使用者自訂的type1是否能抓到Outer class 未測試完成 */
  @Test
  public void testAddDummyHandlerSmellInfoForUserPatternType1() {
    String testClassPattern = UserDefineDummyHandlerFish.class.getName() + ".*";

    // 確認初始值
    setEmptySetting();
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());

    // 確認全部的Example中恰有偵測到兩次呼叫
    smellSettings.addDummyHandlerPattern(testClassPattern, true);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(2, dummyHandlerVisitor.getDummyList().size());

    // 確認當使用者未勾選時不會偵測到
    setEmptySetting();
    smellSettings.addDummyHandlerPattern(testClassPattern, false);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());
  }
コード例 #3
0
  @Test
  public void testAddDummyHandlerSmellInfoForExtraRule_OrgApacheLog4j() throws Exception {
    Method method =
        DummyHandlerVisitor.class.getDeclaredMethod(
            "addDummyHandlerSmellInfo", MethodInvocation.class);
    method.setAccessible(true);

    // 確認初始值
    setEmptySetting();
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());
    // OrgApacheLog4j case
    dummyHandlerPatternsInXML = new String[] {SmellSettings.EXTRARULE_OrgApacheLog4j};
    setNewSettingsWithExtraRules(dummyHandlerPatternsInXML);
    //   分別測試:全部例子、符合例子、不符合例子 是否有抓出
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(1, dummyHandlerVisitor.getDummyList().size());

    MethodInvocation mi = null;
    mi =
        ASTNodeFinder.getMethodInvocationByMethodNameAndCode(
                compilationUnit, "true_Log4J", "log4j.info(\"message\")")
            .get(0);
    method.invoke(dummyHandlerVisitor, mi);
    assertEquals(2, dummyHandlerVisitor.getDummyList().size());

    mi =
        ASTNodeFinder.getMethodInvocationByMethodNameAndCode(
                compilationUnit, "true_javaLogInfo", "javaLog.info(\"\")")
            .get(0);
    method.invoke(dummyHandlerVisitor, mi);
    assertEquals(2, dummyHandlerVisitor.getDummyList().size());
  }
コード例 #4
0
  public static ICleanUpFix createCleanUp(
      CompilationUnit compilationUnit,
      boolean addFinalFields,
      boolean addFinalParameters,
      boolean addFinalLocals) {

    if (!addFinalFields && !addFinalParameters && !addFinalLocals) return null;

    HashMap writtenNames = new HashMap();
    WrittenNamesFinder finder = new WrittenNamesFinder(writtenNames);
    compilationUnit.accept(finder);

    List operations = new ArrayList();
    VariableDeclarationFinder visitor =
        new VariableDeclarationFinder(
            addFinalFields, addFinalParameters, addFinalLocals, operations, writtenNames);
    compilationUnit.accept(visitor);

    if (operations.isEmpty()) return null;

    return new VariableDeclarationFix(
        FixMessages.VariableDeclarationFix_add_final_change_name,
        compilationUnit,
        (CompilationUnitRewriteOperation[])
            operations.toArray(new CompilationUnitRewriteOperation[operations.size()]));
  }
コード例 #5
0
  @Override
  public void acceptAST(String sourceFilePath, CompilationUnit compUnit) {
    checkForProblems(sourceFilePath, compUnit);

    if (isTestFile(sourceFilePath)) {
      ModificationRecordingVisitor visitor = new AutocheckVisitor(compUnit.getAST());
      compUnit.accept(visitor);
      actualResults.put(sourceFilePath, compUnit);
    } else if (isExpectedFile(sourceFilePath)
        && actualResults.containsKey(testFileMapping.get(sourceFilePath))) {
      CompilationUnit actual = actualResults.get(testFileMapping.get(sourceFilePath));
      Object diff = ASTCompare.getDifference(compUnit, actual);
      if (diff != null) {
        throw new RuntimeException(
            "The expected and the actual AST does not match. Expected file: "
                + sourceFilePath
                + ", actual content:\n"
                + actual
                + "\ndifference around: "
                + diff);
      }
    } else {
      throw new RuntimeException("Unexpected AST: " + sourceFilePath);
    }
  }
コード例 #6
0
ファイル: BaseQuickFix.java プロジェクト: mkaouer/robusta
  /**
   * 取得Method相關資訊
   *
   * @param resource 來源
   * @param methodIdx Method的Index
   * @return 是否成功
   */
  protected boolean findCurrentMethod(IResource resource, int methodIdx) {
    if (resource instanceof IFile && resource.getName().endsWith(".java")) {
      try {
        IJavaElement javaElement = JavaCore.create(resource);

        if (javaElement instanceof IOpenable) {
          actOpenable = (IOpenable) javaElement;
        }

        // Create AST to parse
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);

        parser.setSource((ICompilationUnit) javaElement);
        parser.setResolveBindings(true);
        actRoot = (CompilationUnit) parser.createAST(null);
        // AST 2.0紀錄方式
        actRoot.recordModifications();

        // 取得該class所有的method
        ASTMethodCollector methodCollector = new ASTMethodCollector();
        actRoot.accept(methodCollector);
        List<MethodDeclaration> methodList = methodCollector.getMethodList();

        // 取得目前要被修改的method node
        currentMethodNode = methodList.get(methodIdx);

        return true;
      } catch (Exception ex) {
        logger.error("[Find DH Method] EXCEPTION ", ex);
      }
    }
    return false;
  }
コード例 #7
0
  public static VariableDeclarationFix createChangeModifierToFinalFix(
      final CompilationUnit compilationUnit, ASTNode[] selectedNodes) {
    HashMap writtenNames = new HashMap();
    WrittenNamesFinder finder = new WrittenNamesFinder(writtenNames);
    compilationUnit.accept(finder);
    List ops = new ArrayList();
    VariableDeclarationFinder visitor =
        new VariableDeclarationFinder(true, true, true, ops, writtenNames);
    if (selectedNodes.length == 1) {
      if (selectedNodes[0] instanceof SimpleName) {
        selectedNodes[0] = selectedNodes[0].getParent();
      }
      selectedNodes[0].accept(visitor);
    } else {
      for (int i = 0; i < selectedNodes.length; i++) {
        ASTNode selectedNode = selectedNodes[i];
        selectedNode.accept(visitor);
      }
    }
    if (ops.size() == 0) return null;

    CompilationUnitRewriteOperation[] result =
        (CompilationUnitRewriteOperation[])
            ops.toArray(new CompilationUnitRewriteOperation[ops.size()]);
    String label;
    if (result.length == 1) {
      label = FixMessages.VariableDeclarationFix_changeModifierOfUnknownToFinal_description;
    } else {
      label = FixMessages.VariableDeclarationFix_ChangeMidifiersToFinalWherPossible_description;
    }
    return new VariableDeclarationFix(label, compilationUnit, result);
  }
コード例 #8
0
  @Test
  public void testGetCarelessCleanupListWithoutExtraRules() {
    /* 重新產生設定檔 */
    SmellSettings smellSettings = new SmellSettings(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    // 因為Setup時候已經產出一個有ExtraRule的設定檔,現在要特地把ExtraRule移除掉來測試。
    smellSettings.removeExtraRule(
        SmellSettings.SMELL_CARELESSCLEANUP,
        SmellSettings.EXTRARULE_CARELESSCLEANUP_DETECTISRELEASEIOCODEINDECLAREDMETHOD);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);

    // 重新產生Visitor,使得設定值有存入CarelessCleaupVisitor
    carelessCleanupVisitor = new CarelessCleanupVisitor2(compilationUnit);

    int carelessCleanupSmellCount = 0;
    assertNotNull(compilationUnit);
    assertNotNull(carelessCleanupVisitor);
    compilationUnit.accept(carelessCleanupVisitor);
    if (carelessCleanupVisitor.getCarelessCleanupList() != null) {
      carelessCleanupSmellCount = carelessCleanupVisitor.getCarelessCleanupList().size();
    }
    assertEquals(
        colloectBadSmellListContent(carelessCleanupVisitor.getCarelessCleanupList()),
        28,
        carelessCleanupSmellCount);
  }
コード例 #9
0
  @Test
  public void testAddDummyHandlerSmellInfoWithUserDefinedPatternAndDetecting() {
    // 使用者自定義 *.toString 的Pattern,並且要求要偵測
    setEmptySetting();
    smellSettings.addDummyHandlerPattern("*.toString", true);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(2, dummyHandlerVisitor.getDummyList().size());

    MethodInvocation mi = null;

    // 符合 *.toString 的程式碼 -> e.toString()
    mi =
        ASTNodeFinder.getMethodInvocationByMethodNameAndCode(
                compilationUnit, "true_systemOutPrintlnWithoutE", "e.toString()")
            .get(0);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    dummyHandlerVisitor.detectDummyHandler(mi);
    assertEquals(1, dummyHandlerVisitor.getDummyList().size());

    // 不符合 *.toString 的程式碼 -> e.toString.toCharArray()
    mi =
        ASTNodeFinder.getMethodInvocationByMethodNameAndCode(
                compilationUnit, "true_systemOutPrintlnWithoutE", "e.toString().toCharArray()")
            .get(0);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    dummyHandlerVisitor.detectDummyHandler(mi);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());
  }
コード例 #10
0
  private List<AbstractTypeDeclaration> collectTypes(CompilationUnit unit) {
    final List<AbstractTypeDeclaration> types = Lists.newArrayList();
    unit.accept(
        new ErrorReportingASTVisitor() {
          @Override
          public boolean visit(TypeDeclaration node) {
            if (!node.isInterface()
                || !getStaticFieldsNeedingAccessors(
                        Arrays.asList(node.getFields()), /* isInterface */ true)
                    .isEmpty()
                || !Options.stripReflection()) {
              types.add(node);
            }
            return false;
          }

          @Override
          public boolean visit(EnumDeclaration node) {
            types.add(node); // always print enums
            return false;
          }

          @Override
          public boolean visit(AnnotationTypeDeclaration node) {
            if (BindingUtil.isRuntimeAnnotation(Types.getTypeBinding(node))
                || !getStaticFieldsNeedingAccessors(
                        ASTUtil.getFieldDeclarations(node), /* isInterface */ true)
                    .isEmpty()) {
              types.add(node);
            }
            return false;
          }
        });
    return types;
  }
コード例 #11
0
ファイル: GCodeAnalyzer.java プロジェクト: taoxiease/asegrp
  /**
   * Function for traversing the source files in the application under analysis
   *
   * @param astC
   * @return
   */
  public TreeSet analyzeLibraryCode(ASTCrawler astC) {
    IJavaProject libProject = RepositoryAnalyzer.getInstance().getCurrentJProject();
    if (libProject == null) {
      logger.warn("No library project is available as input. Nothing can be done, Sorry!!!!");
      return null;
    }

    try {
      IPackageFragment[] fragments = libProject.getPackageFragments();
      for (int j = 0; j < fragments.length; j++) {
        switch (fragments[j].getKind()) {
          case IPackageFragmentRoot.K_SOURCE:

            /**
             * @todo I'm not sure whether K_SOURCE actually means non-Archive (and therefore further
             *     testing is obsolete)
             */
            IPackageFragmentRoot root =
                (IPackageFragmentRoot) fragments[j].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

            if (!root.isArchive()) {
              ICompilationUnit[] units = fragments[j].getCompilationUnits();
              for (ICompilationUnit icu : units) {
                ASTParser parser = ASTParser.newParser(AST.JLS3);
                parser.setProject(libProject);
                parser.setResolveBindings(true);
                parser.setStatementsRecovery(true);

                parser.setSource(icu);
                CompilationUnit cu_java = (CompilationUnit) parser.createAST(null);

                try {
                  // This also clears the class specific data of the previous run
                  String path = icu.getPath().toString();
                  int indexOfLastSlash;
                  if ((indexOfLastSlash = path.lastIndexOf("/")) != -1) {
                    path = path.substring(indexOfLastSlash + 1, path.length());
                  }
                  astC.preProcessClass(cu_java, path);
                  MethodInvocationHolder.MIHKEYGEN = 0;
                  cu_java.accept(astC);
                } catch (Exception ex) {
                  ex.printStackTrace();
                }
              }
            }

            break;

          default:
            break;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return astC.postProcess();
  }
コード例 #12
0
 /**
  * Scans the specified source {@linkplain CompilationUnit} for contributed API javadoc tags. Tags
  * on methods will have unresolved signatures.
  *
  * @param source the source file to scan for tags
  * @param description the API description to annotate with any new tag rules found
  * @param container optional class file container containing the class file for the given source
  *     that can be used to resolve method signatures if required (for tags on methods). If not
  *     provided (<code>null</code>), method signatures will be unresolved.
  * @param options a map of Java compiler options to use when creating the AST to scan or <code>
  *     null</code> if default options should be used
  * @param monitor
  * @throws CoreException
  */
 public void scan(
     CompilationUnit source,
     IApiDescription description,
     IApiTypeContainer container,
     Map options,
     IProgressMonitor monitor)
     throws CoreException {
   SubMonitor localmonitor = SubMonitor.convert(monitor, 2);
   ASTParser parser = ASTParser.newParser(AST.JLS3);
   InputStream inputStream = null;
   try {
     inputStream = source.getInputStream();
     parser.setSource(
         Util.getInputStreamAsCharArray(
             inputStream, -1, System.getProperty("file.encoding"))); // $NON-NLS-1$
   } catch (FileNotFoundException e) {
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             ApiPlugin.PLUGIN_ID,
             MessageFormat.format(
                 "Compilation unit source not found: {0}", new String[] {source.getName()}),
             e)); //$NON-NLS-1$
   } catch (IOException e) {
     if (DEBUG) {
       System.err.println(source.getName());
     }
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             ApiPlugin.PLUGIN_ID,
             MessageFormat.format(
                 "Error reading compilation unit: {0}", new String[] {source.getName()}),
             e)); //$NON-NLS-1$
   } finally {
     if (inputStream != null) {
       try {
         inputStream.close();
       } catch (IOException e) {
         ApiPlugin.log(e);
       }
     }
   }
   Util.updateMonitor(localmonitor);
   Map loptions = options;
   if (loptions == null) {
     loptions = JavaCore.getOptions();
   }
   loptions.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
   parser.setCompilerOptions(loptions);
   org.eclipse.jdt.core.dom.CompilationUnit cunit =
       (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(localmonitor.newChild(1));
   Visitor visitor = new Visitor(description, container);
   cunit.accept(visitor);
   if (visitor.getException() != null) {
     throw visitor.getException();
   }
 }
コード例 #13
0
 private void findTypeDeclarations(CompilationUnit unit) {
   unit.accept(
       new ASTVisitor() {
         @Override
         public void preVisit(ASTNode node) {
           nodesByType.put(node.getNodeType(), node);
         }
       });
 }
コード例 #14
0
  @Test
  public void testAddDummyHandlerSmellInfoWithUserDefinedPatternButNotDetecting() {
    // 使用者有自定義 *.toString 的Pattern,但是不要偵測
    setEmptySetting();
    smellSettings.addDummyHandlerPattern("*.toString", false);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());

    // 使用者輸入改為 *.toString(), 不會被視同是 *.toString
    setEmptySetting();
    smellSettings.addDummyHandlerPattern("*.toString()", true);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());
  }
コード例 #15
0
 public void traverse(ArrayList<CompileUnit> compileUnits) {
   System.out.println("Traverse...............................");
   castHelper = CASTHelper.getInstance();
   for (CompileUnit compileUnit : compileUnits) {
     this.filePath = compileUnit.getFilePath();
     this.compilationUnit = compileUnit.getCompilationUnit();
     compilationUnit.accept(this);
   }
 }
コード例 #16
0
  @Test
  public void testCatchClauseFinderVisitor_2CatchClause() {
    // 不知道為什麼,測試時候,ASTView上面看到的數字還要減一,答案才會正確。實際用的時候沒差。
    int targetCatchClauseStartPosition = 476 - 1;
    CatchClauseFinderVisitor catchClauseFinder =
        new CatchClauseFinderVisitor(targetCatchClauseStartPosition);
    compilationUnit.accept(catchClauseFinder);
    assertEquals(
        "catch (FileNotFoundException e) {\n  e.printStackTrace();\n}\n",
        catchClauseFinder.getFoundCatchClause().toString());

    targetCatchClauseStartPosition = 577 - 1;
    catchClauseFinder = new CatchClauseFinderVisitor(targetCatchClauseStartPosition);
    compilationUnit.accept(catchClauseFinder);
    assertEquals(
        "catch (IOException e) {\n  e.printStackTrace();\n}\n",
        catchClauseFinder.getFoundCatchClause().toString());
  }
コード例 #17
0
 @Test
 public void testCatchClauseFinderVisitor_1CatchClause() {
   int targetCatchClauseStartPosition = 794 - 1;
   CatchClauseFinderVisitor catchClauseFinder =
       new CatchClauseFinderVisitor(targetCatchClauseStartPosition);
   compilationUnit.accept(catchClauseFinder);
   assertEquals(
       "catch (IOException e) {\n  System.out.println(e);\n}\n",
       catchClauseFinder.getFoundCatchClause().toString());
 }
コード例 #18
0
 private void findInvokedConstructors(CompilationUnit unit) {
   unit.accept(
       new ErrorReportingASTVisitor() {
         @Override
         public boolean visit(ConstructorInvocation node) {
           invokedConstructors.add(methodKey(Types.getMethodBinding(node)));
           return false;
         }
       });
 }
コード例 #19
0
 /** 測試當使用者自訂的type3是否能抓到 同時測試addDummyHandlerSmellInfo()中,遇到含有"<>"library會自動轉成"<"之前的子字串 */
 @Test
 public void testAddDummyHandlerSmellInfoForUserPatternType3WithBracket() {
   String testClassPattern = "java.util.ArrayList.add";
   setEmptySetting();
   smellSettings.addDummyHandlerPattern(testClassPattern, true);
   smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
   dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
   compilationUnit.accept(dummyHandlerVisitor);
   assertEquals(1, dummyHandlerVisitor.getDummyList().size());
 }
コード例 #20
0
ファイル: MethodsInClass.java プロジェクト: sazu2905/tassal
 public void scan(final Collection<File> files) {
   final MethodExtractor me = new MethodExtractor();
   final JavaASTExtractor jEx = new JavaASTExtractor(false);
   for (final File f : files) {
     try {
       final CompilationUnit cu = jEx.getAST(f);
       cu.accept(me);
     } catch (final Throwable e) {
       LOGGER.warning("Failed to get methods from " + f);
     }
   }
 }
コード例 #21
0
ファイル: DeduplicateCode.java プロジェクト: vesperin/vesper
  private Delta deduplicate(CompilationUnit root, ASTRewrite rewrite, Cause cause) {

    final List<ASTNode> nodes = cause.getAffectedNodes();
    final int size = nodes.size();
    final int cloneNumber = size == 0 ? size : size - 1; // minus the original declaration

    if (cloneNumber == 0) {
      throw new RuntimeException("calling deduplicate() when there are no detected clones");
    } else if (cloneNumber >= 1) {
      // NOTE: THIS WORKS ONLY AT METHOD LEVEL, other forms of duplication will
      // will be ignored.

      // The strategy this code follows to perform deduplication is the following:
      // per duplicated method declaration, find all of its invocations. Then
      // rename each found invocation using the name of the original method declaration.
      // After that, remove the duplicated method declaration.
      if (AstUtil.isOfType(MethodDeclaration.class, nodes.get(0))) {
        final MethodDeclaration original = AstUtil.exactCast(MethodDeclaration.class, nodes.get(0));
        final Iterable<ASTNode> rest = Iterables.skip(nodes, 1);
        for (ASTNode eachClone : rest) {
          final MethodDeclaration duplicate = AstUtil.exactCast(MethodDeclaration.class, eachClone);
          final MethodDeclaration copied =
              AstUtil.copySubtree(MethodDeclaration.class, root.getAST(), duplicate);
          final boolean sameReturn = sameReturnType(original, copied);

          if (!sameReturn) { // all or none. We don't do partial deduplication
            throw new RuntimeException(
                "automatic deduplication cannot be done on methods "
                    + "with different return types; please consider "
                    + "manual deduplication.");
          }

          final MethodInvocationVisitor invokesOfDuplication =
              new MethodInvocationVisitor(copied.getName());
          root.accept(invokesOfDuplication);
          final Set<MethodInvocation> invokes = invokesOfDuplication.getMethodInvocations();

          for (MethodInvocation each : invokes) {
            final MethodInvocation copiedInvoke =
                AstUtil.copySubtree(MethodInvocation.class, root.getAST(), each);
            copiedInvoke.setName(root.getAST().newSimpleName(original.getName().getIdentifier()));
            rewrite.replace(each, copiedInvoke, null);
          }

          rewrite.remove(duplicate, null);
        }
      }
    }

    return createDelta(root, rewrite);
  }
コード例 #22
0
 @Test
 public void testGetCarelessCleanupList() {
   int carelessCleanupSmellCount = 0;
   assertNotNull(compilationUnit);
   assertNotNull(carelessCleanupVisitor);
   compilationUnit.accept(carelessCleanupVisitor);
   if (carelessCleanupVisitor.getCarelessCleanupList() != null) {
     carelessCleanupSmellCount = carelessCleanupVisitor.getCarelessCleanupList().size();
   }
   assertEquals(
       colloectBadSmellListContent(carelessCleanupVisitor.getCarelessCleanupList()),
       31,
       carelessCleanupSmellCount);
 }
コード例 #23
0
 @Override
 public boolean visit(IResource resource) throws CoreException {
   System.out.println("Visit called on " + resource.getName());
   if (resource.getType() == IResource.FILE && JavaCore.isJavaLikeFileName(resource.getName())) {
     methodLocations = MethodLocations.getInstance();
     methodLocations.clearLocations();
     ICompilationUnit icu = JavaCore.createCompilationUnitFrom((IFile) resource);
     CompilationUnit cu = parse(icu);
     cu.accept(new MyASTVisitor());
     processComments(cu);
     DatabaseLoader.getInstance().workedFile();
   }
   return true;
 }
コード例 #24
0
ファイル: SourceGraph.java プロジェクト: ruigameiro/PESTT
 public void create(ICompilationUnit unit, String methodName) {
   // Now create the AST for the ICompilationUnits
   CompilationUnit parser = parse(unit);
   GraphBuilder visitor = new GraphBuilder(methodName, parser);
   parser.accept(visitor);
   sourceGraph = visitor.getGraph();
   javadocAnnotations = visitor.getJavadocAnnotations();
   hash = visitor.getMethodHash();
   params = visitor.getMethodParameters();
   attributes = visitor.getClassAttributes();
   enumFields = visitor.getEnumClassAttributes();
   setChanged();
   notifyObservers(new CFGCreateEvent(sourceGraph));
 }
コード例 #25
0
  public RefactoringStatus checkActivationBasics(CompilationUnit rootNode) throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    fRootNode = rootNode;

    fAnalyzer = new SurroundWithTryCatchAnalyzer(fCUnit, fSelection);
    fRootNode.accept(fAnalyzer);
    result.merge(fAnalyzer.getStatus());
    ITypeBinding[] exceptions = fAnalyzer.getExceptions();
    if (fIsMultiCatch && (exceptions == null || exceptions.length <= 1)) {
      result.merge(
          RefactoringStatus.createWarningStatus(
              RefactoringCoreMessages.SurroundWithTryCatchRefactoring_notMultipleexceptions));
    }
    return result;
  }
コード例 #26
0
  /**
   * 另外測試若 try statement 位於非 try statement 之中時,是否會正確偵測
   *
   * @throws Exception
   */
  @Test
  public void testDetectDummyHandlerWithTryStatementInNonTryStatement() throws Exception {
    CompilationUnit compilationUnitWithTSINTS;

    // 新建立測試用的 DummyHandlerExampleWithTryStatementInNonTryStatement
    javaFile2String.clear();
    javaFile2String.read(
        DummyHandlerExampleWithTryStatementInNonTryStatement.class,
        JavaProjectMaker.FOLDERNAME_TEST);
    javaProjectMaker.createJavaFile(
        DummyHandlerExampleWithTryStatementInNonTryStatement.class.getPackage().getName(),
        DummyHandlerExampleWithTryStatementInNonTryStatement.class.getSimpleName()
            + JavaProjectMaker.JAVA_FILE_EXTENSION,
        "package "
            + DummyHandlerExampleWithTryStatementInNonTryStatement.class.getPackage().getName()
            + ";\n"
            + javaFile2String.getFileContent());

    Path path =
        new Path(
            PathUtils.getPathOfClassUnderSrcFolder(
                DummyHandlerExampleWithTryStatementInNonTryStatement.class, testProjectName));
    // Create AST to parse
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    // 設定要被建立AST的檔案
    parser.setSource(
        JavaCore.createCompilationUnitFrom(ResourcesPlugin.getWorkspace().getRoot().getFile(path)));
    parser.setResolveBindings(true);
    // 取得AST
    compilationUnitWithTSINTS = (CompilationUnit) parser.createAST(null);
    compilationUnitWithTSINTS.recordModifications();
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnitWithTSINTS);

    // 確認初始值
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());

    // do this test
    compilationUnitWithTSINTS.accept(dummyHandlerVisitor);

    // 驗證總共抓到幾個bad smell
    assertEquals(2, dummyHandlerVisitor.getDummyList().size());
  }
コード例 #27
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);
  }
コード例 #28
0
    /** {@inheritDoc} */
    public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups)
        throws CoreException {
      InferTypeArgumentsTCModel model = new InferTypeArgumentsTCModel();
      InferTypeArgumentsConstraintCreator creator =
          new InferTypeArgumentsConstraintCreator(model, true);

      CompilationUnit root = cuRewrite.getRoot();
      root.accept(creator);

      InferTypeArgumentsConstraintsSolver solver = new InferTypeArgumentsConstraintsSolver(model);
      InferTypeArgumentsUpdate update = solver.solveConstraints(new NullProgressMonitor());
      solver = null; // free caches

      ASTNode[] nodes =
          InferTypeArgumentsRefactoring.inferArguments(fTypes, update, model, cuRewrite);
      if (nodes.length == 0) return;

      ASTRewrite astRewrite = cuRewrite.getASTRewrite();
      for (int i = 0; i < nodes.length; i++) {
        if (nodes[i] instanceof ParameterizedType) {
          ParameterizedType type = (ParameterizedType) nodes[0];
          List args = (List) type.getStructuralProperty(ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
          int j = 0;
          for (Iterator iter = args.iterator(); iter.hasNext(); ) {
            LinkedProposalPositionGroup group =
                new LinkedProposalPositionGroup("G" + i + "_" + j); // $NON-NLS-1$ //$NON-NLS-2$
            Type argType = (Type) iter.next();
            if (!positionGroups.hasLinkedPositions()) {
              group.addPosition(astRewrite.track(argType), true);
            } else {
              group.addPosition(astRewrite.track(argType), false);
            }
            positionGroups.addPositionGroup(group);
            j++;
          }
        }
      }
      positionGroups.setEndPosition(astRewrite.track(nodes[0]));
    }
コード例 #29
0
  @Test
  public void testGetCarelessCleanupListWithUserDefiendOnlyMethods() throws Exception {
    // 產生設定檔
    SmellSettings smellSettings = new SmellSettings(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    smellSettings.addCarelessCleanupPattern("rain", true);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);

    // 重新產生Visitor,使得設定值有存入CarelessCleaupVisitor
    carelessCleanupVisitor = new CarelessCleanupVisitor2(compilationUnit);

    // 偵測結果
    int carelessCleanupSmellCount = 0;
    assertNotNull(compilationUnit);
    assertNotNull(carelessCleanupVisitor);
    compilationUnit.accept(carelessCleanupVisitor);
    if (carelessCleanupVisitor.getCarelessCleanupList() != null) {
      carelessCleanupSmellCount = carelessCleanupVisitor.getCarelessCleanupList().size();
    }
    assertEquals(
        colloectBadSmellListContent(carelessCleanupVisitor.getCarelessCleanupList()),
        33,
        carelessCleanupSmellCount);
  }
コード例 #30
0
 /**
  * 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);
   }
 }