/** * Determines is the java element contains a type with a specific annotation. * * <p>The syntax for the property tester is of the form: qualified or unqualified annotation name * <li>qualified or unqualified annotation name, required. For example, <code>org.junit.JUnit * </code>. * </ol> * * @param element the element to check for the method * @param annotationName the qualified or unqualified name of the annotation to look for * @return true if the type is found in the element, false otherwise */ private boolean hasTypeWithAnnotation(IJavaElement element, String annotationType) { try { IType type = getType(element); if (type == null || !type.exists()) { return false; } IBuffer buffer = null; IOpenable openable = type.getOpenable(); if (openable instanceof ICompilationUnit) { buffer = ((ICompilationUnit) openable).getBuffer(); } else if (openable instanceof IClassFile) { buffer = ((IClassFile) openable).getBuffer(); } if (buffer == null) { return false; } ISourceRange sourceRange = type.getSourceRange(); ISourceRange nameRange = type.getNameRange(); if (sourceRange != null && nameRange != null) { IScanner scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(buffer.getCharacters()); scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); if (findAnnotation(scanner, annotationType)) { return true; } } } catch (JavaModelException e) { } catch (InvalidInputException e) { } return false; }
private void failHelper1( int startLine, int startColumn, int endLine, int endColumn, boolean makeFinal, String className, int visibility, int expectedSeverity) throws Exception { ICompilationUnit cu = createCUfromTestFile(getPackageP(), false, 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.setVisibility(visibility); if (preconditionResult == null) preconditionResult = ref.checkFinalConditions(new NullProgressMonitor()); else preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor())); if (preconditionResult.isOK()) preconditionResult = null; assertNotNull("precondition was supposed to fail", preconditionResult); assertEquals("incorrect severity:", expectedSeverity, preconditionResult.getSeverity()); }
private void addDeclarationUpdate() throws CoreException { ISourceRange nameRange = fField.getNameRange(); TextEdit textEdit = new ReplaceEdit(nameRange.getOffset(), nameRange.getLength(), getNewElementName()); ICompilationUnit cu = fField.getCompilationUnit(); String groupName = RefactoringCoreMessages.RenameFieldRefactoring_Update_field_declaration; addTextEdit(fChangeManager.get(cu), groupName, textEdit); }
/** * Default strategy for when no source position can be computed: creates a {@link Position} for * the name of the given {@link IType}. Returns <code>null</code> in the event the given {@link * IType} is <code>null</code> or the name range cannot be computed for the type. * * @param type the type * @param reference the reference * @throws CoreException * @return returns a default {@link Position} for the name range of the given {@link IType} */ protected Position defaultSourcePosition(IType type, IReference reference) throws CoreException { if (type != null) { ISourceRange range = type.getNameRange(); if (range != null) { return new Position(range.getOffset(), range.getLength()); } } return null; }
public ASTNode search() throws JavaModelException { ISourceRange range = null; if (this.element instanceof IMember && !(this.element instanceof IInitializer)) range = ((IMember) this.element).getNameRange(); else range = this.element.getSourceRange(); this.rangeStart = range.getOffset(); this.rangeLength = range.getLength(); this.ast.accept(this); return this.foundNode; }
public void run(IStructuredSelection selection) { IMember member = getMember(selection); if (!ActionUtil.isProcessable(getShell(), member)) return; FindOccurrencesEngine engine = FindOccurrencesEngine.create(new OccurrencesFinder()); try { ISourceRange range = member.getNameRange(); String result = engine.run(member.getTypeRoot(), range.getOffset(), range.getLength()); if (result != null) showMessage(getShell(), fActionBars, result); } catch (JavaModelException e) { JavaPlugin.log(e); } }
private void failActivationHelper( int startLine, int startColumn, int endLine, int endColumn, int expectedSeverity) throws Exception { ICompilationUnit cu = createCUfromTestFile(getPackageP(), false, 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()); assertEquals( "activation was supposed to fail", expectedSeverity, preconditionResult.getSeverity()); }
CalleeAnalyzerVisitor( IMember member, CompilationUnit compilationUnit, IProgressMonitor progressMonitor) { fSearchResults = new CallSearchResultCollector(); this.fMember = member; this.fCompilationUnit = compilationUnit; this.fProgressMonitor = progressMonitor; try { ISourceRange sourceRange = member.getSourceRange(); this.fMethodStartPosition = sourceRange.getOffset(); this.fMethodEndPosition = fMethodStartPosition + sourceRange.getLength(); } catch (JavaModelException jme) { JavaPlugin.log(jme); } }
/** * Returns the source range to use for the given field within the given {@link IType} * * @param type the type to look in for the given {@link IApiField} * @param reference the reference the field is involved in * @param field the field to find the range for * @return the {@link ISourceRange} in the given {@link IType} that encloses the given {@link * IApiField} * @throws JavaModelException * @throws CoreException */ protected Position getSourceRangeForField(IType type, IReference reference, IApiField field) throws JavaModelException, CoreException { IField javaField = type.getField(field.getName()); Position pos = null; if (javaField.exists()) { ISourceRange range = javaField.getNameRange(); if (range != null) { pos = new Position(range.getOffset(), range.getLength()); } } if (pos == null) { return defaultSourcePosition(type, reference); } return pos; }
/** * Returns the source range for the given {@link IApiMethod} within the given {@link IType} * * @param type the type to look for the method within * @param reference the reference the method comes from * @param method the {@link IApiMethod} to look for the source range for * @return the {@link ISourceRange} in the {@link IType} enclosing the given {@link IApiMethod} * @throws CoreException * @throws JavaModelException */ protected Position getSourceRangeForMethod(IType type, IReference reference, IApiMethod method) throws CoreException, JavaModelException { IMethod match = findMethodInType(type, method); Position pos = null; if (match != null) { ISourceRange range = match.getNameRange(); if (range != null) { pos = new Position(range.getOffset(), range.getLength()); } } if (pos == null) { return defaultSourcePosition(type, reference); } return pos; }
@Override public void run(IStructuredSelection selection) { try { IMember member = getMember(selection); if (member == null || !ActionUtil.isEditable(getShell(), member)) return; ISourceRange range = member.getNameRange(); RefactoringExecutionStarter.startChangeTypeRefactoring( member.getCompilationUnit(), getShell(), range.getOffset(), range.getLength()); } catch (CoreException e) { ExceptionHandler.handle( e, RefactoringMessages.ChangeTypeAction_dialog_title, RefactoringMessages.ChangeTypeAction_exception); } }
/** * Method getPosition. Get position for workspace java source files * * @param aSelectedElement ISourceReference * @param aFile IFile * @return TextPosition * @throws CoreException */ public static R4EUITextPosition getPosition(ISourceReference aSelectedElement, IFile aFile) throws CoreException { int offset = 0; int length = 0; String name = ""; if (null != aSelectedElement) { final ISourceRange sourceRange = aSelectedElement.getSourceRange(); if (null != sourceRange) { offset = sourceRange.getOffset(); length = sourceRange.getLength(); } name = ((IJavaElement) aSelectedElement).getElementName(); } final R4EUITextPosition position = new R4EUITextPosition(offset, length, aFile); position.setName(name); return position; }
/** * Formats the specified compilation unit. * * @param unit the compilation unit to format * @param monitor the monitor for the operation * @throws JavaModelException */ public static void formatUnitSourceCode(ICompilationUnit unit, IProgressMonitor monitor) throws JavaModelException { CodeFormatter formatter = ToolFactory.createCodeFormatter(null); ISourceRange range = unit.getSourceRange(); TextEdit formatEdit = formatter.format( CodeFormatter.K_COMPILATION_UNIT, unit.getSource(), range.getOffset(), range.getLength(), 0, null); if (formatEdit != null && formatEdit.hasChildren()) { unit.applyTextEdit(formatEdit, monitor); } else { monitor.done(); } }
/** @see ISourceReference */ public String getSource() throws JavaModelException { IOpenable openable = this.parent.getOpenableParent(); IBuffer buffer = openable.getBuffer(); if (buffer == null) { return null; } ISourceRange range = getSourceRange(); int offset = range.getOffset(); int length = range.getLength(); if (offset == -1 || length == 0) { return null; } try { return buffer.getText(offset, length); } catch (RuntimeException e) { return null; } }
@Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus result = new RefactoringStatus(); result.merge(Checks.checkAvailability(targetClass)); if (result.hasFatalError()) return result; fRoot = new RefactoringASTParser(AST.JLS3).parse(targetClass.getCompilationUnit(), true, pm); ISourceRange sourceRange = targetClass.getNameRange(); ASTNode node = NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength()); if (node == null) { return mappingErrorFound(result, node); } else { targetClassDeclaration = ASTNodeSearchUtil.getTypeDeclarationNode(targetClass, fRoot); } fRewriter = ASTRewrite.create(fRoot.getAST()); return result; }
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()); }
/* * (non-Javadoc) * @see org.eclipse.pde.api.tools.internal.builder.AbstractProblemDetector# * getSourceRange(org.eclipse.jdt.core.IType, * org.eclipse.jface.text.IDocument, * org.eclipse.pde.api.tools.internal.provisional.builder.IReference) */ @Override protected Position getSourceRange(IType type, IDocument document, IReference reference) throws CoreException, BadLocationException { switch (reference.getReferenceType()) { case IReference.T_TYPE_REFERENCE: { int linenumber = reference.getLineNumber(); if (linenumber > 0) { // line number starts at 0 for the linenumber--; } if (linenumber > 0) { int offset = document.getLineOffset(linenumber); String line = document.get(offset, document.getLineLength(linenumber)); String qname = reference.getReferencedTypeName().replace('$', '.'); int first = line.indexOf(qname); if (first < 0) { qname = Signatures.getSimpleTypeName(reference.getReferencedTypeName()); qname = qname.replace('$', '.'); first = line.indexOf(qname); } Position pos = null; if (first > -1) { pos = new Position(offset + first, qname.length()); } else { // optimistically select the whole line since we can't // find the correct variable name and we can't just // select // the first occurrence pos = new Position(offset, line.length()); } return pos; } else { IApiMember apiMember = reference.getMember(); switch (apiMember.getType()) { case IApiElement.FIELD: { IApiField field = (IApiField) reference.getMember(); return getSourceRangeForField(type, reference, field); } case IApiElement.METHOD: { // reference in a method declaration IApiMethod method = (IApiMethod) reference.getMember(); return getSourceRangeForMethod(type, reference, method); } default: break; } // reference in a type declaration ISourceRange range = type.getNameRange(); Position pos = null; if (range != null) { pos = new Position(range.getOffset(), range.getLength()); } if (pos == null) { return defaultSourcePosition(type, reference); } return pos; } } case IReference.T_FIELD_REFERENCE: { int linenumber = reference.getLineNumber(); if (linenumber > 0) { return getFieldNameRange( reference.getReferencedTypeName(), reference.getReferencedMemberName(), document, reference); } // reference in a field declaration IApiField field = (IApiField) reference.getMember(); return getSourceRangeForField(type, reference, field); } case IReference.T_METHOD_REFERENCE: { if (reference.getLineNumber() >= 0) { String referenceMemberName = reference.getReferencedMemberName(); String methodName = null; boolean isConstructor = Util.isConstructor(referenceMemberName); if (isConstructor) { methodName = Signatures.getSimpleTypeName(reference.getReferencedTypeName().replace('$', '.')); } else { methodName = referenceMemberName; } Position pos = getMethodNameRange(isConstructor, methodName, document, reference); if (pos == null) { return defaultSourcePosition(type, reference); } return pos; } // reference in a method declaration IApiMethod method = (IApiMethod) reference.getMember(); return getSourceRangeForMethod(type, reference, method); } default: return null; } }
/** * Determines is the java element contains a method with a specific annotation. * * <p>The syntax for the property tester is of the form: qualified or unqualified annotation name, * modifiers * <li>qualified or unqualified annotation name, required. For example, <code>org.junit.JUnit * </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 annotationName the qualified or unqualified name of the annotation to look for * @return true if the method is found in the element, false otherwise */ private boolean hasMethodWithAnnotation(IJavaElement element, Object[] args) { try { String annotationType = (String) args[0]; int flags = 0; if (args.length > 1) { String[] modifiers = ((String) args[1]).split(" "); // $NON-NLS-1$ 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(); } } } else { flags = -1; } IType type = getType(element); if (type == null || !type.exists()) { return false; } IMethod[] methods = type.getMethods(); if (methods.length == 0) { return false; } IBuffer buffer = null; IOpenable openable = type.getOpenable(); if (openable instanceof ICompilationUnit) { buffer = ((ICompilationUnit) openable).getBuffer(); } else if (openable instanceof IClassFile) { buffer = ((IClassFile) openable).getBuffer(); } if (buffer == null) { return false; } IScanner scanner = null; // delay initialization for (int i = 0; i < methods.length; i++) { IMethod curr = methods[i]; if (curr.isConstructor() || (flags != -1 && flags != (curr.getFlags() & FLAGS_MASK))) { continue; } ISourceRange sourceRange = curr.getSourceRange(); ISourceRange nameRange = curr.getNameRange(); if (sourceRange != null && nameRange != null) { if (scanner == null) { scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(buffer.getCharacters()); } scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); if (findAnnotation(scanner, annotationType)) { return true; } } } } catch (JavaModelException e) { } catch (InvalidInputException e) { } return false; }
private void doListSelectionChanged(int page, ISourceRange[] ranges) { if (fEditor != null && ranges != null && page >= 0 && page < ranges.length) { ISourceRange range = ranges[page]; fEditor.selectAndReveal(range.getOffset(), range.getLength()); } }
public IDocInfo getBasicDocInfo() { try { IMethod iMethod = (IMethod) tm; ISourceRange javadocRange = iMethod.getJavadocRange(); if (javadocRange != null) { String attachedJavadoc = iMethod .getCompilationUnit() .getSource() .substring( javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength()); attachedJavadoc = attachedJavadoc.substring(3, attachedJavadoc.length() - 2); StringReader rr = new StringReader(attachedJavadoc); BufferedReader mm = new BufferedReader(rr); final StringBuilder bld = new StringBuilder(); final HashMap<String, String> mmq = new HashMap<String, String>(); while (true) { try { String s = mm.readLine(); if (s == null) { break; } int indexOf = s.indexOf('*'); if (indexOf != -1) { s = s.substring(indexOf + 1); } s = s.trim(); if (s.startsWith("@")) { // $NON-NLS-1$ if (s.startsWith(PARAM)) { s = s.substring(PARAM.length()); s = s.trim(); int p = s.indexOf(' '); if (p != -1) { String pName = s.substring(0, p).trim(); String pVal = s.substring(p).trim(); mmq.put(pName, pVal); } } if (s.startsWith(RETURN)) { s = s.substring(RETURN.length()); s = s.trim(); mmq.put(RETURN, s); } continue; } bld.append(s); bld.append('\n'); } catch (IOException e) { break; } } return new IDocInfo() { public String getDocumentation(String pName) { return mmq.get(pName); } public String getDocumentation() { return bld.toString().trim(); } public String getReturnInfo() { return mmq.get(RETURN); } }; } return new IDocInfo() { public String getReturnInfo() { return ""; //$NON-NLS-1$ } public String getDocumentation(String pName) { return ""; //$NON-NLS-1$ } public String getDocumentation() { return ""; //$NON-NLS-1$ } }; } catch (JavaModelException e) { throw new IllegalStateException(); } }
/** * Invokes the introduce indirection ref. Some pointers: * * @param topLevelName This is an array of fully qualified top level(!) type names with exactly * one package prefix (e.g. "p.Foo"). Simple names must correspond to .java files. The first * cu will be used for the invocation of the refactoring (see positioning) * @param newName name of indirection method * @param qTypeName qualified type name of the type for the indirection method. Should be one of * the cus in topLevelName. * @param startLine starting line of selection in topLevelName[0] * @param startColumn starting column of selection in topLevelName[0] * @param endLine ending line of selection in topLevelName[0] * @param endColumn ending column of selection in topLevelName[0] * @param updateReferences true if references should be updated * @param shouldWarn if true, warnings will be expected in the result * @param shouldError if true, errors will be expected in the result * @param shouldFail if true, fatal errors will be expected in the result * @throws Exception * @throws JavaModelException * @throws CoreException * @throws IOException */ private void helper( String[] topLevelName, String newName, String qTypeName, int startLine, int startColumn, int endLine, int endColumn, boolean updateReferences, boolean shouldWarn, boolean shouldError, boolean shouldFail) throws Exception, JavaModelException, CoreException, IOException { ICompilationUnit[] cu = new ICompilationUnit[topLevelName.length]; for (int i = 0; i < topLevelName.length; i++) { String packName = topLevelName[i].substring(0, topLevelName[i].indexOf('.')); String className = topLevelName[i].substring(topLevelName[i].indexOf('.') + 1); IPackageFragment cPackage = getRoot().createPackageFragment(packName, true, null); cu[i] = createCUfromTestFile(cPackage, className); } ISourceRange selection = TextRangeUtil.getSelection(cu[0], startLine, startColumn, endLine, endColumn); try { IntroduceIndirectionRefactoring ref = new IntroduceIndirectionRefactoring(cu[0], selection.getOffset(), selection.getLength()); ref.setEnableUpdateReferences(updateReferences); if (qTypeName != null) ref.setIntermediaryClassName(qTypeName); if (newName != null) ref.setIntermediaryMethodName(newName); boolean failed = false; RefactoringStatus status = performRefactoringWithStatus(ref); if (status.hasFatalError()) { assertTrue( "Failed but shouldn't: " + status.getMessageMatchingSeverity(RefactoringStatus.FATAL), shouldFail); failed = true; } else assertFalse("Didn't fail although expected", shouldFail); if (!failed) { if (status.hasError()) assertTrue( "Had errors but shouldn't: " + status.getMessageMatchingSeverity(RefactoringStatus.ERROR), shouldError); else assertFalse("No error although expected", shouldError); if (status.hasWarning()) assertTrue( "Had warnings but shouldn't: " + status.getMessageMatchingSeverity(RefactoringStatus.WARNING), shouldWarn); else assertFalse("No warning although expected", shouldWarn); for (int i = 0; i < topLevelName.length; i++) { String className = topLevelName[i].substring(topLevelName[i].indexOf('.') + 1); assertEqualLines( "invalid output.", getFileContents(getOutputTestFileName(className)), cu[i].getSource()); } } } finally { for (int i = 0; i < topLevelName.length; i++) JavaProjectHelper.delete(cu[i]); } }