How do I simulate a click with coordinates on HtmlPage then get the result a HtmlPage?
I want to click a button without an id or a name
I'm using the library com.gargoylesoftware.htmlunit
not sure about specific system or browser settings, but in general you can do this by following:
import java.awt.event.*;
import java.awt.Robot;
public class test {
int xparam=50;
int yparam=100;
public static void main(String args[]) {
Robot mybot = null;
try {
mybot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instant. Robot: " + failed);
}
int maske = InputEvent.BUTTON1_DOWN_MASK;
mybot.mouseMove(xparam,yparam);
mybot.mousePress(maske);
mybot.mouseRelease(maske);
}
}
For a smoother solution take a look at this ;
No,You can't click button with coordinates(X,Y).
Please specify the element other attributes because it can be click with help of other attribute
Related
I am trying to automate an android application using Appium and Cucumber with Java.I have written the code for a functionality and it is working fine. But some times while running the script, it throws an error
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original err
or: Could not proxy command to remote server. Original error: Error: read ECONNRESET (WARNING: The server did not provid
e any stacktrace information)
Source code:
import com.google.common.base.Function;
import com.intel.truevr.appautomation.core.Capabilities;
import org.openqa.selenium.By;
import io.appium.java_client.MobileDriver;
import io.appium.java_client.MobileElement;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openqa.selenium.support.ui.Wait;
import java.util.List;
import io.appium.java_client.TouchAction;
public class C754L2D {
Capabilities c = new Capabilities();
MobileDriver driver = c.getDefaultCapabilities();
Wait wait = new Wait() {
#Override
public Object until(Function isTrue) {
return null;
}
};
#Given("^User taps the toggle button in the live 2D video playing screen$")
public void user_taps_toggle_button() throws Exception {
MobileElement allow = (MobileElement) driver.findElement(By.id("com.android.packageinstaller:id/permission_allow_button"));
allow.click();
List<MobileElement> list = driver.findElements(By.id("android:id/text1"));
for(MobileElement ele :list) {
String text = ele.getText();
if(text.equals("Live")){
ele.click();
break;
}
}
MobileElement panoramicButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/rl_select_2d"));
panoramicButton.click();
MobileElement Screen= (MobileElement) driver.findElement(By.className("android.view.View"));
TouchAction ta = new TouchAction(driver);
ta.tap(Screen, 531, 357).perform();
MobileElement toggleButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/fab_player_switch_mode"));
toggleButton.click();
}
#When("^Taps back button in the transition screen$")
public void taps_back_button() throws InterruptedException {
Thread.sleep(1000);
MobileElement backButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/iv_cardboard_back"));
backButton.click();
}
#Then("^The transition screen should dismiss and user should be navigated back to 2d live video playing screen$")
public void dismiss_transition_screen() {
try{
MobileElement cameraAngleSelectionButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/rl_player_switch_camera_parent"));
if(cameraAngleSelectionButton != null) {
System.out.println("The transition screen is dismissed and user is navigated back to 2d live video playing screen");
}
}catch(Exception e){
System.out.println("The transition screen is not dismissed and user is not navigated back to 2d live video playing screen");
}
//driver.quit();
}
}
This error gets cleared and the script works fine when I close the emulator and open it again. Can anybody help me in this?
Hey please then kill all simulator programmatically after executing testcase. Below code might help you.
/**
* Stop Simulator
*/
public void stopSimulator() {
try {
Runtime.getRuntime().exec("killall \"iOS Simulator\"");
} catch (IOException e) {
//e.printStackTrace();
}
try {
Runtime.getRuntime().exec("killall Simulator");
} catch (IOException e) {
//e.printStackTrace();
}
}
If you are openning a specific simulator you can specify this in above code.
For android simulator please use
Runtime.getRuntime().exec("adb emu kill");
Summary: In the url below, please click the reply button. Then, a popup will appear and hide the reply button. When you click a blank area or on the paragraph containing 'post id:', the popup disappears and you can see the reply button again. I want to do these things using the code below.
Problem: None of the last 3 method calls in main make the popup disappear. What is wrong with my code and how do I make it work ?
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class Temp {
private static final WebDriver browser = new ChromeDriver();
private static String reply_btn_xpath = "//button[contains(concat(\" \", normalize-space(#class), \" \"), \" "
+ "reply_button" + " \")]";
private static By reply_btn_loc = By.xpath(reply_btn_xpath);
private static String url = "https://sfbay.craigslist.org/pen/apa/5764613878.html";
public static void main(String[] args) {
browser.get(url);
WebElement reply = browser.findElement(reply_btn_loc);
reply.click();
WebElement post_id = browser.findElement(By.xpath("//p[contains(., 'post id:')]"));
post_id.click();
click_with_actions(post_id);
click_with_js(post_id);
}
public static void click_with_actions(WebElement element) {
Actions actions = new Actions(browser);
actions.moveToElement(element).click().perform();
}
public static void click_with_js(WebElement element) {
((JavascriptExecutor) browser).executeScript("arguments[0].click();", element);
}
}
Apparently, it is advised not to use java.awt.Robot in VMs or CI to do the clicks because they don't have real keyboards. Java awt.Robot not working inside a virtual machine?
I tried Robot also in the above code and it did not work.
public static void click_with_robot(WebElement element, int x, int y) {
Robot bot = null;
try {
bot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
Point location = element.getLocation();
int x_loc = location.getX() + x;
int y_loc = location.getY() + y;
bot.mouseMove(x_loc, y_loc);
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
}
I need to capture the full page of IE browser. I am using web driver. Pls help me.
below code is used to capture the present window only.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
You can change the browser to full screen before taking the screenshot. This is the code:
private void changeToFullScreen() {
try {
Robot r;
r = new Robot();
r.keyPress(java.awt.event.KeyEvent.VK_F11);
r.keyRelease(java.awt.event.KeyEvent.VK_F11);
driver.sleep(2);
} catch (AWTException e) {
log.error("It was not possible to maximize", e)
driver.manage().window().maximize();
}
}
If you don't want to change the screen size, you can obtain the browser height and take screenShots while you scroll down until the bottom (can be done with Robot):
int numberOfScrolls = pageHeight / browserHeight;
for(int i = 0 ; i < numberOfScrolls ; i++){
takeScreenshot();
scrollDown(browserHeight);
}
concatenateScreenshots();
import java.io.File;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class TakeScreenshotWithScroll {
static WebDriver driver;
public static void main(String args[]) throws Exception{
String key = "webdriver.gecko.driver";
String value = "driver/geckodriver.exe";
driver = new FirefoxDriver();
System.setProperty(key, value);
driver.get("ENTER THE URL HERE");
Thread.sleep(2000);
Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(fpScreenshot.getImage(),"PNG",new File("D:///FullPageScreenshot.png"));
}
}
Here is the download link of aShot Jar file
I have a Java JApplet that functions perfectly when eclipse runs it but dissapoints in a browser.
The applet is working fine in the browser up to the point at which the only JButton is pressed. At which point, something should happen, but, in the browser, nothing happens at all apart from the button shows it has been pressed. This doesn't happen when eclipse runs it.
Here is the code:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JTextArea;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
public class OverviewGenerator extends JApplet {
int state = 0;
JTextArea label = new JTextArea();
JButton button = new JButton();
String pluginYML;
YamlConfiguration yml = new YamlConfiguration();
String page;
public ActionListener buttonListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(state == 0) {
try {
pluginYML = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (HeadlessException e1) {
e1.printStackTrace();
} catch (UnsupportedFlavorException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
yml.loadFromString(pluginYML);
} catch (InvalidConfigurationException e1) {
e1.printStackTrace();
}
state = 1;
}else {
generatePage();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Clipboard clipboard = toolkit.getSystemClipboard();
StringSelection strSel = new StringSelection(page);
clipboard.setContents(strSel, null);
state = 0;
}
refreshComponents();
}
};
/**
*
*/
private static final long serialVersionUID = 3470279389867972761L;
public void init() {
makeGui();
}
private void makeGui() {
label.setWrapStyleWord(true);
label.setLineWrap(true);
label.setBackground(Color.CYAN);
label.setEditable(false);
GridLayout layout = new GridLayout();
layout.setRows(2);
layout.setColumns(1);
getContentPane().setLayout(layout);
refreshComponents();
getContentPane().add(label);
getContentPane().add(button);
button.addActionListener(buttonListener);
}
private void refreshComponents() {
if(state==0) {
label.setText("Copy your plugin.yml into the clipboard then press done!");
button.setText("Done");
}else if(state == 1) {
label.setText("Now press the button to copy your template BukkitDev overview into your clipboard!");
button.setText("Copy");
}
}
private void generatePage() {
page = "";
page += "== "+yml.getString("name")+" ==\n";
if(yml.contains("description")) {
page += "\n//"+yml.getString("description")+"//\n\n\n";
}
if(yml.contains("commands")) {
page += "== Commands ==\n";
for(String command : yml.getConfigurationSection("commands").getKeys(false)) {
page += "\n=== "+command+" ===\n\n";
if(yml.contains("commands."+command+".description")) {
page += "//"+yml.getString("commands."+command+".description")+"//\n";
}
if(yml.contains("commands."+command+".usage")) {
page += "Usage: "+yml.getString("commands."+command+".usage")+"\n";
}
}
page += "\n";
}
if(yml.contains("permissions")) {
YamlConfiguration editedYml = new YamlConfiguration();
try {
editedYml.loadFromString(pluginYML.replace(".", "≠"));
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
ConfigurationSection permissions = editedYml.getConfigurationSection("permissions");
page += "== Permissions ==\n";
for(String permission : permissions.getKeys(false)) {
page += "\n=== "+permission.replace('≠', '.')+" ===\n\n";
if(editedYml.contains("permissions."+permission+".description")) {
page += "//"+editedYml.getString("permissions."+permission+".description").replace('≠', '.')+"//\n";
}
}
page += "\n\n\n";
}
page += "//Got any suggestions?//";
}
}
The code above is slightly outdated, I have added in the 'invoke later' code now! I am having trouble showing the Java console but I believe the error may be when the clipboard is accessed.
For security reasons, there are two ways that an applet can access the clip-board.
The applet is digitally signed by the developer, and trusted by the end user.
The applet uses the services of the JNLP API to access the clipboard. That is available in more recent JREs, Sun's 1.6.0_10+, for example.
There is potentially a 3rd way to get data to the applet that involves
having the user paste directly into an HTML form field
then use JS to transfer the data to the applet.
That could be done in a sand-boxed applet, and before the JRE that supports the JNLP API services. OTOH that would mean more clicks for the user, and more setting up.
//Got any suggestions?//
Beyond 'ask a more specific question' I might also suggest:
Enable the Java Console. That information is vital for debugging applets.
Read Copy in sand-boxed app. in 1.6.0_24+ for more details of the problem with clipboard access in applets, and strategies to copy data out of an applet using JS and other techniques.
Oracle released Java 6 Update 24 in February 2011 to remedy 21 vulnerabilities. As part of this security release, the ability to copy & paste from a computer's clipboard into a Java applet has been disabled.
To fix this issue there are 2 solutions:
Create a digital signature for the applet.
Work around: If you do not want to work with the digital signature, add to your java.policy file the following line: permission java.awt.AWTPermission "accessClipboard"
If you want to see an example of Java Applet working with a signed certificate you can looke here (the applet accepts paste action from clipboard which is not allowed to unsigned applets) : http://sqlinform.com/free_online_sw.html
I'm trying to create a splash screen using LWUIT. I want a form to load and display text and an imagefor 5 seconds then continue to the next form. I have a code but fails to show the image. The class and the image are stored together int he same package. Instead, it shows an error.
java.io.IOException
What could be the problem? This is the code
package tungPackage;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import javax.microedition.midlet.MIDlet;
public class photoMidlet extends MIDlet {
public void startApp() {
Display.init(this);
try {
Form splashscreen = new Form();
// Label splashText = new Label("Baldy");
Image image = Image.createImage("/splash.png");
Label pictureLabel = new Label(image);
splashscreen.addComponent(pictureLabel);
splashscreen.show();
} catch (Exception ex) {
Form x = new Form("ERROR");
String y = ex.toString();
Label g = new Label(y);
x.addComponent(g);
x.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Open your JAR file using a ZIP utility (e.g. 7-zip) and look in the root of the file. If splash.png isn't in the root of the jar that's your problem!
Place splash.png so it is in the root of the jar.