public void testFinderOfNonPublicSubclass() throws Exception {
    IPath projectPath = createGenericProject();
    IPath root = projectPath.append("src");
    env.addGroovyClass(
        root, "p2", "Hello", "package p2;\n" + "class Hello extends Tester {\n" + "}\n");
    env.addGroovyClass(
        root,
        "p2",
        "Tester",
        "package p2;\n"
            + "import junit.framework.TestCase\n"
            + "abstract class Tester extends TestCase {\n"
            + "}\n");

    incrementalBuild(projectPath);
    expectingNoProblems();

    IFile file = getFile(projectPath, "src/p2/Hello.groovy");
    ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
    IType type = unit.getType("Hello");
    assertTrue("Groovy type Hello should exist.", type.exists());
    assertTrue(
        "Groovy type Hello should be a test suite (even though it is non-public)",
        new JUnit4TestFinder().isTest(type));
    file = getFile(projectPath, "src/p2/Tester.groovy");
    unit = JavaCore.createCompilationUnitFrom(file);
    type = unit.getType("Tester");
    assertTrue("Groovy type Tester should exist.", type.exists());
    assertFalse(
        "Groovy type Tester should not be a test suite (it is abstract)",
        new JUnit4TestFinder().isTest(type));
  }
    @Override
    public JavaContentAssistInvocationContext apply(IInvocationContext context) {
      ICompilationUnit cu = context.getCompilationUnit();
      int offset = context.getSelectionOffset();
      try {
        cu.codeComplete(
            offset,
            new CompletionRequestor() {
              @Override
              public void acceptContext(CompletionContext context) {
                internalContext = context;
              }

              @Override
              public boolean isExtendedContextRequired() {
                return true;
              }

              @Override
              public void accept(CompletionProposal proposal) {}
            });
      } catch (JavaModelException e) {
        propagate(e);
      }

      JavaEditor editor = cast(EditorUtility.isOpenInEditor(cu));
      ISourceViewer viewer = editor.getViewer();
      return new JavaContentAssistInvocationContext(viewer, offset, editor) {

        @Override
        public CompletionContext getCoreContext() {
          return internalContext;
        }
      };
    }
  public void testUsingRunWithAnnotation() throws Exception {
    IPath projectPath = createGenericProject();

    IPath root = projectPath.append("src");
    env.addGroovyClass(
        root,
        "",
        "T3",
        ""
            + "import org.junit.runner.RunWith\n"
            + "@RunWith(org.junit.runners.Suite.class)\n"
            + "public class T3 {\n"
            + "def void t() {\n"
            + "return;\n"
            + "}\n"
            + "}\n");
    incrementalBuild(projectPath);
    expectingNoProblems();

    IFile file = getFile(projectPath, "src/T3.groovy");
    ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
    IType type = unit.getType("T3");
    assertTrue("Groovy type T3 should exist.", type.exists());
    assertTrue("Groovy type T3 should be a test suite", new JUnit4TestFinder().isTest(type));
  }
 /**
  * Collects the existing tags on the {@link IJavaElement} we have been activated on
  *
  * @param element
  * @param jcontext
  * @throws JavaModelException
  * @throws BadLocationException
  */
 private void collectExistingTags(
     IJavaElement element, JavaContentAssistInvocationContext jcontext) throws JavaModelException {
   if (element instanceof IMember) {
     IMember member = (IMember) element;
     ICompilationUnit cunit = jcontext.getCompilationUnit();
     if (cunit != null) {
       if (cunit.isWorkingCopy()) {
         cunit.reconcile(ICompilationUnit.NO_AST, false, false, null, null);
       }
       fParser.setSource(member.getSource().toCharArray());
       fParser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
       Map<String, String> options = element.getJavaProject().getOptions(true);
       options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
       fParser.setCompilerOptions(options);
       fParser.setStatementsRecovery(false);
       fParser.setResolveBindings(false);
       fParser.setBindingsRecovery(false);
       ASTNode ast = fParser.createAST(null);
       TagCollector collector = new TagCollector();
       if (ast.getNodeType() == ASTNode.TYPE_DECLARATION) {
         TypeDeclaration typeDeclaration = (TypeDeclaration) ast;
         List<BodyDeclaration> bodyDeclarations = typeDeclaration.bodyDeclarations();
         if (bodyDeclarations.size() == 1) {
           // only one element should be there as we are parsing a
           // specific member
           BodyDeclaration bodyDeclaration = bodyDeclarations.iterator().next();
           Javadoc javadoc = bodyDeclaration.getJavadoc();
           if (javadoc != null) {
             javadoc.accept(collector);
           }
         }
       }
     }
   }
 }
  /*
   * Tests that the same number of calls to discardWorkingCopy() is needed for non-primary working copy
   * to be discarded.
   */
  public void testDiscardWorkingCopy3() throws CoreException {
    try {
      ICompilationUnit cu = getCompilationUnit("P/X.java");
      TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
      this.workingCopy = cu.getWorkingCopy(owner, null);
      this.workingCopy = cu.getWorkingCopy(owner, null);
      this.workingCopy = cu.getWorkingCopy(owner, null);
      assertTrue("should be in working copy mode", this.workingCopy.isWorkingCopy());
      assertTrue("should be opened", this.workingCopy.isOpen());
      assertTrue("should exist", this.workingCopy.exists());

      this.workingCopy.discardWorkingCopy();
      assertTrue("should still be in working copy mode (1)", this.workingCopy.isWorkingCopy());
      assertTrue("should still be opened", this.workingCopy.isOpen());
      assertTrue("should still exist", this.workingCopy.exists());

      this.workingCopy.discardWorkingCopy();
      this.workingCopy.discardWorkingCopy();
      assertTrue("should still be in working copy mode (2)", this.workingCopy.isWorkingCopy());
      assertTrue("should no longer be opened", !this.workingCopy.isOpen());
      assertTrue("should no longer exist", !this.workingCopy.exists());

    } finally {
      if (this.workingCopy != null) {
        int max = 3;
        while (this.workingCopy.isWorkingCopy() && max-- > 0) {
          this.workingCopy.discardWorkingCopy();
        }
      }
    }
  }
  /*
   * Ensures that getPrimary() on a non-primary working copy returns the primary compilation unit.
   */
  public void testGetPrimary1() throws CoreException {
    ICompilationUnit cu = getCompilationUnit("P/X.java");
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = cu.getWorkingCopy(owner, null);

    assertEquals("Unexpected compilation unit", cu, this.workingCopy.getPrimary());
  }
  /**
   * Evaluates a 'java' template in the context of a compilation unit
   *
   * @param template the template to be evaluated
   * @param compilationUnit the compilation unit in which to evaluate the template
   * @param position the position inside the compilation unit for which to evaluate the template
   * @return the evaluated template
   * @throws CoreException in case the template is of an unknown context type
   * @throws BadLocationException in case the position is invalid in the compilation unit
   * @throws TemplateException in case the evaluation fails
   */
  public static String evaluateTemplate(
      Template template, ICompilationUnit compilationUnit, int position)
      throws CoreException, BadLocationException, TemplateException {

    TemplateContextType contextType =
        JavaPlugin.getDefault()
            .getTemplateContextRegistry()
            .getContextType(template.getContextTypeId());
    if (!(contextType instanceof CompilationUnitContextType))
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              JavaUI.ID_PLUGIN,
              IStatus.ERROR,
              JavaTemplateMessages.JavaContext_error_message,
              null));

    IDocument document = new Document();
    if (compilationUnit != null && compilationUnit.exists())
      document.set(compilationUnit.getSource());

    CompilationUnitContext context =
        ((CompilationUnitContextType) contextType)
            .createContext(document, position, 0, compilationUnit);
    context.setForceEvaluation(true);

    TemplateBuffer buffer = context.evaluate(template);
    if (buffer == null) return null;
    return buffer.getString();
  }
