package com.testng.learn;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidKeyCode;
public class First {
AndroidDriver driver;<br/>
DesiredCapabilities caps;<br/>
#BeforeTest<br/>
public void DC() {<br/>
try {<br/>
// Set the Desired Capabilities<br/>
caps = new DesiredCapabilities();<br/>
caps.setCapability("deviceName", "My Phone");<br/>
caps.setCapability("udid", "LGM70021d764e8"); // Give Device ID of your mobile phone<br/>
caps.setCapability("platformName", "Android");<br/>
caps.setCapability("platformVersion", "7.1.1");<br/>
caps.setCapability("appPackage", "com.android.contacts");<br/>
caps.setCapability("appActivity", "com.android.contacts.activities.DialtactsActivity");<br/>
caps.setCapability("noReset", "true");<br/>
driver = new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), caps);<br/>
} catch (MalformedURLException e) {<br/>
// TODO Auto-generated catch block<br/>
e.printStackTrace();<br/>
}
}
#DataProvider()<br/>
public void scroll(String text) {<br/>
try {<br/>
System.out.println(text);<br/>
driver.findElement(MobileBy.AndroidUIAutomator(
"new UiScrollable(new UiSelector()).scrollIntoView(" + "new UiSelector().text(\"" + text + "\"));"))
.click();<br/>
Thread.sleep(5000);<br/>
} catch (InterruptedException e) {<br/>
// TODO Auto-generated catch block<br/>
e.printStackTrace();<br/>
}<br/>
}<br/>
#Test(priority = 0)<br/>
public void print() {<br/>
try {<br/>
String text = "Karthik";<br/>
Thread.sleep(2000);<br/>
driver.findElementByAccessibilityId("Contacts Tab 3 of 4").click();<br/>
Thread.sleep(1000);<br/>
First f1 = new First();<br/>
f1.scroll(text);<br/>
Thread.sleep(1000);<br/>
driver.pressKeyCode(AndroidKeyCode.BACK);<br/>
Thread.sleep(2000);<br/>
driver.pressKeyCode(AndroidKeyCode.HOME);<br/>
} catch (InterruptedException e) {<br/>
// TODO Auto-generated catch block<br/>
e.printStackTrace();<br/>
}<br/>
}<br/>
}
As according to your code, You have define #DataProvider() method incorrectly. You should need to refer articles on TestNG Dataprovider.
Related
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class clientWindow {
static Text chatWindow;
public static void sendMessage(Socket socket, String message) throws IOException {
PrintWriter pr = new PrintWriter(socket.getOutputStream());
pr.println("Client: " + message);
pr.flush();
}
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("10.0.1.8", 4500);
Display display = new Display();
Shell clientWindow = new Shell(display);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
clientWindow.setLayout(layout);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
GridData data1 = new GridData(GridData.FILL_BOTH);
chatWindow = new Text(clientWindow, SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY);
chatWindow.setLayoutData(data1);
Text messageBox = new Text(clientWindow, SWT.SINGLE);
messageBox.setLayoutData(data);
Button send = new Button(clientWindow, 0);
send.setText("Send");
send.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
try {
sendMessage(s, messageBox.getText());
messageBox.setText("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void widgetDefaultSelected(SelectionEvent arg0) {
// TODO Auto-generated method stub
}
});
clientWindow.open();
while (!clientWindow.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
This is a small messaging app that I've finished. Everything in here works fine in Eclipse. When I try to run it in the Terminal, however, I get this.
Exception in thread "main" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:4711)
at org.eclipse.swt.SWT.error(SWT.java:4626)
at org.eclipse.swt.SWT.error(SWT.java:4597)
at org.eclipse.swt.widgets.Display.error(Display.java:1112)
at org.eclipse.swt.widgets.Display.createDisplay(Display.java:853)
at org.eclipse.swt.widgets.Display.create(Display.java:837)
at org.eclipse.swt.graphics.Device.<init>(Device.java:132)
at org.eclipse.swt.widgets.Display.<init>(Display.java:736)
at org.eclipse.swt.widgets.Display.<init>(Display.java:727)
at clientWindow.main(clientWindow.java:28)
I'm pretty sure this error happens when a trying to access the Display from something that isn't in "main", which isn't what I'm trying to do. So why is it giving me this error?
Judging by the line numbers in the Display code you are running this on macOS.
On macOS you must specify the -XstartOnFirstThread option when you run your code with the java command in Terminal.
The program works in Eclipse because Eclipse sets this up for you automatically in the Run Configuration.
I want to scroll through the menu of this and other related application and also want to click on them. So kindly tell a method that can work on all applications in Appium Java
this is my code by far that clicks on menu button of all applications but does not scroll or click :
package project;
import java.util.Scanner;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.touch.TouchActions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.PressesKeyCode;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidKeyCode;
public class firstpro {
static AppiumDriver<MobileElement> driver = null;
public static void main(String[] args) {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("deviceName", "Samsung Galaxy");
caps.setCapability("udid", "HFTUN678");
caps.setCapability("platformName", "Android");
caps.setCapability("platformVersion", "7.0");
caps.setCapability("appPackage", "com.olx.pk");
caps.setCapability("appActivity",
"pl.tablica2.activities.ProxyActivity");
try {
driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps);
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
}
menus();
}
public static void menus() {
WebDriverWait wait = new WebDriverWait(driver, 10000);
WebElement Element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("android.view.ViewGroup")));
driver.findElement(By.className("android.widget.ImageButton")).click();
}
}
You can try this code, I'm not sure how accurate it is since I still don't know the full node tree structures but it should give you a good idea of some approaches you can take:
public static void menus() {
List<WebElement> scrollViews = driver.findElements(By.className("android.widget.ScrollView"));
Iterator<WebElement> it = scrollViews.iterator();
while(it.hasNext()) {
WebElement scrollView = it.next();
// make sure this scroll view has the child element "Home"
List<WebElement> homeElements = scrollView.findElements(By.xpath("*[text() = 'Home' or text() = 'home']"));
if(homeElements.isEmpty()) {
// filter out scroll views that don't have a child with the text "Home"
it.remove();
} else if (homeElements.size() > 1) {
// this scroll view has multiple children with the text "Home"
}
}
if(scrollViews.isEmpty()) {
// TODO error, couldn't find any scroll view containing a child with the text "Home"
} else if (scrollViews.size() > 1) {
// TODO error, there are multiple scroll views containing children with the text "Home"
}
// the only scroll view that has a child with text "Home"
// likely the main menu scroll view
WebElement targetMenuScrollView = scrollViews.get(0);
// get all the ImageButtons in the menu
List<WebElement> menuButtons = targetMenuScrollView
.findElements(By.className("android.widget.ImageButton"));
// click all the buttons
for (WebElement button : menuButtons) {
button.click();
}
}
I`m trying to put some music or a short clip of a sound to my project. I try some helps from here. It kinda work, but I could not hear anything. It just wrote that its playing.
I found a lot of examples, but nothing is working for me. Maybe you can help me with that AudioStream, AudioPlayer. Many people are using it. How can I use it in my Java Eclipse 4.4.0?
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import sun.audio.*;
public class zaciatky {
public static void main(String[] args) throws LineUnavailableException {
// TODO Auto-generated method stub
try {
AudioInputStream audoAudioInputStream=AudioSystem.getAudioInputStream(new File("D:\\Betka\\Dokumenty\\INF\\JAVA\\Saxik\\Music\\saxik.wav"));
Clip songik=AudioSystem.getClip();
songik.open(audoAudioInputStream);
songik.start();
System.out.println("Song is playing...");
System.out.println(songik.getFormat());
if(songik.isActive()) System.out.println("is active");
songik.stop();
if(songik.isActive()) System.out.println("is active");
else System.out.println("not active");
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
System.out.println("Error occures with playing the sound.");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error occures with playing the sound.");
e.printStackTrace();
}
}
}
I'd like to type: "/ammo" when I type ALT+A.
The program runs but it seems like to stop right after the running:
I press alt+A or A and the code is not doing anything at all.
package jnativehook01;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class Example implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals("A")) {
try {
GlobalScreen.unregisterNativeHook();
Robot bot;
try {
bot = new Robot();
String text = "/ammo";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
//type: /ammo
bot.keyPress(KeyEvent.VK_T);
bot.keyRelease(KeyEvent.VK_T);
} catch (AWTException e1) {
}
} catch (NativeHookException e1) {
}
}
}
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}
public static void main(String[] args) {
new Example();
}
}
Ok, now it's working:
package jnativehook01;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import java.util.logging.*;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
public class Example implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals("A")) {
Robot bot;
try {
String text = "/ammo";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
bot = new Robot();
for (int i = 0; i < 10; i++) {
//t
bot.keyPress(KeyEvent.VK_T);
bot.delay(100);
bot.keyRelease(KeyEvent.VK_T);
bot.delay(500);
bot.keyPress(KeyEvent.VK_CONTROL);
bot.keyPress(KeyEvent.VK_V);
bot.keyRelease(KeyEvent.VK_V);
bot.keyRelease(KeyEvent.VK_CONTROL);
bot.delay(500);
//Enter
bot.keyPress(KeyEvent.VK_ENTER);
bot.keyRelease(KeyEvent.VK_ENTER);
bot.delay(1000);
bot.keyPress(KeyEvent.VK_ENTER);
bot.keyRelease(KeyEvent.VK_ENTER);
bot.delay(400);
}
} catch (AWTException e1) {
}
}
}
public void nativeKeyReleased(NativeKeyEvent e) {
}
public void nativeKeyTyped(NativeKeyEvent e) {
}
public static void main(String[] args) {
Example ex = new Example();
try {
GlobalScreen.registerNativeHook();
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.OFF);
} catch (NativeHookException eb) {
System.out.println(eb.getMessage());
}
GlobalScreen.addNativeKeyListener(ex);
}
}
There are still a few problems with your code.
if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals("A")) {
This is not the correct way to check for the A key. This will check to see if AWT produces the ascii 'A' for that key. These values could be overridden by the JVM at runtime. You should check for the NativeKeyEvent.VK_A constant. You also fail to check for the ALT flag on that key event. Something like the following is more of what you are looking for.
if (e.getKeyCode() == NativeKeyEvent.VC_A && e.getModifiers() & NativeInputEvent.ALT_MASK) {
A note on thread safety. You are relying on AWT inside of the key callback, however, this library does not use AWT to dispatch events by default. You need to take a look at the Thread Safety section of the wiki for Thread Safe examples.
You may choose to replace the Robots class with GlobalScreen.postNativeEvent(...) for convenience, to omit Swing/AWT, but it is not required.
A note on blocking inside of the event listener callback. If you block inside this function, via sleep or other long running process, you may cause a delay in key event delivery by the OS or worse, library removal by some operating systems. This removal is outside the control of the library and controlled by the OS.
I've recently been experimenting with the user of JTextPanes for an upcoming project I'll be working on, there have been various posts online detailing how to go about counting the number of lines within the text pane however the solutions I found all seem to fail when inserting Icons or Components into the text pane's document.
The solution I found that worked for plain text was this one (with the solution implemented of course): BadLocationException when using Utilities.getRowStart On hit of Enter key
However once I try to insert a Component (JLabel) or a plain Icon for that matter, the getRowStart() method from Utilities throws a null pointer exception. What I find unusual about this is the Java Doc states that "...This is represented in the associated document as an attribute of one character of content. ", so I assumed it would treat it as any other character but it seems this is not the case.
I've included a code example to replicate the problem if anyone would like to try it. I have a feeling that it just simply isn't possible, which would be a shame.
import java.awt.Dimension;
import java.awt.Image;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Utilities;
public class Test{
private JFrame frame;
private JTextPane textPane;
private Image img;
private URL imgURL;
public Test(){
frame = new JFrame();
frame.setSize(new Dimension(500,300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textPane = new JTextPane();
try {
imgURL = new URL("http://www.freeiconspng.com/uploads/floppy-save-icon--23.png");
img = ImageIO.read(imgURL);
JLabel label = new JLabel(new ImageIcon(img.getScaledInstance(10, 10, Image.SCALE_SMOOTH)));
textPane.insertComponent(label);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frame.getContentPane().add(textPane);
frame.setVisible(true);
}
public JTextPane getTextPane(){
return this.textPane;
}
public int getLineCount(){
int totalCharacters = textPane.getDocument().getLength();
int lineCount = (totalCharacters == 0) ? 1 : 0;
try {
int offset = totalCharacters;
while (offset > 0) {
offset = Utilities.getRowStart(textPane, offset) - 1;
lineCount++;
}
} catch (BadLocationException e) {
e.printStackTrace();
}
return lineCount;
}
public static void main(String[] args){
Test t = new Test();
t.getLineCount();
}
}
The problem was solved after the following comment:
It doesn't throw any exception for me once I wrap the content inside
your main method inside a EventQueue.invokeLater() call. I.e.:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Test t = new Test();
t.getLineCount();
}
});