Exemplo n.º 1
0
  public void testSearchAfterDeletion()
      throws JavaModelException, PartInitException, IOException, CoreException {
    view = (ActiveSearchView) JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    if (view != null) {
      assertEquals(0, view.getViewer().getTree().getItemCount());

      IWorkbenchPart part =
          PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
      IMethod m1 = type1.createMethod("void m1() {\n m2() \n}", null, true, null);
      IMethod m2 = type1.createMethod("void m2() { }", null, true, null);
      StructuredSelection sm2 = new StructuredSelection(m2);
      monitor.selectionChanged(part, sm2);
      IInteractionElement node =
          manager.processInteractionEvent(
              mockInterestContribution(m2.getHandleIdentifier(), scaling.getLandmark()));
      assertEquals(1, ContextCore.getContextManager().getActiveLandmarks().size());

      assertEquals(1, search(2, node).size());

      m1.delete(true, null);
      assertFalse(m1.exists());

      assertEquals(0, search(2, node).size());
    }
  }
Exemplo n.º 2
0
 @SuppressWarnings("deprecation")
 private boolean isParameterNamesAvailable() throws Exception {
   ASTParser parser = ASTParser.newParser(AST.JLS3);
   parser.setIgnoreMethodBodies(true);
   IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
   parser.setProject(javaProject);
   IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
   IBinding[] bindings = parser.createBindings(new IJavaElement[] {type}, null);
   ITypeBinding typeBinding = (ITypeBinding) bindings[0];
   IMethodBinding[] methods = typeBinding.getDeclaredMethods();
   for (IMethodBinding method : methods) {
     if (method.isConstructor()) {
       IMethod element = (IMethod) method.getJavaElement();
       if (element.exists()) {
         String[] parameterNames = element.getParameterNames();
         if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
           return true;
         }
       } else {
         return false;
       }
     }
   }
   return false;
 }
  private RefactoringStatus checkRelatedMethods() throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); ) {
      IMethod method = iter.next();

      result.merge(
          Checks.checkIfConstructorName(
              method, getNewElementName(), method.getDeclaringType().getElementName()));

      String[] msgData =
          new String[] {
            BasicElementLabels.getJavaElementName(method.getElementName()),
            BasicElementLabels.getJavaElementName(
                method.getDeclaringType().getFullyQualifiedName('.'))
          };
      if (!method.exists()) {
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_not_in_model, msgData));
        continue;
      }
      if (method.isBinary())
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_binary, msgData));
      if (method.isReadOnly())
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_read_only, msgData));
      if (JdtFlags.isNative(method))
        result.addError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_native_1, msgData));
    }
    return result;
  }
Exemplo n.º 4
0
  private void addAccessorOccurrences(
      IProgressMonitor pm,
      IMethod accessor,
      String editName,
      String newAccessorName,
      RefactoringStatus status)
      throws CoreException {
    Assert.isTrue(accessor.exists());

    IJavaSearchScope scope = RefactoringScopeFactory.create(accessor);
    SearchPattern pattern =
        SearchPattern.createPattern(
            accessor,
            IJavaSearchConstants.ALL_OCCURRENCES,
            SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
    SearchResultGroup[] groupedResults =
        RefactoringSearchEngine.search(
            pattern, scope, new MethodOccurenceCollector(accessor.getElementName()), pm, status);

    for (int i = 0; i < groupedResults.length; i++) {
      ICompilationUnit cu = groupedResults[i].getCompilationUnit();
      if (cu == null) continue;
      SearchMatch[] results = groupedResults[i].getSearchResults();
      for (int j = 0; j < results.length; j++) {
        SearchMatch searchResult = results[j];
        TextEdit edit =
            new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), newAccessorName);
        addTextEdit(fChangeManager.get(cu), editName, edit);
      }
    }
  }
 public static IMethod[] getMethods(IType type, String[] names, String[][] signatures) {
   if (names == null || signatures == null) return new IMethod[0];
   List methods = new ArrayList(names.length);
   for (int i = 0; i < names.length; i++) {
     IMethod method = type.getMethod(names[i], signatures[i]);
     assertTrue("method " + method.getElementName() + " does not exist", method.exists());
     if (!methods.contains(method)) methods.add(method);
   }
   return (IMethod[]) methods.toArray(new IMethod[methods.size()]);
 }
