/*
   * (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;
  }
  /**
   * 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();
  }
Пример #3
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;
 }
  private void performCu(int expectedInitialStatus, int expectedFinalStatus) throws Exception {
    IPackageFragment packageP = getPackageP();
    String cuName = "A";
    ICompilationUnit cu = packageP.getCompilationUnit(cuName + ".java");
    if (!cu.exists()) cu = createCUfromTestFile(packageP, cuName);
    IJavaElement[] elements = {cu};
    boolean performed = perform(elements, expectedInitialStatus, expectedFinalStatus);
    if (!performed) return;

    String expected = getFileContents(getOutputTestFileName("A"));
    String actual = cu.getSource();
    assertEqualLines(expected, actual);
  }
Пример #5
0
  /**
   * Finds a compilation unit by looking in all the available java projects.
   *
   * @param file The absolute file path to find.
   * @return The compilation unit.
   * @throws IllegalArgumentException If the file is not found.
   */
  public static ICompilationUnit getCompilationUnit(String file) throws Exception {
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    for (int ii = 0; ii < projects.length; ii++) {
      IJavaProject javaProject = getJavaProject(projects[ii]);

      ICompilationUnit src = getCompilationUnit(javaProject, file);
      if (src != null && src.exists()) {
        return src;
      }
    }
    throw new IllegalArgumentException(
        Services.getMessage("src.file.not.found", file, ".classpath"));
  }
  /* (non-Javadoc)
   * @see org.eclipse.team.ui.history.ElementLocalHistoryPageSource#getFile(java.lang.Object)
   */
  public IFile getFile(Object input) {
    // extract CU from input
    ICompilationUnit cu = null;
    if (input instanceof ICompilationUnit) cu = (ICompilationUnit) input;
    else if (input instanceof IMember) cu = ((IMember) input).getCompilationUnit();

    if (cu == null || !cu.exists()) return null;

    // get to original CU
    cu = cu.getPrimary();

    // find underlying file
    IFile file = (IFile) cu.getResource();
    if (file != null && file.exists()) return file;
    return null;
  }
Пример #7
0
  /**
   * @since 2.3
   * @deprecated This method is not used anymore.
   */
  @Deprecated
  protected IType getPrimaryTypeFrom(ICompilationUnit cu) {
    try {
      if (cu.exists()) {
        IType primaryType = cu.findPrimaryType();
        if (primaryType != null) return primaryType;

        // if no exact match is found, return the first public type in CU (if any)
        for (IType type : cu.getTypes()) {
          if (Flags.isPublic(type.getFlags())) return type;
        }
      }
    } catch (JavaModelException e) {
      if (LOGGER.isDebugEnabled()) LOGGER.debug(e, e);
    }
    return null;
  }
  private void helper1(
      String[] methodNames,
      String[][] signatures,
      boolean deleteAllInSourceType,
      boolean deleteAllMatchingMethods,
      boolean replaceOccurences)
      throws Exception {
    ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
    IType type = getType(cu, "B");
    IMethod[] methods = getMethods(type, methodNames, signatures);

    ExtractSupertypeProcessor processor = createRefactoringProcessor(methods);
    Refactoring refactoring = processor.getRefactoring();
    processor.setMembersToMove(methods);

    assertTrue("activation", refactoring.checkInitialConditions(new NullProgressMonitor()).isOK());

    processor.setTypesToExtract(new IType[] {type});
    processor.setTypeName("Z");
    processor.setCreateMethodStubs(true);
    processor.setInstanceOf(false);
    processor.setReplace(replaceOccurences);
    if (deleteAllInSourceType) processor.setDeletedMethods(methods);
    if (deleteAllMatchingMethods)
      processor.setDeletedMethods(
          getMethods(processor.getMatchingElements(new NullProgressMonitor(), false)));

    RefactoringStatus status = refactoring.checkFinalConditions(new NullProgressMonitor());
    assertTrue("precondition was supposed to pass", !status.hasError());
    performChange(refactoring, false);

    String expected = getFileContents(getOutputTestFileName("A"));
    String actual = cu.getSource();
    assertEqualLines(expected, actual);

    expected = getFileContents(getOutputTestFileName("Z"));
    ICompilationUnit unit = getPackageP().getCompilationUnit("Z.java");
    if (!unit.exists()) assertTrue("extracted compilation unit does not exist", false);
    actual = unit.getBuffer().getContents();
    assertEqualLines(expected, actual);
  }
  private void helper1(
      int startLine,
      int startColumn,
      int endLine,
      int endColumn,
      boolean makeFinal,
      boolean makeStatic,
      String className,
      int visibility)
      throws Exception {
    ICompilationUnit cu = createCUfromTestFile(getPackageP(), true, true);
    ISourceRange selection =
        TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn);
    ConvertAnonymousToNestedRefactoring ref =
        new ConvertAnonymousToNestedRefactoring(cu, selection.getOffset(), selection.getLength());

    RefactoringStatus preconditionResult = ref.checkInitialConditions(new NullProgressMonitor());
    if (preconditionResult.isOK()) preconditionResult = null;
    assertEquals("activation was supposed to be successful", null, preconditionResult);

    ref.setClassName(className);
    ref.setDeclareFinal(makeFinal);
    ref.setDeclareStatic(makeStatic);
    ref.setVisibility(visibility);

    if (preconditionResult == null)
      preconditionResult = ref.checkFinalConditions(new NullProgressMonitor());
    else preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor()));
    if (preconditionResult.isOK()) preconditionResult = null;
    assertEquals("precondition was supposed to pass", null, preconditionResult);

    performChange(ref, false);

    IPackageFragment pack = (IPackageFragment) cu.getParent();
    String newCuName = getSimpleTestFileName(true, true);
    ICompilationUnit newcu = pack.getCompilationUnit(newCuName);
    assertTrue(newCuName + " does not exist", newcu.exists());
    assertEqualLines(getFileContents(getTestFileName(true, false)), newcu.getSource());
  }