Example #8
0
  private void runOnMultiple(final ICompilationUnit[] cus) {
    ICleanUp[] cleanUps = getCleanUps(cus);
    if (cleanUps == null) return;

    MultiStatus status =
        new MultiStatus(
            JavaUI.ID_PLUGIN, IStatus.OK, ActionMessages.CleanUpAction_MultiStateErrorTitle, null);
    for (int i = 0; i < cus.length; i++) {
      ICompilationUnit cu = cus[i];

      if (!ActionUtil.isOnBuildPath(cu)) {
        String cuLocation = BasicElementLabels.getPathLabel(cu.getPath(), false);
        String message =
            Messages.format(ActionMessages.CleanUpAction_CUNotOnBuildpathMessage, cuLocation);
        status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null));
      }
    }
    if (!status.isOK()) {
      ErrorDialog.openError(getShell(), getActionName(), null, status);
      return;
    }

    try {
      performRefactoring(cus, cleanUps);
    } catch (InvocationTargetException e) {
      JavaPlugin.log(e);
      if (e.getCause() instanceof CoreException) showUnexpectedError((CoreException) e.getCause());
    }
  }
  /**
   * Tests if a MethodBreakPoint was moved appropriately.
   *
   * @throws Exception
   */
  public void testMethodBreakPoint() throws Exception {
    cleanTestFiles();
    IJavaProject javaProject = get14Project();
    ICompilationUnit cunit = getCompilationUnit(javaProject, "src", "a.b.c", "Movee.java");
    IType type = cunit.getType("NonPublicType");

    try {
      // create an EntryMethod Breakpoint to test & do so
      createMethodBreakpoint(
          "a.b.c", "Movee.java", "NonPublicType", "nonPublicMethod", "()V", true, false);
      refactor(javaProject, type);
      IBreakpoint[] breakpoints = getBreakpointManager().getBreakpoints();
      assertEquals("wrong number of breakpoints", 1, breakpoints.length);
      IJavaMethodBreakpoint methodBreakpoint = (IJavaMethodBreakpoint) breakpoints[0];
      assertEquals("wrong type name", "a.b.MoveeRecipient", methodBreakpoint.getTypeName());
      assertEquals(
          "breakpoint attached to wrong method",
          "nonPublicMethod",
          methodBreakpoint.getMethodName());
    } catch (Exception e) {
      throw e;
    } finally {
      removeAllBreakpoints();
    }
  }
  /**
   * Updates the content of <code>cu</code>, modifying the type name and/or package declaration as
   * necessary.
   *
   * @return an AST rewrite or null if no rewrite needed
   */
  private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName)
      throws JavaModelException {
    String[] currPackageName = ((PackageFragment) cu.getParent()).names;
    String[] destPackageName = dest.names;
    if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
      return null; // nothing to change
    } else {
      // ensure cu is consistent (noop if already consistent)
      cu.makeConsistent(this.progressMonitor);

      // GROOVY start
      // don't use the ASTParser if not a Java compilation unit
      if (LanguageSupportFactory.isInterestingSourceFile(cu.getElementName())) {
        // ZALUUM
        // old return updateNonJavaContent(cu, destPackageName, currPackageName, newName);
        return LanguageSupportFactory.updateContent(cu, destPackageName, currPackageName, newName);
        // END ZALUUM
      }
      // GROOVY end

      this.parser.setSource(cu);
      CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
      AST ast = astCU.getAST();
      ASTRewrite rewrite = ASTRewrite.create(ast);
      updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
      updatePackageStatement(astCU, destPackageName, rewrite, cu);
      return rewrite.rewriteAST();
    }
  }
  /** Creates two simple classes, A and B. Sets the instance fields fType1 and fType2. */
  public void createSimpleClasses() throws CoreException, JavaModelException {
    createPackages();

    ICompilationUnit cu1 = fPack1.getCompilationUnit("A.java");

    fType1 =
        cu1.createType(
            "public class A {\n"
                + "public A() {\n"
                + "}\n "
                + "public void method1() {\n"
                + "}\n "
                + "public void method2() {\n"
                + "  method1();\n"
                + "}\n "
                + "public void recursiveMethod1() {\n"
                + "  recursiveMethod2();\n "
                + "}\n "
                + "public void recursiveMethod2() {\n"
                + "  recursiveMethod1();\n "
                + "}\n"
                + "}\n",
            null,
            true,
            null);

    ICompilationUnit cu2 = fPack2.getCompilationUnit("B.java");
    fType2 =
        cu2.createType(
            "public class B extends pack1.A {\npublic void method3() { method1(); method2(); }\n public void method4() { method3(); }\n}\n",
            null,
            true,
            null);
  }
  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);
  }
  public static String getMatchedPackage(String className, ICompilationUnit cUnit)
      throws JavaModelException {
    int higherAccuracy = 0;
    String matchedPackage = cUnit.getPackageDeclarations()[0].getElementName();
    IImportDeclaration[] imports = cUnit.getImports();
    for (IImportDeclaration impDec : imports) {
      String fullName = impDec.getElementName();
      int dotIndex = fullName.lastIndexOf('.');

      String lastNameOfImport = fullName.substring(dotIndex + 1);
      if (lastNameOfImport.equals(className) && higherAccuracy < 2) {
        matchedPackage = fullName.substring(0, dotIndex);
        higherAccuracy = 2;
      } else if (lastNameOfImport.equals("*") && higherAccuracy < 1) {
        matchedPackage = fullName.substring(0, dotIndex);
        higherAccuracy = 1;
      }
    }

    if (higherAccuracy > 0) return matchedPackage;

    if (cUnit.getType(className) != null) return cUnit.getPackageDeclarations()[0].getElementName();

    return "java.lang";
  }
  /**
   * Gets the fully qualified class name for an active file. For example, its value is foo.bar.Baz.
   *
   * @param file Get fully qualified class file.
   * @return The fully qualified class name. For example,foo.bar.Baz.
   */
  private String getFullyQualifedClassName(IFile file) {
    String fullClassName = "";
    if (file.exists() && file.getName().endsWith(EclipseSensorConstants.JAVA_EXT)) {
      ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create(file);
      String className = compilationUnit.getElementName();
      if (className.endsWith(EclipseSensorConstants.JAVA_EXT)) {
        className = className.substring(0, className.length() - 5);
      }

      try {
        IPackageDeclaration[] packageDeclarations = compilationUnit.getPackageDeclarations();
        // Should only have one package declaration
        if (packageDeclarations == null || packageDeclarations.length == 0) {
          fullClassName = className;
        } else {
          fullClassName = packageDeclarations[0].getElementName() + '.' + className;
        }
      } catch (JavaModelException e) {
        // This exception will be thrown if user is working on a Java but did not open
        // it with "Java Perspective". Thus, the Java Model does not exist to parse
        // Java files. So we only log out exception while Eclipse's Java Perspective
        // exits.
        if (!e.isDoesNotExist()) {
          EclipseSensorPlugin.getDefault().log(file.getName(), e);
        }
      }
    }

    return fullClassName;
  }
  /**
   * @param input the editor input
   * @param offset the offset in the file
   * @return the element at the given offset
   */
  protected IJavaElement getElementAt(IEditorInput input, int offset) {
    if (input instanceof IClassFileEditorInput) {
      try {
        return ((IClassFileEditorInput) input).getClassFile().getElementAt(offset);
      } catch (JavaModelException ex) {
        return null;
      }
    }

    IWorkingCopyManager manager = JavaPlugin.getDefault().getWorkingCopyManager();
    ICompilationUnit unit = manager.getWorkingCopy(input);
    if (unit != null)
      try {
        if (unit.isConsistent()) return unit.getElementAt(offset);
        else {
          /*
           * XXX: We should set the selection later when the
           *      CU is reconciled.
           *      see https://bugs.eclipse.org/bugs/show_bug.cgi?id=51290
           */
        }
      } catch (JavaModelException ex) {
        // fall through
      }
    return null;
  }
  /*
   * Ensures that searching takes the owner's working copies into account.
   */
  public void testSearch2() throws CoreException {
    ICompilationUnit cu = getCompilationUnit("P/X.java");
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = cu.getWorkingCopy(owner, null);

    // remove type X
    this.workingCopy.getBuffer().setContents("");
    this.workingCopy.makeConsistent(null);

    SearchPattern pattern =
        SearchPattern.createPattern(
            "X",
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    JavaSearchTests.JavaSearchResultCollector resultCollector =
        new JavaSearchTests.JavaSearchResultCollector();
    new SearchEngine(owner)
        .search(
            pattern,
            new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
            SearchEngine.createWorkspaceScope(),
            resultCollector,
            null);
    assertEquals(
        "", // should not find any in the owner's context
        resultCollector.toString());
  }
Example #17
0
  /**
   * Determines if the supplied src file contains an import for the supplied type (including
   * wildcard .* imports).
   *
   * @param src The compilation unit.
   * @param type The type.
   * @return true if the src file has a qualifying import.
   */
  public static boolean containsImport(ICompilationUnit src, IType type) throws Exception {
    String typePkg = type.getPackageFragment().getElementName();

    IPackageDeclaration[] packages = src.getPackageDeclarations();
    String pkg = packages.length > 0 ? packages[0].getElementName() : null;

    // classes in same package are auto imported.
    if ((pkg == null && typePkg == null) || (pkg != null && pkg.equals(typePkg))) {
      return true;
    }

    // java.lang is auto imported.
    if (JAVA_LANG.equals(typePkg)) {
      return true;
    }

    typePkg = typePkg + ".*";
    String typeName = type.getFullyQualifiedName().replace('$', '.');

    IImportDeclaration[] imports = src.getImports();
    for (int ii = 0; ii < imports.length; ii++) {
      String name = imports[ii].getElementName();
      if (name.equals(typeName) || name.equals(typePkg)) {
        return true;
      }
    }
    return false;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jface.wizard.Wizard#performFinish()
   */
  @Override
  public boolean performFinish() {
    boolean saved = false;

    try {
      DoSave doSave = new DoSave();

      getContainer().run(false, false, doSave);

      if (doSave.exception != null) {
        throw doSave.exception;
      } else {
        saved = doSave.saved;
      }
    } catch (Exception e) {
      IStatus status =
          new Status(IStatus.ERROR, CodeUtilsActivator.PLUGIN_ID, e.getLocalizedMessage());
      EclipseUtils.showErrorDialog(
          CodeUtilsNLS.UI_GenericErrorDialogTitle,
          CodeUtilsNLS.ERR_BuildingBlockCreation_ErrorMessage,
          status);
    }

    if (saved) {
      ICompilationUnit javaFile =
          getBuildingBlock()
              .getPackageFragment()
              .getCompilationUnit(getBuildingBlock().getName() + ".java"); // $NON-NLS-1$

      if ((javaFile != null) && javaFile.exists()) {
        try {
          JavaUI.openInEditor(javaFile);
        } catch (Exception e) {
          // Do nothing
          AndmoreLogger.error(
              NewActivityBasedOnTemplateWizard.class,
              "Could not open the activity " //$NON-NLS-1$
                  + getBuildingBlock().getName()
                  + " on an editor.",
              e); //$NON-NLS-1$
        }
      }
    }

    if (saved) {
      // Collecting usage data for statistical purposes
      try {
        AndmoreLogger.collectUsageData(
            UsageDataConstants.WHAT_BUILDINGBLOCK_ACTIVITY,
            UsageDataConstants.KIND_BUILDINGBLOCK,
            UsageDataConstants.DESCRIPTION_DEFAULT,
            CodeUtilsActivator.PLUGIN_ID,
            CodeUtilsActivator.getDefault().getBundle().getVersion().toString());
      } catch (Throwable e) {
        // Do nothing, but error on the log should never prevent app
        // from working
      }
    }
    return saved;
  }
 public static ICompilationUnit createCU(IPackageFragment pack, String name, String contents)
     throws Exception {
   assertTrue(!pack.getCompilationUnit(name).exists());
   ICompilationUnit cu = pack.createCompilationUnit(name, contents, true, null);
   cu.save(null, true);
   return cu;
 }
Example #20
0
  /** @see edu.buffalo.cse.green.editor.model.commands.DeleteCommand#doDelete() */
  public void doDelete() {
    RootModel root = _typeModel.getRootModel();

    // Remove relationships first
    List<RelationshipModel> rels = root.getRelationships();

    // No iterators here due to CME's (ConcurrentModificationException)
    // Removal of relationships causes modifications to the rels list.
    for (int i = 0; i < rels.size(); i++) {
      IType t = _typeModel.getType();
      RelationshipModel r = rels.get(i);
      if (r.getSourceType() == t || r.getTargetType() == t) {
        DeleteCommand drc = r.getDeleteCommand(DiagramEditor.findProjectEditor(root.getProject()));
        drc.suppressMessage(true);
        drc.execute();
      }
    }

    _typeModel.removeChildren(); // remove fields/methods
    _typeModel.removeFromParent();
    try {
      IType type = _typeModel.getType();
      ICompilationUnit cu = (ICompilationUnit) type.getAncestor(IJavaElement.COMPILATION_UNIT);

      if (type.equals(cu.findPrimaryType())) {
        cu.delete(true, PlugIn.getEmptyProgressMonitor());
      } else {
        type.delete(true, PlugIn.getEmptyProgressMonitor());
      }
    } catch (JavaModelException e) {
      e.printStackTrace();
    }
    root.updateRelationships();
  }
Example #21
0
  /**
   * 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();
  }
  /*
   * Ensures that getPrimaryElement() on an element of a non-primary working copy returns
   * an element ofthe primary compilation unit.
   */
  public void testGetPrimaryElement1() throws CoreException {
    ICompilationUnit cu = getCompilationUnit("P/X.java");
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = cu.getWorkingCopy(owner, null);
    IJavaElement element = this.workingCopy.getType("X");

    assertEquals("Unexpected element", cu.getType("X"), element.getPrimaryElement());
  }
 public IType createType(IPackageFragment pack, String cuName, String source)
     throws JavaModelException {
   StringBuffer buf = new StringBuffer();
   buf.append("package " + pack.getElementName() + ";\n");
   buf.append("\n");
   buf.append(source);
   ICompilationUnit cu = pack.createCompilationUnit(cuName, buf.toString(), false, null);
   return cu.getTypes()[0];
 }
Example #24
0
 /**
  * Finds a compilation unit by looking in the java project of the supplied name.
  *
  * @param project The name of the project to locate the file in.
  * @param file The file to find.
  * @return The compilation unit.
  */
 public static ICompilationUnit getCompilationUnit(String project, String file) throws Exception {
   IJavaProject javaProject = getJavaProject(project);
   ICompilationUnit src = getCompilationUnit(javaProject, file);
   if (src == null || !src.exists()) {
     throw new IllegalArgumentException(
         Services.getMessage("src.file.not.found", file, ".classpath"));
   }
   return src;
 }
 static ICompilationUnit createNewWorkingCopy(
     ICompilationUnit cu, TextChangeManager manager, WorkingCopyOwner owner, SubProgressMonitor pm)
     throws CoreException {
   ICompilationUnit newWc = cu.getWorkingCopy(owner, null);
   String previewContent = manager.get(cu).getPreviewContent(new NullProgressMonitor());
   newWc.getBuffer().setContents(previewContent);
   newWc.reconcile(ICompilationUnit.NO_AST, false, owner, pm);
   return newWc;
 }
Example #26
0
 @Override
 public String toString() {
   return "("
       + ModifiableMClass.class.getSimpleName()
       + ")"
       + jdtCu.getParent().getElementName()
       + "."
       + jdtCu.getElementName();
 }
Example #27
0
  private void check(IResource resource, Architecture architecture, boolean reextractDependencies)
      throws CoreException {
    if (resource instanceof IFile && resource.getName().endsWith(".java")) {
      final IFile file = (IFile) resource;
      MarkerUtils.deleteMarkers(file);

      final ICompilationUnit unit = ((ICompilationUnit) JavaCore.create((IFile) resource));

      /* We only consider the units linked to source-folders */
      if (!unit.isOpen()) {
        return;
      }

      final String className = DCLUtil.getClassName(unit);

      /* We only consider the units without compilation errors*/
      if (file.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)
          == IMarker.SEVERITY_ERROR) {
        // MarkerUtils.addErrorMarker(this.getProject(), "DCLcheck has not verified class " +
        // className + " because it contains compilation errors.");
        return;
      }

      try {
        final Collection<Dependency> dependencies;
        if (reextractDependencies) {
          dependencies = DCLUtil.getDependenciesUsingAST(unit);
          architecture.updateDependencies(className, dependencies);
          DCLPersistence.persist(this.getProject(), className, dependencies);
        } else {
          dependencies = architecture.getDependencies(className);
        }

        for (DependencyConstraint dc : architecture.getDependencyConstraints()) {
          Collection<ArchitecturalDrift> result =
              dc.validate(
                  className,
                  architecture.getModules(),
                  architecture.getProjectClasses(),
                  dependencies,
                  this.getProject());
          if (result != null && !result.isEmpty()) {
            for (ArchitecturalDrift ad : result) {
              MarkerUtils.addMarker(file, ad);
            }
          }
        }
      } catch (Exception e) {
        MarkerUtils.addErrorMarker(
            this.getProject(), "There was a problem in extracting dependencies from " + className);
        CoreException ce = new CoreException(Status.CANCEL_STATUS);
        ce.setStackTrace(e.getStackTrace());
        throw ce;
      }
    }
  }
Example #28
0
 /**
  * @since 2.3
  * @deprecated This method is not used anymore.
  */
 @Deprecated
 protected String getExpectedPrimaryTypeNameFor(ICompilationUnit cu) {
   String fileName = cu.getElementName();
   String typeName = fileName.substring(0, fileName.lastIndexOf('.'));
   IPackageFragment pkg = (IPackageFragment) cu.getParent();
   if (!pkg.isDefaultPackage()) {
     typeName = pkg.getElementName() + '.' + typeName;
   }
   return typeName;
 }
Example #29
0
 @Override
 public void setName(String name) {
   try {
     IPackageFragment jdtPkg = (IPackageFragment) jdtCu.getParent();
     jdtCu.rename(name + ".java", false, MyMonitor.currentMonitor());
     jdtCu = jdtPkg.getCompilationUnit(name + ".java");
   } catch (JavaModelException e) {
     throw new MyRuntimeException("Rename " + this + " to " + name, e);
   }
 }
  public void testExtractInterfaceFromInterface2() throws Exception {
    String className = "A";
    String extendingInterfaceName = "I1";
    String newInterfaceName = "B";

    IType clas =
        getType(createCUfromTestFile(getPackageP(), getTopLevelTypeName(className)), className);
    ICompilationUnit cu = clas.getCompilationUnit();
    IPackageFragment pack = (IPackageFragment) cu.getParent();

    getType(
        createCUfromTestFile(getPackageP(), getTopLevelTypeName(extendingInterfaceName)),
        extendingInterfaceName);

    IPackageFragmentRoot root = RefactoringTestSetup.getDefaultSourceFolder();
    assertNotNull(root);
    IPackageFragment p2 = root.createPackageFragment("p2", true, null);
    getType(createCUfromTestFile(p2, getTopLevelTypeName("I2")), "I2");

    ExtractInterfaceProcessor processor =
        new ExtractInterfaceProcessor(
            clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject()));
    Refactoring ref = new ProcessorBasedRefactoring(processor);

    processor.setTypeName(newInterfaceName);
    assertEquals(
        "interface name should be accepted",
        RefactoringStatus.OK,
        processor.checkTypeName(newInterfaceName).getSeverity());

    IMember[] extractableMembers = processor.getExtractableMembers();
    final IMember[] members = new IMember[extractableMembers.length - 1];
    List<IMember> list = new ArrayList<>();
    for (IMember iMember : extractableMembers) {
      if (!(iMember instanceof IField)) {
        list.add(iMember);
      }
    }
    processor.setExtractedMembers(list.toArray(members));
    processor.setReplace(true);
    processor.setAnnotations(false);
    RefactoringStatus performRefactoring = performRefactoring(ref);
    assertEquals("was supposed to pass", null, performRefactoring);
    assertEqualLines(
        "incorrect changes in " + className,
        getFileContents(getOutputTestFileName(className)),
        cu.getSource());

    ICompilationUnit interfaceCu = pack.getCompilationUnit(newInterfaceName + ".java");
    assertEqualLines(
        "incorrect interface created",
        getFileContents(getOutputTestFileName(newInterfaceName)),
        interfaceCu.getSource());
  }