Exemplo n.º 6
0
  public void testOutputParameterOfMethod() throws JavaModelException {
    assertNotNull(getTestSetting().getRoleJavaElement());
    assertTrue(getTestSetting().getRoleJavaElement().exists());

    IMethod method = getTestSetting().getRoleJavaElement().getMethod(METHOD_NAME, new String[0]);
    assertNotNull(method);
    assertTrue(method.exists());

    String returnType = method.getReturnType();
    assertEquals(returnType, RETURN_TYPE);
  }
 public static IMethod getGetter(IField field) throws JavaModelException {
   String getterName = getGetterName(field, EMPTY, true);
   IMethod primaryCandidate =
       JavaModelUtil.findMethod(getterName, new String[0], false, field.getDeclaringType());
   if (!JavaModelUtil.isBoolean(field) || (primaryCandidate != null && primaryCandidate.exists()))
     return primaryCandidate;
   // bug 30906 describes why we need to look for other alternatives here (try with get... for
   // booleans)
   String secondCandidateName = getGetterName(field, EMPTY, false);
   return JavaModelUtil.findMethod(
       secondCandidateName, new String[0], false, field.getDeclaringType());
 }
Exemplo n.º 8
0
 private Set<IMethod> getExcludedMethods(
     IType objectClass, LinkedHashSet<MethodSkeleton<U>> methodSkeletons) throws Exception {
   Set<IMethod> excludedMethods = new HashSet<IMethod>();
   for (MethodSkeleton<U> methodSkeleton : methodSkeletons) {
     IMethod excludedMethod =
         objectClass.getMethod(
             methodSkeleton.getMethodName(), methodSkeleton.getMethodArguments(objectClass));
     if (excludedMethod.exists()) {
       excludedMethods.add(excludedMethod);
     }
   }
   return excludedMethods;
 }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    if (!fMethod.exists()) {
      String message =
          Messages.format(
              RefactoringCoreMessages.RenameMethodRefactoring_deleted,
              BasicElementLabels.getFileName(fMethod.getCompilationUnit()));
      return RefactoringStatus.createFatalErrorStatus(message);
    }

    RefactoringStatus result = Checks.checkAvailability(fMethod);
    if (result.hasFatalError()) return result;
    result.merge(Checks.checkIfCuBroken(fMethod));
    if (JdtFlags.isNative(fMethod))
      result.addError(RefactoringCoreMessages.RenameMethodRefactoring_no_native);
    return result;
  }
Exemplo n.º 10
0
 public String getNewGetterName() throws CoreException {
   IMethod primaryGetterCandidate =
       JavaModelUtil.findMethod(
           GetterSetterUtil.getGetterName(fField, new String[0]),
           new String[0],
           false,
           fField.getDeclaringType());
   if (!JavaModelUtil.isBoolean(fField)
       || (primaryGetterCandidate != null && primaryGetterCandidate.exists()))
     return GetterSetterUtil.getGetterName(
         fField.getJavaProject(),
         getNewElementName(),
         fField.getFlags(),
         JavaModelUtil.isBoolean(fField),
         null);
   // bug 30906 describes why we need to look for other alternatives here
   return GetterSetterUtil.getGetterName(
       fField.getJavaProject(), getNewElementName(), fField.getFlags(), false, null);
 }
Exemplo n.º 11
0
  private RefactoringStatus checkNewAccessor(IMethod existingAccessor, String newAccessorName)
      throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    IMethod accessor =
        JavaModelUtil.findMethod(
            newAccessorName,
            existingAccessor.getParameterTypes(),
            false,
            fField.getDeclaringType());
    if (accessor == null || !accessor.exists()) return null;

    String message =
        Messages.format(
            RefactoringCoreMessages.RenameFieldRefactoring_already_exists,
            new String[] {
              JavaElementUtil.createMethodSignature(accessor),
              BasicElementLabels.getJavaElementName(
                  fField.getDeclaringType().getFullyQualifiedName('.'))
            });
    result.addError(message, JavaStatusContext.create(accessor));
    return result;
  }
