Can I use the eclipse debugger to write a variable to a file - eclipse

Is it possible to create some sort of "trace breakpoint" in eclipse whereby Eclipse will log variables that I choose to a file when a "breakpoint" is hit without pausing the application?

Sure. For this sample method:
public static void logArgs(final String one, final String two) {
System.out.println(one + two);
}
put your breakpoint in it, right click it and edit Breakpoint properties... as in the example. The important checkboxes are Conditional and Suspend when 'true'. Just return false so that breakpoint does not suspend at all.
java.io.FileWriter w = new java.io.FileWriter("/tmp/file.txt", true);
w.write(String.format("args(%s, %s)%n"), one, two));
w.close();
return false;

For Java 11 MichaƂ Grzejszczak's answer can be written as
java.nio.file.Files.writeString(java.nio.file.Path.of("f.txt"), "My string to save");return true;
(Best way to write String to file using java nio)

Related

Winum can not locate elements on windows 10

I am newbie using Winium and installed a sample test - steps are only to open Notepad and click on the File button/menu item. The launching of the application (Notepad) works but it seems it can not locate the button. I have tried to locate using both name and id attributes without any luck. I am running on Windows 10 so my guess is it has something to do with this..Any tips or workarounds highly appriciated - i will pase my simple code below
Thanks!
public static void main(String[] args) throws MalformedURLException, InterruptedException {
DesktopOptions option = new DesktopOptions();
option.setApplicationPath("C:\\Windows\\System32\\notepad.exe");
WiniumDriver driver = new WiniumDriver(new URL("http://localhost:9999"), option);
Thread.sleep(2000);
WebElement el = driver.findElement(By.name("File"));
el.click();
}
You could try getting a reference to the window first, and then looking within that for an element called 'File'.
This works for me.
var window = driver.FindElementByClassName("Notepad");
var fileMenuHeader = window.FindElement(By.Name("File"));
fileMenuHeader.Click();
I'm not sure how you get the next level of menus though - it doesn't appear to be part of the window.
Try catching the menu-bar first with its ID.
Then with that element try catching the menu options like file, edit,etc.
Below code works fine on Windows 10.
var menubar = Driver.FindElementById("MenuBar");
var editMenu = menubar.FindElement(By.Name("Edit"));
var FileMenu = menubar.FindElement(By.Name("File");
editMenu.Click();

How create Part not restorable in e4 application

In e3 to create not restorable View I set field "restorable" to false in extension org.eclipse.ui.views and it works. In my e4 application I create PartDescriptor with tag "NoRestore" but it do nothing. After restart Part is shown. What I do wrong? Or it is bug?
If you let e4 save the workbench model on exit it is restored exactly as saved the next time the RCP is started. There is no support for a NoRestore tag.
Specifying the -clearPersistedState flag on startup will reset the model to the initial state. You can also specify -persistState false to stop the model being saved on exit.
If you just want to deal with one part you can alter the model in your life cycle class during startup. Something like:
#ProcessAdditions
public void processAdditions(MApplication app, EModelService modelService)
{
MUIElement el = modelService.find("your part id", app);
if (el != null) {
el.setToBeRendered(false);
}
}
which just finds a part and turns off the 'to be rendered' flag.
For compatibility with future versions, in which the IPresentationEngine.NO_RESTORE("NoRestore") tag will be present, you can use the following code.
#PreSave
void preSave(MApplication a_app, EModelService a_modelService){
ArrayList<MElementContainer<MUIElement>> containers = new ArrayList<>();
List<MPart> parts = a_modelService.findElements(a_app, null, MPart.class, Arrays.asList("NoRestore"));
parts.forEach(p -> {
p.setToBeRendered(false); // hide parts
containers.add(p.getParent()); // collect containers with no restorable parts
});
// hide containers which contains only no restorable parts
containers.stream().filter(c -> c.getChildren().stream().allMatch(ch -> ch.getTags().contains("NoRestore"))).forEach(c -> c.setToBeRendered(false));
}
NOTE. Attempts to add the same code to methods with annotations #ProcessAdditions or #ProcessRemovals did not help: errors occurred and after the restart of the application no parts were displayed. So I added my code to the #PreSave method.

How to pass an object from one part to another part in Eclispe e4 RCP?

I am building an application with eclipse e4 RCP. I have a navigator (similar to Navigator in eclipse IDE) and I would like to link it to an editor (similar to how a file in Navigator in eclipse IDE is linked to an editor). Currently I am using EPartService to open up my editor Part (by creating a new instance) when the user double clicks on a file in the Navigator tree. But I would like to pass it a parameter (a String or an Object) to let it know which file to open in the editor. I want to be able to open multiple editors for different nodes of the Navigator tree. I have done a lot of research on internet but could not find a solution. I think its a common problem and the e4 framework should provide an mechanism to pass such parameters from one Part to another Part. Current code is as below:
viewer.addDoubleClickListener(event -> {
final IStructuredSelection selection = (IStructuredSelection) event.getSelection();
FileNode file = null;
boolean partExists = false;
if (selection.getFirstElement() instanceof FileNode ) {
file = (FileNode ) selection.getFirstElement();
for (MPart part1 : partService.getParts()) {
if (part1.getLabel().equals(file.getName())) {
partService.showPart(part1, PartState.ACTIVATE);
partExists = true;
break;
}
}
if (!partExists) {
MPart part2 = partService
.createPart("com.parts.partdescriptor.fileeditor");
part2.setLabel(file.getName());
partService.showPart(part2, PartState.ACTIVATE);
}
}
});
Is it possible to say something like part2.setParameter("PARAM_NAME", "FILE_NAME"); ?
When you have an MPart you can call:
MPart mpart = ...
MyClass myClass = (MyClass)mpart.getObject();
to get your class for the part (the class defined in the 'Class URI' for the part in the Application.e4xmi). You can then call any methods you have defined on your part class.
You can also set data in the 'transient data' area of a part:
mpart.getTransientData().put("key", "data");
Object data = mpart.getTransientData().get("key");

Making Ctrl-C copy from whichever SourceViewer has focus in Eclipse plug-in

I successfully extended the PyDev editor in Eclipse with a side-by-side display, but I can't copy the contents of the extra SourceViewer that I added. I can select some text in the display, but when I press Ctrl+C, it always copies the main PyDev editor's selected text.
I found an article on key bindings in Eclipse editors, but the code there seems incomplete and a bit out-of-date. How can I configure the copy command to copy from whichever SourceViewer has focus?
The reason I want to do this is that I've written a tool for live coding in Python, and it would be much easier for users to submit bug reports if they could just copy the display and paste it into the bug description.
David Green's article was a good start, but it took a bit of digging to make it all work. I published a full example project on GitHub, and I'll post a couple of snippets here.
The TextViewerSupport class wires up a new action handler for each command you want to delegate to the extra text viewer. If you have multiple text viewers, just instantiate a TextViewerSupport object for each of them. It wires up everything in its constructor.
public TextViewerSupport(TextViewer textViewer) {
this.textViewer = textViewer;
StyledText textWidget = textViewer.getTextWidget();
textWidget.addFocusListener(this);
textWidget.addDisposeListener(this);
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
handlerService = (IHandlerService) window
.getService(IHandlerService.class);
if (textViewer.getTextWidget().isFocusControl()) {
activateContext();
}
}
The activateContext() method has a list of all the commands you want to delegate, and registers a new handler for each one. This was one of the changes from David's article; his ITextEditorActionDefinitionIds has been deprecated and replaced with IWorkbenchCommandConstants.
protected void activateContext() {
if (handlerActivations.isEmpty()) {
activateHandler(ITextOperationTarget.COPY,
IWorkbenchCommandConstants.EDIT_COPY);
}
}
// Add a single handler.
protected void activateHandler(int operation, String actionDefinitionId) {
StyledText textWidget = textViewer.getTextWidget();
IHandler actionHandler = createActionHandler(operation,
actionDefinitionId);
IHandlerActivation handlerActivation = handlerService.activateHandler(
actionDefinitionId, actionHandler,
new ActiveFocusControlExpression(textWidget));
handlerActivations.add(handlerActivation);
}
// Create a handler that delegates to the text viewer.
private IHandler createActionHandler(final int operation,
String actionDefinitionId) {
Action action = new Action() {
#Override
public void run() {
if (textViewer.canDoOperation(operation)) {
textViewer.doOperation(operation);
}
}
};
action.setActionDefinitionId(actionDefinitionId);
return new ActionHandler(action);
}
The ActiveFocusControlExpression gives the new handler a high enough priority that it will replace the standard handler, and it's almost identical to David's version. However, to get it to compile, I had to add extra dependencies to my plug-in manifest: I imported packages org.eclipse.core.expressions and org.eclipse.ui.texteditor.

Eclipse: selection autocopy to clipboard

I love an Emacs feature to copy selection to clipboard automatically. Is it possible to do the same on Eclipse?
Environment: Windows XP, Helios
To copy a String from Eclipse to the clipboard, you can use
void copyToClipboard (String toClipboard, Display display){
String toClipboard = "my String";
Clipboard clipboard = new Clipboard(display);
TextTransfer [] textTransfer = {TextTransfer.getInstance()};
clipboard.setContents(new Object [] {toClipboard}, textTransfer);
clipboard.dispose();
}
Then you can call this method from a MouseAdapter or KeyAdapter, depending on where you want to get your String from. In your case it could be MouseAdapter, which listens to doubleclicks, gets the current cursor position of the text, marks the word and then adds the String to the clipboard.
edit to answer a question: You can set up your own MouseAdapater and attach it to buttons, text fields or whateer you like. Here's an example for a button:
Button btnGo1 = new Button(parent, SWT.NONE);
btnGo1.setText("Go");
btnGo1.addMouseListener(new MouseAdapter() {
#Override
public void mouseDoubleClick(MouseEvent e) {
//do what you want to do in here
}
});
If you want to implement mouseUp and mouseDown events, too, you can just add MouseListenerinstead of the Adapter. The only advantage of the Adapter is, that you don't have to override the other methods of the interface.
Since the original question was to automatically get the selection of the text of an editor: the way to get the selection from an editor is explained here.
You can try this plugin. Along with auto copy points mentioned in Eclipse show number of lines and/or file size also addressed.