I am quite new to Eclipse Plugin development so I need a bit of help.
I have a project in which I must get the current position of the cursor within an active editor and upon clicking a button, I am to display in a dialog box the method directly surrounding it. I have tried the following and I am so far only able to get the name of the method, but not the entire source code as I want. If I try only with compilationUnit I can also get the entire source code of the active editor. Other questions seem to only require the name of the method, but I'm interested in getting the full source code of the method. Is there any way I can get the source code of only the method directly surrounding the cursor?
IWorkbenchPage page = window.getActivePage();
IEditorPart editor = page.getActiveEditor();
ITextEditor textEditor = (ITextEditor) page.getActiveEditor();
IJavaElement element = JavaUI.getEditorInputJavaElement(textEditor.getEditorInput());
if (element instanceof ICompilationUnit) {
ITextSelection selection = (ITextSelection) ((JavaEditor) textEditor).getSelectionProvider().getSelection();
IJavaElement selected;
try {
selected = ((ICompilationUnit) element).getElementAt(selection.getOffset());
if (selected != null && selected.getElementType() == IJavaElement.METHOD) {
return (IMethod) selected;
}
MessageDialog.openInformation(
window.getShell(),
editor.getTitle(),
selected +"\n"); //(IMethod)
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Yeah so I found an answer. It took a while but I finally figured it out.
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
try {
IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
ISelection selection = workbenchWindow.getSelectionService().getSelection();
ITextSelection textSelection;
if (selection instanceof ITextSelection)
textSelection = (ITextSelection) selection;
else
throw new RuntimeException("No text selection");
IEditorInput editorInput = workbenchWindow.getActivePage().getActiveEditor().getEditorInput();
ICompilationUnit compilationUnit = JavaUI.getWorkingCopyManager().getWorkingCopy(editorInput);
IJavaElement elementWithCursorInside = compilationUnit.getElementAt(textSelection.getOffset());
ISourceReference sourceReference;
if (elementWithCursorInside instanceof ISourceReference)
sourceReference = (ISourceReference) elementWithCursorInside;
else
throw new RuntimeException("Not an ISourceReference");
MessageDialog.openInformation(window.getShell(), "Source Code of the Method", sourceReference.getSource());
} catch (Exception e) {
e.printStackTrace();
}
return null;
this seems to work well for me now. I hope maybe my solution will help someone else with the same problem
Related
I want to find a way to do kind of a custom "paste from clipboard" action. Let's assume the content of clipboard is text for simplicity (not a file). Whenever you press Ctrl+V, it inserts that content (which is text) to a current open file which has a focus.
I have an app for catching a global hotkey. Note this is not a window application, it's a console one and it catches the hotkey globally. Let's say I have the hotkey of Ctrl+U. So what I want to do is when I press Ctrl+U I want to insert some predefined text to a current open file. Just like Ctrl+V does! The differences from a standard Ctrl+V is that I want to insert a predefined text and the hotkey is different.
How do I do this?
I'd prefer a cross-platform solution, however first of all I'm going to do that for Linux, specifically Ubuntu. The language is not important but Java or Scala would be better. Of course, I understand that the solutions is Java uses native OS' API for that.
I'm hoping that this hackish solution would work, but it is still untested, I am unsure how to catch the event for the hotkey.
The idea behind this code is the following five steps:
Get the old text in the clipboard and temporarily save it
Paste our predefined text into the clipboard
Trigger the global paste event
Release the global paste event
Reset the clipboard to the old text
This should give the appearance of a new clipboard (if not, hopefully it inspires you to come up with a better, less hackish solution).
Without further ado, here is my code. First I have a simple helper method to set the value of the clipboard (as we do this twice).
public static void setClipboard(String s) {
StringSelection contents = new StringSelection(s);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(contents, contents);
}
And then, I have a main method where I go through the five steps in order.
public static void main(String[] args) {
// Step 1 ) get old text
String oldText = "";
try {
oldText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// Step 2 ) paste our text in clipboard
setClipboard("This lorem ipsum predefined string blows my mind.");
// Step 3 ) trigger paste event
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException awte) {
awte.printStackTrace();
}
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
// Step 4 ) Release paste event
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
// Step 5 ) Reset clipboard
setClipboard(oldText);
}
[Edit]:
Here is some code to test what kind of contents are in the Clipboard - image, text, etc. The unicode error was coming from the fact that the old contents of the clipboard were something that couldn't be represented by a plain String. To fix this error, you will have to check if the old contents were an image, the old contents were text, and save them accordingly.
public static int kindOfContents() {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
if(contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// String, save temporarily as string and write back as string
return 0;
} else if(contents.isDataFlavorSupported(DataFlavor.imageFlavor)) {
// Image, save temporarily as BufferedImage and write back as image
return 1;
} else if(contents.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
// List of files, save temporarily as java.util.List interface and write back as the file lists
return 2;
}
}
If the contents are text, then for saving and writing the content you would use the old method, repasted below for convenience.
// Step 1 ) get old text
String oldText = "";
try {
oldText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// Step 5 ) Reset clipboard
setClipboard(oldText);
However, if the contents are an image, then for saving temporarily and rewriting you need to do the following. Note that the code for writing the image is not mine, but is taken from the accepted answer at Setting images to Clipboard - Java
// Step 1 ) get old image
BufferedImage img = null;
try {
img = (BufferedImage) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.imageFlavor);
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Taken from Setting images to Clipboard - Java :
// Step 5 ) Reset clipboard
ImageTransferable transferable = new ImageTransferable( image );
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(transferable, null);
static class ImageTransferable implements Transferable
{
private Image image;
public ImageTransferable (Image image)
{
this.image = image;
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException
{
if (isDataFlavorSupported(flavor))
{
return image;
}
else
{
throw new UnsupportedFlavorException(flavor);
}
}
public boolean isDataFlavorSupported (DataFlavor flavor)
{
return flavor == DataFlavor.imageFlavor;
}
public DataFlavor[] getTransferDataFlavors ()
{
return new DataFlavor[] { DataFlavor.imageFlavor };
}
}
im working with Java Swing.
Im trying with print method of Jtable...
public void actionPerformed(java.awt.event.ActionEvent ignore) {
MessageFormat header = new MessageFormat("Page {0,number,integer}");
try {
table.print(JTable.PrintMode.FIT_WIDTH, header, null);
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n", e.getMessage());
}
}
To show a printing dialog . Its work fine ..
The printing dialog
But i want to change the text dialog language to Spanish with a Locale class , how can i do it ???
Thanks!
#Diego
I copied your solution here so it can be more easily read.
It was inspire by the old forum entry here: https://forums.oracle.com/thread/1287832
---- Begin ----
Just adding reflection to change the ResourceBlunde before Jtable.print() method...
try {
Class cl = Class.forName("sun.print.ServiceDialog");
if (cl != null) {
Field fld = cl.getDeclaredField("messageRB");
if (fld != null) {
fld.setAccessible(true);
fld.set(cl, ResourceBundle.getBundle("sun.print.resources.serviceui_es"));
}
}
} catch (Exception ex11) {
ex11.printStackTrace();
}
---- End ----
I may want to search and find it someday.
I'm having problems with these 2 different options, the first one opens up just fine to a browser for future use, but the second option opens the browser and not the dialogue in which i'd like to have open. Also can someone tell me how to make the cancel button cancel out and not open the browser, thanks in advance here's the code.
public static void CheckForUpdates(){
Object[] possibleValues = { "Check for Updates", "Check for version ID" };
Object selectedValue = JOptionPane.showInputDialog(null,
"What would you like to do?", "",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if ( JOptionPane.YES_NO_OPTION == JOptionPane.YES_OPTION) {
try {
Desktop.getDesktop().browse(new URI("www.google.ca"));
} catch (IOException | URISyntaxException e) {
}
if ( JOptionPane.YES_NO_OPTION == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(frame, "version ID: V1");
}
}
}
Comparing constants is deterministic, i.e. you don't get any variation in behavior.
You need to check the result of showInputDialog which is an Object value. The value is null when nothing (cancel) is selected.
if (selectedValue != null) { // anything selected?
// Check for version ID?
if (selectedValue.toString().equals(possibleValues[1])) {
JOptionPane.showMessageDialog(null, "version ID: V1");
} else {
try {
Desktop.getDesktop().browse(new URI("www.google.ca"));
} catch (IOException | URISyntaxException e) {
}
}
}
Aside: Java naming conventions show that method names start with an lowercase letter such as checkForUpdates.
I am trying to use Selenium with JUnit and I am having trouble completing my tests because it seems like my button execution is only occurring once. here's some of the code:
JQueryUITab navTab = new JQueryUITab(driver.findElement(By.cssSelector("nav ul.tabs")));
try {
navTab.selectTab("Tab1");
} catch (Exception e) {
e.printStackTrace();
}
try {
navTab.selectTab("Tab2");
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(navTab.getSelectedTab());
the console print out will read "Tab1". this JQueryUITab object is a custom object. here are the inner workings:
public String getSelectedTab() {
List<WebElement> tabs = jQueryUITab.findElements(By.cssSelector("li.tab"));
for (WebElement tab : tabs) {
if (tab.getAttribute("class").equals("tab selected")) {
return tab.getText();
}
}
return null;
}
public void selectTab(String tabName) throws Exception {
boolean found = false;
List<WebElement> tabs = jQueryUITab.findElements(By.cssSelector("li.tab"));
for (WebElement tab : tabs) {
if(tabName.equals(tab.getText().toString())) {
tab.click();
found = true;
break;
}
}
if (!found) {
throw new Exception("Could not find tab '" + tabName + "'");
}
}
There are no exceptions thrown. At least pertaining before or at this part of the code.
There were a couple problems wrong with my implementation. Firstly, it could have been improved by selecting not the li.tab object, but the a class inside of it. From there, there were 2 solutions that worked for me. First was using
webElement.sendKeys(Keys.ENTER);
and the second (imho more elegant solution) was to get the instance of the selenium driver object controlling the object and then get it to execute the command to click the tab. Here's the full corrected method.
public void selectTab(String tabName) throws Exception {
boolean found = false;
List<WebElement> tabs = jQueryUITab.findElements(By.cssSelector("li.tab a"));
for (WebElement tab : tabs) {
if(tabName.equals(tab.getText().toString())) {
// tab.sendKeys(Keys.ENTER);
WrapsDriver wrappedElement = (WrapsDriver) jQueryUITab;
JavascriptExecutor driver = (JavascriptExecutor) wrappedElement.getWrappedDriver();
driver.executeScript("$(arguments[0]).click();", tab);
found = true;
break;
}
}
if (!found) {
throw new Exception("Could not find tab '" + tabName + "'");
}
}
How do I launch a find and replace command without the user clicking edit->find replace or ctrl+F? I need to do this with a plug-in written in Java.
The action that launches the dialog is FindInFileActionDelegate (it has a few sister types for different scopes), this is found in the org.eclipse.search plugin.
The delegates all inherit from a common parent called RetrieverAction. The RetrieverAction's run() method shows the dialog and runs the query. You can take the relevant processing from this method. You may need to register as an ISelectionListener to track the active selection.
public void run() {
IWorkbenchPage page= getWorkbenchPage();
if (page == null) {
return;
}
TextSearchQueryProvider provider= TextSearchQueryProvider.getPreferred();
String searchForString= getSearchForString(page);
if (searchForString.length() == 0) {
MessageDialog.openInformation(getShell(), SearchMessages.RetrieverAction_dialog_title, SearchMessages.RetrieverAction_empty_selection);
return;
}
try {
ISearchQuery query= createQuery(provider, searchForString);
if (query != null) {
NewSearchUI.runQueryInBackground(query);
}
} catch (OperationCanceledException ex) {
// action cancelled
} catch (CoreException e) {
ErrorDialog.openError(getShell(), SearchMessages.RetrieverAction_error_title, SearchMessages.RetrieverAction_error_message, e.getStatus());
}
}