Exemplo n.º 12
0
 /**
  * Determines is the java element contains a specific method.
  *
  * <p>The syntax for the property tester is of the form: methodname, signature, modifiers.
  *
  * <ol>
  *   <li>methodname - case sensitive method name, required. For example, <code>toString</code>.
  *   <li>signature - JLS style method signature, required. For example, <code>(QString;)V</code>.
  *   <li>modifiers - optional space separated list of modifiers, for example, <code>public static
  *       </code>.
  * </ol>
  *
  * @param element the element to check for the method
  * @param args first arg is method name, secondary args are parameter types signatures
  * @return true if the method is found in the element, false otherwise
  */
 private boolean hasMethod(IJavaElement element, Object[] args) {
   try {
     if (args.length > 1) {
       IType type = getType(element);
       if (type != null && type.exists()) {
         String name = (String) args[0];
         String signature = (String) args[1];
         String[] parms = Signature.getParameterTypes(signature);
         String returnType = Signature.getReturnType(signature);
         IMethod candidate = type.getMethod(name, parms);
         if (candidate.exists()) {
           // check return type
           if (candidate.getReturnType().equals(returnType)) {
             // check modifiers
             if (args.length > 2) {
               String modifierText = (String) args[2];
               String[] modifiers = modifierText.split(" "); // $NON-NLS-1$
               int flags = 0;
               for (int j = 0; j < modifiers.length; j++) {
                 String modifier = modifiers[j];
                 Integer flag = (Integer) fgModifiers.get(modifier);
                 if (flag != null) {
                   flags = flags | flag.intValue();
                 }
               }
               if (candidate.getFlags() == flags) {
                 return true;
               }
             }
           }
         }
       }
     }
   } catch (JavaModelException e) {
   }
   return false;
 }
 /*
  * Used from www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html
  */
 @Override
 public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   RefactoringStatus status = new RefactoringStatus();
   try {
     pm.beginTask("Checking preconditions...", 1);
     if (method == null) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Method has not been specified."));
     } else if (varName == null) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Variable has not been specified."));
     } else if (!method.exists()) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Method does not exist."));
     } else {
       if (!method.isBinary() && !method.getCompilationUnit().isStructureKnown()) {
         status.merge(
             RefactoringStatus.createFatalErrorStatus(
                 "Compilation unit contains compile errors."));
       }
     }
   } finally {
     pm.done();
   }
   return status;
 }
