@Override public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = MarkerFactory.getSelection(); if (selection instanceof ITreeSelection) { ITreeSelection treeSelection = (ITreeSelection) selection; if (treeSelection.getFirstElement() instanceof IOpenable || treeSelection.getFirstElement() instanceof IFile) { IResource resource = ((IAdaptable) treeSelection.getFirstElement()).getAdapter(IResource.class); List<IMarker> markers = MarkerFactory.findMarkers(resource); MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(), "Marker Count", null, markers.size() + " marker(s)", MessageDialog.INFORMATION, new String[] {"OK"}, 0); dialog.open(); } } return null; }
/** * Creates a range for the given offset and length for an {@link IOpenable} * * @param openable * @param offset * @param length * @return * @throws JavaModelException */ public static Range toRange(IOpenable openable, int offset, int length) throws JavaModelException{ Range range = newRange(); if (offset > 0 || length > 0) { int[] loc = null; int[] endLoc = null; IBuffer buffer = openable.getBuffer(); if (buffer != null) { loc = JsonRpcHelpers.toLine(buffer, offset); endLoc = JsonRpcHelpers.toLine(buffer, offset + length); } if (loc == null) { loc = new int[2]; } if (endLoc == null) { endLoc = new int[2]; } setPosition(range.getStart(), loc); setPosition(range.getEnd(), endLoc); } return range; }
/** * Returns the reason for why the Javadoc of the Java element could not be retrieved. * * @param element whose Javadoc could not be retrieved * @param root the root of the Java element * @return the String message for why the Javadoc could not be retrieved for the Java element or * <code>null</code> if the Java element is from a source container * @since 3.9 */ public static String getExplanationForMissingJavadoc( IJavaElement element, IPackageFragmentRoot root) { String message = null; try { boolean isBinary = (root.exists() && root.getKind() == IPackageFragmentRoot.K_BINARY); if (isBinary) { boolean hasAttachedJavadoc = JavaDocLocations.getJavadocBaseLocation(element) != null; boolean hasAttachedSource = root.getSourceAttachmentPath() != null; IOpenable openable = element.getOpenable(); boolean hasSource = openable.getBuffer() != null; // Provide hint why there's no Java doc if (!hasAttachedSource && !hasAttachedJavadoc) message = CorextMessages.JavaDocLocations_noAttachments; else if (!hasAttachedJavadoc && !hasSource) message = CorextMessages.JavaDocLocations_noAttachedJavadoc; else if (!hasAttachedSource) message = CorextMessages.JavaDocLocations_noAttachedSource; else if (!hasSource) message = CorextMessages.JavaDocLocations_noInformation; } } catch (JavaModelException e) { message = CorextMessages.JavaDocLocations_error_gettingJavadoc; LOG.error(message, e); } return message; }
static RefactoringStatusContext createRefactoringStatusContext(IJavaElement element) { if (element instanceof IMember) { return JavaStatusContext.create((IMember) element); } if (element instanceof ISourceReference) { IOpenable openable= element.getOpenable(); try { if (openable instanceof ICompilationUnit) { return JavaStatusContext.create((ICompilationUnit) openable, ((ISourceReference) element).getSourceRange()); } else if (openable instanceof IClassFile) { return JavaStatusContext.create((IClassFile) openable, ((ISourceReference) element).getSourceRange()); } } catch (JavaModelException e) { // ignore } } return null; }
private void addJavaElement(List<Object> selectedElements, IJavaElement je) { if (je.getElementType() == IJavaElement.COMPILATION_UNIT) selectedElements.add(je); else if (je.getElementType() == IJavaElement.CLASS_FILE) selectedElements.add(je); else if (je.getElementType() == IJavaElement.JAVA_PROJECT) selectedElements.add(je); else if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { if (!isInArchiveOrExternal(je)) selectedElements.add(je); } else if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT) { if (!isInArchiveOrExternal(je)) selectedElements.add(je); } else { IOpenable openable= je.getOpenable(); if (openable instanceof ICompilationUnit) selectedElements.add(((ICompilationUnit) openable).getPrimary()); else if (openable instanceof IClassFile && !isInArchiveOrExternal(je)) selectedElements.add(openable); } }
/** * @see MultiOperation This method delegate to <code>deleteResource</code> or * <code>deletePackageFragment</code> depending on the type of <code>element</code>. */ protected void processElement(IJavaElement element) throws JavaModelException { switch (element.getElementType()) { case IJavaElement.CLASS_FILE : case IJavaElement.COMPILATION_UNIT : deleteResource(element.getResource(), this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY); break; case IJavaElement.PACKAGE_FRAGMENT : deletePackageFragment((IPackageFragment) element); break; default : throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element)); } // ensure the element is closed if (element instanceof IOpenable) { ((IOpenable)element).close(); } }
public TextEdit createLambdaConversionTextEdit(CompilationUnit astRoot, IProgressMonitor monitor) throws JavaModelException, CoreException { AST ast = astRoot.getAST(); List<?> types = astRoot.types(); SubMonitor subMonitor = SubMonitor.convert(monitor, types.size()); ASTRewrite rewriter = ASTRewrite.create(ast); ImportRewrite importRewrite = ImportRewrite.create(astRoot, true); boolean modifiedDocument = false; for (ClassInstanceCreation classInstanceCreation : classInstanceCreations) { boolean converted = prepareConversionToLambda(astRoot, ast, rewriter, importRewrite, classInstanceCreation); modifiedDocument = modifiedDocument || converted; } if (modifiedDocument) { ICompilationUnit adapter = (ICompilationUnit) astRoot.getJavaElement().getAdapter(IOpenable.class); if (adapter != null) { return createTextEdit(adapter, subMonitor.newChild(1), rewriter, importRewrite); } } return null; }
private void handleImportRemoval(CompilationUnit cu, ASTRewrite rewriter, ImportRewrite importRewrite, ITypeBinding superclass) throws CoreException, JavaModelException, BadLocationException { ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement().getAdapter(IOpenable.class); TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor()); TextEdit edits = rewriter.rewriteAST(); importEdits.addChild(edits); // apply the text edits to the compilation unit String source = icu.getSource(); Document document = new Document(source); importEdits.apply(document); String oldContents = icu.getBuffer().getContents(); icu.getBuffer().setContents(document.get()); ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setResolveBindings(true); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setBindingsRecovery(true); parser.setSource(icu); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); if (!ImportRelevanceFinder.isStillNeeded(astRoot, superclass.getQualifiedName())) { importRewrite.removeImport(superclass.getQualifiedName()); } icu.getBuffer().setContents(oldContents); }
@Override public void modifyCompilationUnit(CompilationUnit astRoot, IProgressMonitor monitor) throws JavaModelException, CoreException, BadLocationException { AST ast = astRoot.getAST(); List<?> types = astRoot.types(); SubMonitor subMonitor = SubMonitor.convert(monitor, types.size()); ASTRewrite rewriter = ASTRewrite.create(ast); ImportRewrite importRewrite = ImportRewrite.create(astRoot, true); modifiedDocument = false; for (Object object : types) { if (object instanceof TypeDeclaration) { TypeDeclaration typeDeclaration = (TypeDeclaration) object; removeTestCaseSuperclass(rewriter, importRewrite, typeDeclaration); convertTestMethods(ast, rewriter, importRewrite, typeDeclaration); } } if (modifiedDocument) { ICompilationUnit adapter = (ICompilationUnit) astRoot.getJavaElement().getAdapter(IOpenable.class); if (adapter != null) { saveChanges(adapter, subMonitor.newChild(1), rewriter, importRewrite); } } }
public static Range toRange(IOpenable openable, int offset, int length) throws JavaModelException { if (offset > 0 || length > 0) { int[] loc = null; int[] endLoc = null; IBuffer buffer = openable.getBuffer(); // if (buffer != null) { // loc = JsonRpcHelpers.toLine(buffer, offset); // endLoc = JsonRpcHelpers.toLine(buffer, offset + length); // } // if (loc == null) { // loc = new int[2]; // } // if (endLoc == null) { // endLoc = new int[2]; // } // setPosition(range.getStart(), loc); // setPosition(range.getEnd(), endLoc); IDocument document = toDocument(buffer); try { int line = document.getLineOfOffset(offset); int column = offset - document.getLineOffset(line); return new Range(line + 1, column + 1); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // TODO Auto-generated method stub return null; }
public static void updatePathGenerator (IFile ifile, String oldPathGenerator,String newPathGenerator) throws CoreException { ICompilationUnit cu = JavaCore.createCompilationUnitFrom(ifile); ICompilationUnit workingCopy = cu.getWorkingCopy(new NullProgressMonitor()); IBuffer buffer = ((IOpenable)workingCopy).getBuffer(); String source = buffer.getContents(); int start = source.indexOf(oldPathGenerator); buffer.replace(start, oldPathGenerator.length(), newPathGenerator); workingCopy.reconcile(ICompilationUnit.NO_AST, false, workingCopy.getOwner(), new NullProgressMonitor()); workingCopy.commitWorkingCopy(true, null); workingCopy.discardWorkingCopy(); ifile.touch(new NullProgressMonitor ()); }
public DocumentAdapter(IOpenable owner, IFile file) { fOwner = owner; fFile = file; fBufferListeners = new ArrayList<>(3); fIsClosed = false; ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); try { manager.connect(file.getFullPath(), LocationKind.IFILE, null); fTextFileBuffer= manager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE); } catch (CoreException e) { } }
private static IResource getResource(IJavaElement element) { if (element.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit) element).getResource(); } else if (element instanceof IOpenable) { return element.getResource(); } else { return null; } }
private String shortDescription(String javadoc) throws Exception { IMember member = mock(IMember.class); IOpenable openable = (IOpenable)mock(JavaElement.class, withSettings().extraInterfaces(IOpenable.class)); when(member.getOpenable()).thenReturn(openable); IBuffer buffer = BufferManager.createBuffer(openable); buffer.setContents(javadoc); when(openable.getBuffer()).thenReturn(buffer); when(member.getJavadocRange()).thenReturn(new SourceRange(0, javadoc.length())); return javadocCommentProvider.getJavadocCommentShortDescription(member); }
/** * @param elem a Java element (doesn't have to exist) * @return the existing or default line delimiter for the element */ public static String getLineDelimiterUsed(IJavaElement elem) { IOpenable openable = elem.getOpenable(); if (openable instanceof ITypeRoot) { try { return openable.findRecommendedLineSeparator(); } catch (JavaModelException exception) { // Use project setting } } IJavaProject project = elem.getJavaProject(); return getProjectLineDelimiter(project.exists() ? project : null); }
/** * Evaluates the indentation used by a Java element. (in tabulators) * * @param elem the element to get the indent of * @return return the indent unit * @throws JavaModelException thrown if the element could not be accessed */ public static int getIndentUsed(IJavaElement elem) throws JavaModelException { IOpenable openable = elem.getOpenable(); if (openable instanceof ITypeRoot) { IBuffer buf = openable.getBuffer(); if (buf != null) { int offset = ((ISourceReference) elem).getSourceRange().getOffset(); return getIndentUsed(buf, offset, elem.getJavaProject()); } } return 0; }
/** * Constructs a new document adapter. * * @param owner the owner of this buffer * @param path the path of the file that backs the buffer * @since 3.2 */ public DocumentAdapter(IOpenable owner, IPath path) { Assert.isLegal(path != null); fOwner = owner; fPath = path; // fLocationKind = LocationKind.NORMALIZE; initialize(); }
/** * Constructs a new document adapter. * * @param owner the owner of this buffer * @param file the <code>IFile</code> that backs the buffer */ public DocumentAdapter(IOpenable owner, IFile file) { fOwner = owner; fFile = file; fPath = fFile.getFullPath(); // fLocationKind = LocationKind.IFILE; initialize(); }
/** * Constructs a new document adapter. * * @param owner the owner of this buffer * @param file the <code>IFile</code> that backs the buffer */ public DocumentAdapter(IOpenable owner, IPath path, String content) { fOwner = owner; // fFile = file; fPath = path; // fLocationKind = LocationKind.IFILE; fDocument = new Document(content); initialize(); }
private static IResource getResource(IJavaElement element){ if (element.getElementType() == IJavaElement.COMPILATION_UNIT) return ((ICompilationUnit) element).getResource(); else if (element instanceof IOpenable) return element.getResource(); else return null; }
/** * Returns the IBuffer for the IMember represented by this CallLocation. * * @return IBuffer for the IMember or null if the member doesn't have a buffer (for * example if it is a binary file without source attachment). */ private IBuffer getBufferForMember() { IBuffer buffer = null; try { IOpenable openable = fMember.getOpenable(); if (openable != null && fMember.exists()) { buffer = openable.getBuffer(); } } catch (JavaModelException e) { JavaPlugin.log(e); } return buffer; }
/** * Returns the reason for why the Javadoc of the Java element could not be retrieved. * * @param element whose Javadoc could not be retrieved * @param root the root of the Java element * @return the String message for why the Javadoc could not be retrieved for the Java element or * <code>null</code> if the Java element is from a source container * @since 3.9 */ public static String getExplanationForMissingJavadoc(IJavaElement element, IPackageFragmentRoot root) { String message= null; try { boolean isBinary= (root.exists() && root.getKind() == IPackageFragmentRoot.K_BINARY); if (isBinary) { boolean hasAttachedJavadoc= JavaDocLocations.getJavadocBaseLocation(element) != null; boolean hasAttachedSource= root.getSourceAttachmentPath() != null; IOpenable openable= element.getOpenable(); boolean hasSource= openable.getBuffer() != null; // Provide hint why there's no Java doc if (!hasAttachedSource && !hasAttachedJavadoc) message= CorextMessages.JavaDocLocations_noAttachments; else if (!hasAttachedJavadoc && !hasSource) message= CorextMessages.JavaDocLocations_noAttachedJavadoc; else if (!hasAttachedSource) message= CorextMessages.JavaDocLocations_noAttachedSource; else if (!hasSource) message= CorextMessages.JavaDocLocations_noInformation; } } catch (JavaModelException e) { message= CorextMessages.JavaDocLocations_error_gettingJavadoc; JavaPlugin.log(e); } return message; }
/** * @param elem a Java element (doesn't have to exist) * @return the existing or default line delimiter for the element */ public static String getLineDelimiterUsed(IJavaElement elem) { IOpenable openable= elem.getOpenable(); if (openable instanceof ITypeRoot) { try { return openable.findRecommendedLineSeparator(); } catch (JavaModelException exception) { // Use project setting } } IJavaProject project= elem.getJavaProject(); return getProjectLineDelimiter(project.exists() ? project : null); }
/** * Evaluates the indentation used by a Java element. (in tabulators) * * @param elem the element to get the indent of * @return return the indent unit * @throws JavaModelException thrown if the element could not be accessed */ public static int getIndentUsed(IJavaElement elem) throws JavaModelException { IOpenable openable= elem.getOpenable(); if (openable instanceof ITypeRoot) { IBuffer buf= openable.getBuffer(); if (buf != null) { int offset= ((ISourceReference)elem).getSourceRange().getOffset(); return getIndentUsed(buf, offset, elem.getJavaProject()); } } return 0; }
void handleDoubleClick(DoubleClickEvent event) { TreeViewer viewer= fPart.getTreeViewer(); IStructuredSelection selection= (IStructuredSelection)event.getSelection(); Object element= selection.getFirstElement(); if (viewer.isExpandable(element)) { if (doubleClickGoesInto()) { // don't zoom into compilation units and class files if (element instanceof ICompilationUnit || element instanceof IClassFile) return; if (element instanceof IOpenable || element instanceof IContainer || element instanceof IWorkingSet) { fZoomInAction.run(); } } else { IAction openAction= fNavigateActionGroup.getOpenAction(); if (openAction != null && openAction.isEnabled() && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK) return; if (selection instanceof ITreeSelection) { TreePath[] paths= ((ITreeSelection)selection).getPathsFor(element); for (int i= 0; i < paths.length; i++) { viewer.setExpandedState(paths[i], !viewer.getExpandedState(paths[i])); } } else { viewer.setExpandedState(element, !viewer.getExpandedState(element)); } } } else if (element instanceof IProject && !((IProject) element).isOpen()) { OpenProjectAction openProjectAction= fProjectActionGroup.getOpenProjectAction(); if (openProjectAction.isEnabled()) { openProjectAction.run(); } } }
public IBuffer createBuffer(IOpenable owner) { if (owner instanceof ICompilationUnit) { ICompilationUnit unit= (ICompilationUnit) owner; ICompilationUnit original= unit.getPrimary(); IResource resource= original.getResource(); if (resource instanceof IFile) { return new DocumentAdapter(unit, (IFile) resource); } } return DocumentAdapter.NULL; }
/** * Constructs a new document adapter. * * @param owner the owner of this buffer * @param path the path of the file that backs the buffer * @since 3.2 */ public DocumentAdapter(IOpenable owner, IPath path) { Assert.isLegal(path != null); fOwner= owner; fPath= path; fLocationKind= LocationKind.NORMALIZE; initialize(); }
/** * Constructs a new document adapter. * * @param owner the owner of this buffer * @param fileStore the file store of the file that backs the buffer * @param path the path of the file that backs the buffer * @since 3.6 */ public DocumentAdapter(IOpenable owner, IFileStore fileStore, IPath path) { Assert.isLegal(fileStore != null); Assert.isLegal(path != null); fOwner= owner; fFileStore= fileStore; fPath= path; fLocationKind= LocationKind.NORMALIZE; initialize(); }
/** * Constructs a new document adapter. * * @param owner the owner of this buffer * @param file the <code>IFile</code> that backs the buffer */ public DocumentAdapter(IOpenable owner, IFile file) { fOwner= owner; fFile= file; fPath= fFile.getFullPath(); fLocationKind= LocationKind.IFILE; initialize(); }
private Object findMethodWithAttachedDocInHierarchy(final MethodBinding method) throws JavaModelException { ReferenceBinding type= method.declaringClass; final SelectionRequestor requestor1 = (SelectionRequestor) this.requestor; return new InheritDocVisitor() { public Object visit(ReferenceBinding currType) throws JavaModelException { MethodBinding overridden = findOverriddenMethodInType(currType, method); if (overridden == null) return InheritDocVisitor.CONTINUE; TypeBinding args[] = overridden.parameters; String names[] = new String[args.length]; for (int i = 0; i < args.length; i++) { names[i] = Signature.createTypeSignature(args[i].sourceName(), false); } IMember member = (IMember) requestor1.findMethodFromBinding(overridden, names, overridden.declaringClass); if (member == null) return InheritDocVisitor.CONTINUE; if (member.getAttachedJavadoc(null) != null ) { // for binary methods with attached javadoc and no source attached return overridden; } IOpenable openable = member.getOpenable(); if (openable == null) return InheritDocVisitor.CONTINUE; IBuffer buf= openable.getBuffer(); if (buf == null) { // no source attachment found. This method maybe the one. Stop. return InheritDocVisitor.STOP_BRANCH; } ISourceRange javadocRange= member.getJavadocRange(); if (javadocRange == null) return InheritDocVisitor.CONTINUE; // this method doesn't have javadoc, continue to look. String rawJavadoc= buf.getText(javadocRange.getOffset(), javadocRange.getLength()); if (rawJavadoc != null) { return overridden; } return InheritDocVisitor.CONTINUE; } }.visitInheritDoc(type); }
public static IBuffer createBuffer(IOpenable owner) { JavaElement element = (JavaElement) owner; IResource resource = element.resource(); return new Buffer( resource instanceof IFile ? (IFile)resource : null, owner, element.isReadOnly()); }
public static IBuffer createNullBuffer(IOpenable owner) { JavaElement element = (JavaElement) owner; IResource resource = element.resource(); return new NullBuffer( resource instanceof IFile ? (IFile)resource : null, owner, element.isReadOnly()); }
@Test public void modifyCompilation_javaVersionBewow18_noConversionPrepared() throws JavaModelException, CoreException, BadLocationException, IOException, URISyntaxException { CompilationUnit astRoot = setupEnvironment(String.join("\n" , "package " + PACKAGE_NAME , "import org.eclipse.swt.events.SelectionAdapter;" , "public class SamplePart {" , " @PostConstruct" , " public void createComposite() {" , " Button button = new Button(parent, SWT.PUSH);" , " button.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));" , " button.setText(\"Text\");" , " button.addSelectionListener(new SelectionAdapter() {" , " @Override" , " public void widgetSelected(SelectionEvent e) {" , " System.out.println(\"Hello\");" , " }" , " });" , " }" , "}" ), "1.7"); LambdaConverterCleanUp lambdaConverterCleanUp = new LambdaConverterCleanUp(); ICompilationUnit iCU = (ICompilationUnit) astRoot.getJavaElement().getAdapter(IOpenable.class); RefactoringStatus refactoringStatus = lambdaConverterCleanUp.checkPreConditions(env.getJavaProject(PROJECT_NAME), (ICompilationUnit[]) Arrays.asList(iCU).toArray(), new NullProgressMonitor()); assertEquals(4, refactoringStatus.getSeverity()); }
@Test public void createChange_singlelineClassInstanceCreationWidgetSelectedAdapter_savedSinglelineLambda() throws JavaModelException, CoreException, BadLocationException, IOException, URISyntaxException { CompilationUnit astRoot = setupEnvironment(String.join("\n" , "package " + PACKAGE_NAME , "import org.eclipse.swt.events.SelectionAdapter;" , "public class SamplePart {" , " @PostConstruct" , " public void createComposite() {" , " Button button = new Button(parent, SWT.PUSH);" , " button.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));" , " button.setText(\"Text\");" , " button.addSelectionListener(new SelectionAdapter() {" , " @Override" , " public void widgetSelected(SelectionEvent e) {" , " System.out.println(\"Hello\");" , " }" , " });" , " }" , "}" )); ICleanUpFix cleanUp = LambdaConverterFix.createCleanUp(astRoot, true); CompilationUnitChange compilationUnitChange = cleanUp.createChange(new NullProgressMonitor()); compilationUnitChange.perform(new NullProgressMonitor()); ICompilationUnit iCU = (ICompilationUnit) astRoot.getJavaElement().getAdapter(IOpenable.class); String expected = String.join("\n" , "package p" , "import static org.eclipse.swt.events.SelectionListener.widgetSelectedAdapter;" , "public class SamplePart {" , " @PostConstruct" , " public void createComposite() {" , " Button button = new Button(parent, SWT.PUSH);" , " button.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));" , " button.setText(\"Text\");" , " button.addSelectionListener(widgetSelectedAdapter(e -> System.out.println(\"Hello\")));" , " }" , "}"); assertEquals(expected, iCU.getSource()); }