I am unable to upload attachment using SeleniumWebDriver - eclipse

This is my Code
driver.findElement(By.id("ctl00_ContentPlaceHolder1_cbpAssociationNew_panelAssnDetailAdd_Add_Photo_Browse0")).click();
Thread.sleep(2000);
StringSelection ss= new StringSelection("C:\\Users\\ns10\\Desktop\\download.jpg");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
Robot robo=new Robot();
robo.delay(1000);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
robo.keyPress(KeyEvent.VK_CONTROL);
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_CONTROL);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
When I run the above code in Eclipse, it clicks on the File upload; then the windows pop up comes but doesn't select the file which I mentioned. It was just idle.
Could someone please help me with this.

If possible try this first,
driver.findElement(By.id("ctl00_ContentPlaceHolder1_cbpAssociationNew_panelAssnDetailAdd_Add_Photo_Browse0")).sendKeys("C:\\Users\\ns10\\Desktop\\download.jpg");
This is a noted way to upload file via selenium webdriver as of now, where you don't have to bother about clicking on the File Upload button and then using Robot class to upload image. Just sending the path of the file to upload will accomplish the Upload.
If it still doesn't work, then below is the alternative way by using Robot and Sikuli (combined) to accomplish the task:-
Problem:-
Sometimes, the Robot class types the "attachment_path" into the "File Name" field of textbox but doesn't presses 'Enter key' thereafter for the file to upload.
Solution:-
To avert that, I've used Sikuli to click on the Open button, which does infact uploads the file then;
(Note:- You have to take a screenshot of Open button in the window's dialog box, that comes up after clicking on the "File Upload button".
First of all download sikuli-api standalone jar. And, add it to the build path of your project. Then, add the below code for the file upload:-
//Clicking on the File Upload button
driver.findElement(By.id("ctl00_ContentPlaceHolder1_cbpAssociationNew_panelAssnDetailAdd_Add_Photo_Browse0")).click();
//Copying the path of the file to the clipboard
StringSelection attachment = new StringSelection("C:\\Users\\ns10\\Desktop\\download.jpg"); //path to the attachment
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(attachment, null);
//Pasting the contents of clipboard in the field "File name" of the Window Pop-up
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
try{
ScreenRegion screen = new DesktopScreenRegion(); //screen is the default screen region which corresponds to the entire screen on your default monitor.
Target target = new ImageTarget(new File("<PUT HERE THE PATH FOR THE OPEN BUTTON'S IMAGE>"));
ScreenRegion screen_web = screen.wait(target,5000);
screen_web = screen.find(target); //screen_web holds the screen region occupied by the "Open" button that was found by Sikuli's image recognition engine.
if(screen_web != null)
{
Mouse mouse = new DesktopMouse(); // Create a mouse object
mouse.click(screen_web.getCenter()); // Use the mouse object to click on the center of the target region, i.e., the Open button
}else{
throw new Throwable();
}
}catch(Throwable e){
System.err.println("The Open file button wasn't clicked!!" + e.getMessage() + "\n---------------------");
}
Code for Uploading in Tiny Pic.com :-
package pack_ads;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.api.DesktopScreenRegion;
import org.sikuli.api.ImageTarget;
import org.sikuli.api.ScreenRegion;
import org.sikuli.api.Target;
import org.sikuli.api.robot.Mouse;
import org.sikuli.api.robot.desktop.DesktopMouse;
public class Testing_TinyPicUpload {
public static void main(String[] args) throws AWTException, InterruptedException {
WebDriver driver = new FirefoxDriver(); //Opens a firefox browser instance
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //Timeout of 30 seconds given
driver.manage().window().maximize(); //Maximizing the window
//Navigating to tiny pic site
driver.get("http://tinypic.com/");
//Uploading photo
driver.findElement(By.xpath("//input[#id='the_file']")).click(); //Locating the attach button
//Copying the path of the file to the clipboard
StringSelection photo = new StringSelection("D:\\\\Images\\default.jpg"); //Putting the path of the image to upload
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(photo, null);
//Pasting the contents of clipboard in the field "File name" of the Window Pop-up
Thread.sleep(5000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
try{
ScreenRegion screen = new DesktopScreenRegion(); //screen is the default screen region which corresponds to the entire screen on your default monitor.
Target target = new ImageTarget(new File("Tinyimages\\Open_file.png")); //Made a folder in my project as Tinyimages and put the image of Open_file in there.
ScreenRegion screen_web = screen.wait(target,5000);
screen_web = screen.find(target); //screen_web holds the screen region occupied by the "Open" button that was found by Sikuli's image recognition engine.
if(screen_web != null)
{
Mouse mouse = new DesktopMouse(); // Create a mouse object
mouse.click(screen_web.getCenter()); // Use the mouse object to click on the center of the target region, i.e., the Open button
}
else{
throw new Throwable();
}
System.out.println("Attachment was successfully done.\n------------------------------\n");
}catch(Throwable e){
System.err.println("The Open file button wasn't clicked!!" + e.getMessage() + "\n------------------------------");
}
}
}
Note: You can download use this image for the "Open" button from here. Change the file path accordingly in the code Target target = new ImageTarget(new File("Tinyimages\\Open_file.png"));

I was finding the same result, that the code would halt and wait when the File Upload window was opened, and would only continue after the window was closed.
As a workaround I put the thread sleep and the robot keypresses in a separate thread that I spawned just before clicking the file upload button. This solved the issue for me.
// Thread class to be instantiated and run just before button click:
//
public class PasteUploadFileThread extends Thread {
String uploadFileName = "";
public PasteUploadFileThread(String filename){
this.uploadFileName = filename;
}
public void run() {
try {
// Pause 3 seconds giving window time to open up
Thread.sleep(3000);
System.out.println("STARTING PasteUploadFileThread for file: " + this.uploadFileName);
StringSelection ss= new StringSelection(this.uploadFileName);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
Robot robo=new Robot();
robo.delay(2000);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
robo.keyPress(KeyEvent.VK_CONTROL);
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_CONTROL);
robo.delay(2000);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
System.out.println("ENDING PasteUploadFileThread for file: " + this.uploadFileName);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (AWTException e) {
e.printStackTrace();
}
}
}
// Portion of the test class that spawns the thread and then clicks the button
String filepath = "C:\\UploadDocument.txt";
WebElement browseButton = wait60Secs.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[contains(.,'Browse')]")));
// Spawn a thread that will do the interacting with the File Upload window.
// This is needed because when we click on the browse button the code halts waiting for the File Upload window to be closed.
// So this thread will go off on it's own and do it's work while this code is paused.
(new PasteUploadFileThread(filepath)).start();
browseButton.click();
// Execution continues here after the Upload window is closed...
// Find the file that was uploaded before continuing
wait60Secs.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[contains(.,'UploadDocument.txt')]")));

Related

Make jxBrowser open popups in the current window instead of "popping up"

How to set jxBrowser to open links that would pop-up in a new window to open on the calling page (or, at least, in a new tab)?
this is the call I think I have to override (it's the example):
//....
Engine engine = Engine.newInstance(
EngineOptions.newBuilder(
enderingMode.OFF_SCREEN ).enableIncognito().build()
Browser _browser = engine.newBrowser();
//this won't even compile
_browser.set(
OpenPopupCallback.class,
(params) -> {
// Access the created popup.
Browser popup = params.popupBrowser();
_browser.navigation().loadUrl(params.targetUrl());
return Response.proceed();
});
_browser.navigation().loadUrl("http://www.stackoverflow.com");
This is how I call it in my jfx but won't even compile, the code without this call works (opens a browser).
Update, given the nature of the popup I tried to rewrite javascript function (window.open) itself to force name to _parent.
This by running on every navigation the code
String the Javascript = "window.open = function (open) {return function (url, name, features{ console.log("open wrapper");return open.call(window, url, '_parent', features);};}(window.open);"
I thaught I couldn achieve this by
_browser.frames().get(0).executeJavaScript(theJavascript);
But in the remote console, I can't even see the log message ("open wrapper").
I double-checked the same code and it works if copy-pasted in the remote consolle.
What am I missing?
Here's complete JavaFX example that demonstrates how to open popup's URL in the main Browser instance and suppress popup:
import static com.teamdev.jxbrowser.engine.RenderingMode.OFF_SCREEN;
import com.teamdev.jxbrowser.browser.Browser;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback.Response;
import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.view.javafx.BrowserView;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public final class SmokeTest extends Application {
#Override
public void start(Stage primaryStage) {
// Creating and running Chromium engine.
Engine engine = Engine.newInstance(OFF_SCREEN);
Browser browser = engine.newBrowser();
browser.set(CreatePopupCallback.class, params -> {
browser.navigation().loadUrl(params.targetUrl());
return Response.suppress();
});
// Creating UI component for rendering web content
// loaded in the given Browser instance.
BrowserView view = BrowserView.newInstance(browser);
BorderPane root = new BorderPane(view);
Scene scene = new Scene(root, 1280, 900);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
browser.navigation().loadUrl(
"https://www.encodedna.com/javascript/demo/open-new-window-using-javascript-method.htm");
// Close the engine when stage is about to close.
primaryStage.setOnCloseRequest(event -> engine.close());
}
}
Run this program and click a button that displays popup. You will see that popup is not displayed and its URL is loaded in the main Browser.

Create new NetBeans "save as" module

My goal is simple - save the current HTML file in the NetBeans editor with one additional line at the top and bottom of the file, and with the extension of ".h".
This is my first attempt at a NetBeans module, but following some tutorials and research, I got as far as adding an entry to the popup menu when you right-click on an HTML file in the editor. It currently just shows a "Hello World" message:
The code to do that is here:
package ksmiller99.savehtmlasarduinoresource;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
#ActionID(
category = "Edit",
id = "ksmiller99.savehtmlasarduinoresource.SaveHtmlAsArduinoResource"
)
#ActionRegistration(
displayName = "#CTL_SaveHtmlAsArduinoResource"
)
#ActionReference(path = "Editors/text/html/Popup")
#Messages("CTL_SaveHtmlAsArduinoResource=Save as Arduino Resource")
public final class SaveHtmlAsArduinoResource implements ActionListener {
#Override
public void actionPerformed(ActionEvent ev) {
//todo add a line to top and bottom of current file and save with .h extension
JOptionPane.showMessageDialog(null, "Hello Save As World");
}
}
How can I access the contents of the current editor? Would a different approach make more sense?
I'm using NetBeans 12.0, JDK 13, Windows 10.
Use the New Action wizard to create the source code for a Conditionally Enabled action, enabled when User Selects One Node.
In the 2nd wizard panel select File Type Context Menu and choose text/html as content type. If you want your action to appear only in the context menu you can disable Global Menu Item.
You should end up with code like this:
#ActionID(
category = "File",
id = "org.test.TestHtmlAction"
)
#ActionRegistration(
displayName = "#CTL_TestHtmlAction"
)
#ActionReference(path = "Loaders/text/html/Actions", position = 0)
#Messages("CTL_TestHtmlAction=TestHtmlAction")
public final class TestHtmlAction implements ActionListener
{
private final DataObject context;
private static final Logger LOGGER = Logger.getLogger(TestHtmlAction.class.getName());
public TestHtmlAction(DataObject context)
{
this.context = context;
}
#Override
public void actionPerformed(ActionEvent ev)
{
FileObject file = context.getPrimaryFile();
LOGGER.info("context=" + context.getName() + " file.getPath()=" + file.getPath());
}
}
The wizard creates a context aware action, which is enabled only when user selects a single HTML file node. The DataObject parameter gives you the context of the selected node, so you can retrieve the file path etc.