Exemplo n.º 14
0
  /**
   * Returns the activity associated with the given layout file.
   *
   * <p>This is an alternative to {@link #guessActivity(IFile, String)}. Whereas guessActivity
   * simply looks for references to "R.layout.foo", this method searches for all usages of
   * Activity#setContentView(int), and for each match it looks up the corresponding call text (such
   * as "setContentView(R.layout.foo)"). From this it uses a regexp to pull out "foo" from this, and
   * stores the association that layout "foo" is associated with the activity class that contained
   * the setContentView call.
   *
   * <p>This has two potential advantages:
   *
   * <ol>
   *   <li>It can be faster. We do the reference search -once-, and we've built a map of all the
   *       layout-to-activity mappings which we can then immediately look up other layouts for,
   *       which is particularly useful at startup when we have to compute the layout activity
   *       associations to populate the theme choosers.
   *   <li>It can be more accurate. Just because an activity references an "R.layout.foo" field
   *       doesn't mean it's setting it as a content view.
   * </ol>
   *
   * However, this second advantage is also its chief problem. There are some common code constructs
   * which means that the associated layout is not explicitly referenced in a direct setContentView
   * call; on a couple of sample projects I tested I found patterns like for example
   * "setContentView(v)" where "v" had been computed earlier. Therefore, for now we're going to
   * stick with the more general approach of just looking up each field when needed. We're keeping
   * the code around, though statically compiled out with the "if (false)" construct below in case
   * we revisit this.
   *
   * @param layoutFile the layout whose activity we want to look up
   * @return the activity name
   */
  @SuppressWarnings("all")
  @Nullable
  public String guessActivityBySetContentView(String layoutName) {
    if (false) {
      // These should be fields
      final Pattern LAYOUT_FIELD_PATTERN =
          Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); // $NON-NLS-1$
      Map<String, String> mUsages = null;

      sync();
      if (mUsages == null) {
        final Map<String, String> usages = new HashMap<String, String>();
        mUsages = usages;
        SearchRequestor requestor =
            new SearchRequestor() {
              @Override
              public void acceptSearchMatch(SearchMatch match) throws CoreException {
                Object element = match.getElement();
                if (element instanceof IMethod) {
                  IMethod method = (IMethod) element;
                  IType declaringType = method.getDeclaringType();
                  String fqcn = declaringType.getFullyQualifiedName();
                  IDocumentProvider provider = new TextFileDocumentProvider();
                  IResource resource = match.getResource();
                  try {
                    provider.connect(resource);
                    IDocument document = provider.getDocument(resource);
                    if (document != null) {
                      String matchText = document.get(match.getOffset(), match.getLength());
                      Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
                      if (matcher.find()) {
                        usages.put(matcher.group(1), fqcn);
                      }
                    }
                  } catch (Exception e) {
                    AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName());
                  } finally {
                    provider.disconnect(resource);
                  }
                }
              }
            };
        try {
          IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
          if (javaProject == null) {
            return null;
          }

          // Search for which java classes call setContentView(R.layout.layoutname);
          String typeFqcn = "R.layout"; // $NON-NLS-1$
          if (mPackage != null) {
            typeFqcn = mPackage + '.' + typeFqcn;
          }

          IType activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY);
          if (activityType != null) {
            IMethod method =
                activityType.getMethod(
                    "setContentView", new String[] {"I"}); // $NON-NLS-1$ //$NON-NLS-2$
            if (method.exists()) {
              SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES);
              search(requestor, javaProject, pattern);
            }
          }
        } catch (CoreException e) {
          AdtPlugin.log(e, null);
        }
      }

      return mUsages.get(layoutName);
    }

    return null;
  }
  public void run(IMarker marker) {
    IFile file = (IFile) javaDeclaration.getResource();
    try {
      ICompilationUnit original = EclipseUtil.getCompilationUnit(file);
      if (original == null) {
        return;
      }
      ICompilationUnit compilationUnit = original.getWorkingCopy(new NullProgressMonitor());

      String lineDelim = JavaPropertyGenerator.getLineDelimiterUsed(compilationUnit);

      Hashtable<String, String> options = JavaCore.getOptions();

      int tabSize = new Integer(options.get("org.eclipse.jdt.core.formatter.tabulation.size"));

      StringBuffer tabBuf = new StringBuffer();

      for (int i = 0; i < tabSize; i++) tabBuf.append(" ");

      String tab = tabBuf.toString();

      IType type = compilationUnit.findPrimaryType();

      IField field = type.getField(property.getName());

      String propertyType = "";
      if (field != null && field.exists()) {
        propertyType = field.getTypeSignature();
      } else {
        propertyType = "String"; // $NON-NLS-1$

        StringBuffer buf = new StringBuffer();

        buf.append(
            tab
                + "private "
                + propertyType
                + " "
                + property.getName()
                + ";"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        buf.append(lineDelim);

        field = type.createField(buf.toString(), null, false, new NullProgressMonitor());
        if (field != null) {
          IBuffer buffer = compilationUnit.getBuffer();

          buffer.replace(
              field.getSourceRange().getOffset(),
              field.getSourceRange().getLength(),
              buf.toString());
          synchronized (compilationUnit) {
            compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, null);
          }
        }
      }

      IMethod oldMethod = GetterSetterUtil.getSetter(field);
      if (oldMethod == null || !oldMethod.exists()) {
        String setterName = GetterSetterUtil.getSetterName(field, null);
        // JavaPropertyGenerator.createSetter(compilationUnit, type, "public",
        // field.getTypeSignature(), setterName, lineDelim);

        String stub = GetterSetterUtil.getSetterStub(field, setterName, true, Flags.AccPublic);
        IMethod newMethod = type.createMethod(stub, null, false, new NullProgressMonitor());
        if (newMethod != null) {
          IBuffer buffer = compilationUnit.getBuffer();
          // format
          StringBuffer buf = new StringBuffer();

          buf.append(lineDelim);
          buf.append(
              tab
                  + "public void "
                  + setterName
                  + "("
                  + propertyType
                  + " "
                  + property.getName()
                  + "){"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          buf.append(lineDelim);
          buf.append(tab + tab + "this." + property.getName() + " = " + property.getName() + ";");
          buf.append(lineDelim);
          buf.append(tab + "}");
          buf.append(lineDelim);

          buffer.replace(
              newMethod.getSourceRange().getOffset(),
              newMethod.getSourceRange().getLength(),
              buf.toString());
        }
      }

      compilationUnit.commitWorkingCopy(false, new NullProgressMonitor());
      compilationUnit.discardWorkingCopy();

    } catch (CoreException ex) {
      SeamGuiPlugin.getPluginLog().logError(ex);
    }
  }
Exemplo n.º 16
0
  /** {@inheritDoc} */
  public Object execute(CommandLine commandLine) throws Exception {
    String project = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    String propertiesOption = commandLine.getValue(Options.PROPERTIES_OPTION);
    String[] properties = {};
    if (propertiesOption != null) {
      properties = StringUtils.split(propertiesOption, ',');
    }
    int offset = getOffset(commandLine);

    // validate supplied fields.
    ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);
    IType type = TypeUtils.getType(src, offset);
    for (int ii = 0; ii < properties.length; ii++) {
      if (!type.getField(properties[ii]).exists()) {
        throw new RuntimeException(
            Services.getMessage("field.not.found", properties[ii], type.getElementName()));
      }
    }

    // check if constructor already exists.
    IMethod method = null;
    if (properties.length == 0) {
      method = type.getMethod(type.getElementName(), null);
    } else {
      String[] fieldSigs = new String[properties.length];
      for (int ii = 0; ii < properties.length; ii++) {
        fieldSigs[ii] = type.getField(properties[ii]).getTypeSignature();
      }
      method = type.getMethod(type.getElementName(), fieldSigs);
    }
    if (method.exists()) {
      throw new RuntimeException(
          Services.getMessage(
              "constructor.already.exists",
              type.getElementName() + " (" + buildParams(type, properties) + ")"));
    }

    // find the sibling to insert before.
    IJavaElement sibling = null;
    IMethod[] methods = type.getMethods();
    for (int ii = 0; ii < methods.length; ii++) {
      if (methods[ii].isConstructor()) {
        sibling = ii < methods.length - 1 ? methods[ii + 1] : null;
      }
    }
    // insert before any other methods or inner classes if any.
    if (sibling == null) {
      if (methods.length > 0) {
        sibling = methods[0];
      } else {
        IType[] types = type.getTypes();
        sibling = types != null && types.length > 0 ? types[0] : null;
      }
    }

    HashMap<String, Object> values = new HashMap<String, Object>();
    values.put("type", type.getElementName());
    boolean hasProperties = properties != null && properties.length > 0;
    values.put("fields", hasProperties ? properties : null);
    values.put("params", hasProperties ? buildParams(type, properties) : StringUtils.EMPTY);

    PluginResources resources = (PluginResources) Services.getPluginResources(PluginResources.NAME);
    String constructor = TemplateUtils.evaluate(resources, TEMPLATE, values);
    Position position =
        TypeUtils.getPosition(type, type.createMethod(constructor, sibling, false, null));
    JavaUtils.format(
        src, CodeFormatter.K_COMPILATION_UNIT, position.getOffset(), position.getLength());

    return null;
  }