E4: drag an object from a TableViewer to Windows Explorer (or OS specific file system)

In my Eclipse RCP application I display some business data in a TableViewer.
I want the user to be able to drag a row from the table viewer and drop it on the windows desktop/explorer. Windows should then create a file with the data from the selected row that I could provide in the dragSetData(..) method of the DragSourceAdapter class.
How to implement this? It seems that using FileTransfer as the dragSourceSupport on the table viewer is the way to go as it trigger a call to the dragSetData() method. But what object should I create and assign to "event.data" in this method?
A working example would be appreciated.
I've implemented the reverse without problem, i.e. drag a file from windows explorer onto the TableViewer and add a row in the table. There are plenty on sample for this on the net but can't find a sample of the opposite, drag from eclipse to the OS
[edit + new requirement]
So I understand that I have to create a temporary file somewhere and set the name of that temp file in event.data in dragSetData()
Q: is there a simpler way to do that, eg set somewhere (iun data) the content of the file directly without the temp file?
There is another requirement. When the drop operation is about to occur, I want to show a popup to the user that will have to choose what "business data" from the "row" he wants to export and the name of the file that will be created. I tried the following (only asking for the filename for now) but it does not work as expected as the popup shows up as soon as the cursor reach the first pixel outside my app. I would like to show the popup just "before" the drop operation occurs.
Q: is there a way to have this popup show just before the drop operation occurs, ie when the user "release" the mouse button?
#Override
public void dragSetData(final DragSourceEvent event){
if (FileTransfer.getInstance().isSupportedType(event.dataType)) {
// Will be a more complex dialog with multiple fields..
InputDialog inputDialog = new InputDialog(shell, "Please enter a file name", "File Name:", "", null);
if (inputDialog.open() != Window.OK) {
event.doit = false;
return;
}
event.data = new String[] { inputDialog.getValue() };
}
}
The event.data for FileTransfer is an array of file path strings.
You DragSourceAdapter class might look something like:
public class MyDragSourceAdapter extends DragSourceAdapter
{
private final StructuredViewer viewer;
public MyDragSourceAdapter(final StructuredViewer viewer)
{
super();
this.viewer = viewer;
}
#Override
public void dragStart(final DragSourceEvent event)
{
IStructuredSelection selection = viewer.getStructuredSelection();
if (selection == null)
return;
// TODO check if the selection contains any files
// TODO set event.doit = false if not
}
#Override
public void dragSetData(final DragSourceEvent event)
{
if (!FileTransfer.getInstance().isSupportedType(event.dataType))
return;
IStructuredSelection selection = viewer.getStructuredSelection();
List<String> files = new ArrayList<>(selection.size());
// TODO add files in the selection to 'files'
event.data = files.toArray(new String [files.size()]);
}
}
and you install it on your viewer with:
MyDragSourceAdapter adapter = new MyDragSourceAdapter(viewer);
viewer.addDragSupport(DND.DROP_COPY, new Transfer [] {FileTransfer.getInstance()}, adapter);

How to open a filedialog within an Eclipse Wizard

I'm writing an Eclipseplugin, which has to create a new project. This works so far, but i need to copy an external file into the projectfolder. I intend to have a 'Browse' button on one of my WizardPages, which opens a filedialog, where the user can browse to the file and after closing the dialog i can use the path to this file for various actions. My problem is that the dialog window never opens. Right now i'm trying it that way (snippet from my wizardpage):
public void createControl(Composite composite) {
this.container = new Composite(composite, SWT.NONE);
GridLayout layout = new GridLayout();
this.container.setLayout(layout);
layout.numColumns = 2;
Button browseButton = new Button(this.container, SWT.PUSH);
browseButton.setText("Browse");
browseButton.addSelectionListener(new SelectionListener() {
#Override
public void widgetDefaultSelected(SelectionEvent arg0) {
FileDialog fileDialog = new FileDialog(DataPage.this.container.getShell(), SWT.OPEN);
fileDialog.setText("JZOS created File");
String path = fileDialog.open();
DataPage.this.setJzosCreatedName(path);
}
});
I tried several implementations, that i have seen in examples and tutorials but nothing did work. I'm assuming a problem with the Shell that i give to the filedialog. I tried to open a new Shell within the widgetDefaultSelected function but it didn't work either. Any Suggestions?
You should be using the widgetSelected method of SelectionListener not widgetDefaultSelected

Eclipse - Opening editor programmatically causes focus problems

I'm having a bit of an issue with an eclipse plugin that I am working on. In this plugin, a special type of plugin-specific editor is often opened programmatically; this is triggered by various actions in various views/editors, but the code to open the editor is the same. The plugin-specific editors open fine; however, I've recently noticed that every time one of these editors is opened, a strange focus glitch happens:
When the editor is opened, it appears to receive focus, but if the previously active view/editor is clicked immediately after this, it does not take back focus. As soon as anything other than the previously active view/editor is clicked, the problem is instantly solved, and focus resumes normally.
As an example, say you choose a context menu option from the Package Explorer view, which causes an editor to open. The editor opens properly and appears to have focus. After this, you first click again on the Package Explorer, but it doesn't get focus (the editor still appears to have focus). You right-click on Package Explorer, but Package Explorer-specific context menu items do not appear. After this, you click on some other view and then on Package Explorer again. Now Package Explorer gets focus, as normal.
This is the code I'm using to open the editor:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
final GraphEditorPart gp = (GraphEditorPart) page.openEditor(new NullEditorInput(), "editor.id");
After this, the editor is populated with some visuals, via the albireo SWT-AWT bridge (Not sure if this is relevant to the problem -- the class used for main editor elements is org.eclipse.albireo.core.SwingControl).
I thought perhaps the problem was that the editor wasn't "really" getting focus, or the previously active view wasn't "really" losing focus, so I tried adding the following line:
page.activate(gp);
However this didn't seem to change anything. Why this might happen?
package name:rcp_demo.Editor
class name: EmpCommand.java, EmployeeEditor.java and EmployeeEditorInput.java
package rcp_demo.Editor;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
public class EmpCommand extends AbstractHandler {
public static final String Id = "rcp_demo.Editor.EmpCommand";
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IEditorReference[] editors = page.getEditorReferences();
EmployeeEditorInput input = new EmployeeEditorInput();
//All Comments are easily understand
//public class EmployeeEditorInput implements IEditorInput{}
for (int i=0; i<editors.length; i++) {
//List out all Exist editor
//compare with EmployeeEditor.Id="rcp_demo.Editor.emp";
if (editors[i].getId().equals(EmployeeEditor.Id)) {
//public class EmployeeEditor extends EditorPart
//{
// public static final String Id="rcp_demo.Editor.emp";
// public void createPartControl(Composite parent) {.....}
//}
page.activate(editors[i].getEditor(true));
System.out.println("set focus an existing editor(Employee)");
return null;
}
}
try {
//open new Editor like EmployeeEditor.Id="rcp_demo.Editor.emp";
page.openEditor(input,EmployeeEditor.Id);
System.out.println("open Editor(Employee) ");
} catch (PartInitException e) {
e.printStackTrace();
}
return null;
}
}
Full describe this question and answer visit :
Eclipse RCP : have the same editor open in editor window