I have a app in which i need to scan the QR code. Taking the picture from the app is not feasible as i need to run the app in multiple devices at once and it require human presence. How can i provide the QR code image/data to the app without scanning? Is there any way possible to simulate taking of picture and give store image as input to app?
If you have scanned test "QR Code image" then you can push it to the device from where app can read it.
You can ask dev team about the path from where app is reading the scanned image, and at same path you can push the test image.
Below is the code for how to push image file to device and other methods to push/pull different file formats
import java.awt.image.BufferedImage;
import io.appium.java_client.android.AndroidDriver;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
#Test
public class pushFileTest {
public static AndroidDriver<WebElement> _driver;
#BeforeClass
public void setUpAppium() throws InterruptedException, IOException {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("platformVersion","5.1");
cap.setCapability("platformName","Android");
cap.setCapability("deviceName","ZX12222D");
cap.setCapability("appPackage","io.appium.android.apis");
cap.setCapability("appActivity","ApiDemos");
//System.out.println("Before calling appium");
_driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4725/wd/hub"), cap);
//System.out.println("After calling appium");
}
#Test
public void pullImageFileFromMobileSDCardTest() throws IOException {
byte[] returnData = _driver.pullFile("/storage/sdcard1/IMG_20140828_072840.jpg");
//System.out.println("Base 64 Converted String received from mobile :: " + returnData);
BufferedImage image=ImageIO.read(new ByteArrayInputStream(returnData));
ImageIO.write(image, "jpg", new File("C:\\eclipse","snap.jpg"));
}
/* Test Case to pull log file from mobile device*/
#Test
public void pullTextFileFromMobileSDCardTest() throws IOException {
byte[] returnData = _driver.pullFile("/storage/sdcard1/mili_log.txt");
//System.out.println(" Printing Text of File received from mobile :: " + new String(Base64.decodeBase64(returnData)));
File fs = new File("C:\\eclipse\\MobileFile.txt");
FileOutputStream fos = new FileOutputStream(fs);
fos.write(returnData);
fos.flush();
fos.close();
}
#Test
public void pushImageFileToMobileTest() throws IOException {
File fi = new File("C:\\eclipse\\img1.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath());
_driver.pushFile("/storage/sdcard1", fileContent);
}
#Test
public void pushTextFileToMobileTest() throws IOException {
File fi = new File("C:\\eclipse\\MobileFile.txt");
byte[] data = Files.readAllBytes(fi.toPath());
System.out.println("Base 64 Converted String sent to mobile :: " + data);
_driver.pushFile("/storage/sdcard1/appium.txt",data);
}
public void pullVideoFileFromMobileSDCardTest() throws IOException {
byte[] returnData = _driver.pullFile("/storage/sdcard1/VideoIconfile.mp4");
//System.out.println(" Printing Text of File received from mobile :: " + new String(Base64.decodeBase64(returnData)));
//File fs = new File("C:\\eclipse\\video.mp4");
FileOutputStream fos = new FileOutputStream("C:\\eclipse\\video.mp4");
fos.write(returnData);
fos.flush();
fos.close();
}
#AfterTest(alwaysRun= true)
public void tearDown(){
if (_driver!= null )
_driver.quit();
System.out.println("tearDown() :: driver.quit() executed");
}
}
Related
I have a program that connects to a user defined URL from a TextField and scrapes the images on that web page. The user defined URL is gotten from the textfield via .getText() and assigned to a String. The String is then used to connect to the Web page with JSoup and puts the webpage into a document.
String address = labelforAddress.getText();
try {
document = Jsoup.connect(address).get();
}catch(IOException ex){
ex.printStackTrace();
}
I've tried differently formatted URLS: "https://www.", "www.", "https://" but everything I use throws the malformed URL error.
Someone please show me how to get the text from the TextField the correct way.
Below is the entire code.
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main extends Application {
Document document;
LinkedList<String> imageURLList = new LinkedList<String>();
ArrayList<File> fileList = new ArrayList<File>();
int fileCount = 1;
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Webpage Photo Scraper");
GridPane gp = new GridPane();
Label labelforAddress = new Label("URL");
GridPane.setConstraints(labelforAddress, 0,0);
TextField URLAddress = new TextField();
GridPane.setConstraints(URLAddress, 1,0);
Button scrape = new Button("Scrape for Photos");
GridPane.setConstraints(scrape, 0,1);
scrape.setOnAction(event->{
String address = labelforAddress.getText();
try {
document = Jsoup.connect(address).get();
}catch(IOException ex){
ex.printStackTrace();
}
Elements imgTags = document.getElementsByAttributeValueContaining("src", "/CharacterImages");
for(Element imgTag: imgTags){
imageURLList.add(imgTag.absUrl("src"));
}
for(String url: imageURLList){
File file = new File("C:\\Users\\Andrei\\Documents\\file" + fileCount + ".txt");
downloadFromURL(url, file);
fileList.add(file);
fileCount++;
}
});
Button exportToZipFile = new Button("Export to Zip File");
GridPane.setConstraints(exportToZipFile, 0,2);
exportToZipFile.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter exfilt = new FileChooser.ExtensionFilter("Zip Files", ".zip");
fileChooser.getExtensionFilters().add(exfilt);
try{
FileOutputStream fos = new FileOutputStream(fileChooser.showSaveDialog(primaryStage));
ZipOutputStream zipOut = new ZipOutputStream(fos);
for(int count = 0; count<=fileList.size()-1; count++){
File fileToZip = new File(String.valueOf(fileList.get(count)));
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
}catch(IOException e1){
e1.printStackTrace();
}
});
primaryStage.setScene(new Scene(gp, 300, 275));
primaryStage.show();
gp.getChildren().addAll(exportToZipFile, labelforAddress, scrape, URLAddress);
}
public static void downloadFromURL(String url, File file){
try {
URL Url = new URL(url);
BufferedInputStream bis = new BufferedInputStream(Url.openStream());
FileOutputStream fis = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int count = 0;
while((count = bis.read(buffer, 0,1024)) !=-1){
fis.write(buffer, 0, count);
}
fis.close();
bis.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Your text field containing the value entered by user is stored in URLAddress object but you always try to get the url from labelforAddress object which is a label always containing "URL" text.
So the solution is to use:
String address = URLAddress.getText();
If you read carefully error message it would help you to find the cause, because it always displays the value it considers wrong. In this case I see:
Caused by: java.net.MalformedURLException: no protocol: URL
and it shows the unrecognized address is: URL.
If you encounter this kind of error next time try:
debugging the aplication in runtime to see values of each variable
logging variable values in the console to see if variables contain values you expect
In order to test the duplication in registering,I need to close and relaunch the iOS application.Can any one provide the best and simple scripts to close an application and relaunch the same in iOS using Appium and JAVA?
You can achieve the following way :
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class SampleTest {
AppiumDriver<?> appiumDriver;
final String URL_STRING = "http://127.0.0.1:4723/wd/hub";
URL url = new URL(URL_STRING);
public SampleTest() throws MalformedURLException {
}
#BeforeTest
public void beforeTest() {
File appDir = new File("path to ipa file");
File app = new File(appDir, "app.ipa");
DesiredCapabilities iOSCapabilities = new DesiredCapabilities();
iOSCapabilities.setCapability(MobileCapabilityType.PLATFORM, "iOS");
iOSCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");
iOSCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone6s");
iOSCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "11.2.1");
iOSCapabilities.setCapability(MobileCapabilityType.UDID, "udid");
iOSCapabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
appiumDriver = new IOSDriver(url, iOSCapabilities);
}
#Test
public void test() {
//perform some test
}
#AfterTest
public void afterTest() {
// following command will close and restart the app
appiumDriver.resetApp();
}
}
You may want to check this for more details.
use the driver driver.resetApp(), like this
try{
LOG.debug("reset app");
driver.resetApp();
} catch (WebDriverException e){
LOG.error("ERROR on reset app, e: ",e);
}
Appium allows you to start any pre-installed app on the device, so you can use closeApp first and then launchApp with your app bundle id:
// closing app
driver.closeApp();
// launch app again
HashMap<String, Object> args = new HashMap<>();
args.put("bundleId", APP_BUNDLE_ID);
driver.executeScript("mobile: launchApp", args);
I am successfully retrieve the data of response using xpath expression /abcde/response from the xml ,
<abcde>
<response>000</response>
</abcde>
But couldnt retrieve the data of response from the same xml but with some additional data
<abcde version="8.1" xmlns="http://www.litle.com/schema"
response="0" message="Valid Format">
<response>000</response>
</abcde>
What am i doing wrong ?
package stackoverflow;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.xpath.DefaultXPath;
import org.jaxen.VariableContext;
public class MakejdomWork {
public static void main(String[] args) {
new MakejdomWork().run();
}
public void run() {
ByteArrayInputStream bis = new ByteArrayInputStream("<abcde version=\"8.1\" xmlns=\"http://www.litle.com/schema\" response=\"0\" message=\"Valid Format\"> <response>000</response></abcde>".getBytes());
//ByteArrayInputStream bis = new ByteArrayInputStream("<abcde><response>000</response></abcde>".getBytes());
Map nsPrefixes = new HashMap();
nsPrefixes.put( "x", "http://www.litle.com/schema" );
DocumentFactory factory = new DocumentFactory();
factory.setXPathNamespaceURIs( nsPrefixes );
SAXReader reader = new SAXReader();
reader.setDocumentFactory( factory );
Document doc;
try {
doc = reader.read( bis );
Object value = doc.valueOf("/abcde/x:response");
System.out.println(value);
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
Short answer: you need to use namespace prefixes if your parser is namespace aware (which dom4j is)
I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save.
So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR :
LAVF_header: av_open_input_stream() failed
while playing with the mplayer.
Here is the sample Java Code i m using in which i m reading audio data from the audio file:
package networksocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JApplet;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.Properties;
import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager;
import sun.awt.HorizBagLayout;
import sun.awt.VerticalBagLayout;
import sun.misc.BASE64Encoder;
/**
*
* #author mukand
*/
public class Urlconnection extends JApplet implements ActionListener
{
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public BufferedInputStream in;
public BufferedOutputStream out;
public String line;
public FileOutputStream file;
public int bytesread;
public int toread=1024;
byte b[]= new byte[toread];
public String f="FINISH";
public String match;
public File fileopen;
public JTextArea jTextArea;
public Button refreshButton;
public HttpURLConnection urlConn;
public URL url;
OutputStreamWriter wr;
BufferedReader rd;
#Override
public void init() {
// TODO start asynchronous download of heavy resources
//textField= new TextField("START");
//getContentPane().add(textField);
JPanel p = new JPanel();
jTextArea= new JTextArea(1500,1500);
p.setLayout(new GridLayout(1,1, 1,1));
p.add(new JLabel("Server Details"));
p.add(jTextArea);
Container content = getContentPane();
content.setLayout(new GridBagLayout()); // Used to center the panel
content.add(p);
jTextArea.setLineWrap(true);
refreshButton = new java.awt.Button("Refresh");
refreshButton.reshape(287,49,71,23);
refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12));
refreshButton.addActionListener(this);
add(refreshButton);
Properties properties = System.getProperties();
properties.put("http.proxyHost", "netmon.iitb.ac.in");
properties.put("http.proxyPort", "80");
}
#Override
public void actionPerformed(ActionEvent e)
{
try
{
url = new URL("http://localhost:3000/audio/audiorecieve");
urlConn = (HttpURLConnection)url.openConnection();
//String login = "mukandagarwal:rammstein$";
//String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes());
//urlConn.setRequestProperty("Proxy-Authorization",login);
urlConn.setRequestMethod("POST");
// urlConn.setRequestProperty("Content-Type",
//"application/octet-stream");
//urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Length", "" +
// Integer.toString(urlParameters.getBytes().length));
urlConn.setRequestProperty("Content-Language", "UTF-8");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
byte bread[]=new byte[2048];
int iread;
char c;
String data=URLEncoder.encode("key1", "UTF-8")+ "=";
//String data="key1=";
FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3");
while((iread=fileread.read(bread))!=-1)
{
//data+=(new String());
/*for(int i=0;i<iread;i++)
{
//c=(char)bread[i];
System.out.println(bread[i]);
}*/
data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));//
// data+=new String(bread,iread);
}
//urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length));
System.out.println(data);
//data+=URLEncoder.encode("mukand", "UTF-8");
//data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
//data="key1=";
wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream();
//if((iread=fileread.read(bread))!=-1)
// wr.write(bread,0,iread);
wr.write(data);
wr.flush();
fileread.close();
jTextArea.append("Send");
// Get the response
rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = rd.readLine()) != null) {
jTextArea.append(line);
}
wr.close();
rd.close();
//jTextArea.append("click");
}
catch (MalformedURLException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void start()
{
}
#Override
public void stop()
{
}
#Override
public void destroy()
{
}
// TODO overwrite start(), stop() and destroy() methods
}
Here is the Rails controller function for recieving:
def audiorecieve
puts "///////////////////////////////////////******RECIEVED*******////"
puts params[:key1]#+" "+params[:key2]
data=params[:key1]
#request.env('RAW_POST_DATA')
file=File.new("audiodata.ogg", 'w')
file.write(data)
file.flush
file.close
puts "////**************DONE***********//////////////////////"
end
Please reply quickly
Base64 encode the data. Send it as a string, receive it on the Rails side and decode it back to the original format.
I am trying to validate generated WSDL to be correct. I have tried WS-i test tool downloaded from http://www.ws-i.org/ but it's test tool require all input to go through a config xml and the output is again an output xml file. Is there other easier way of validating a WSDL?
The Woden library/jar provides adequate functionality to be able to do this. If your wsdl isn't valid, the last statement, reader.readWSDL(...), will throw an exception.
import static junit.framework.Assert.fail;
import java.net.URISyntaxException;
import org.apache.woden.WSDLException;
import org.apache.woden.WSDLFactory;
import org.apache.woden.WSDLReader;
import org.apache.woden.wsdl20.Description;
import org.junit.Test;
public class WSDLValidationTest {
String wsdlFileName = "/MyService.wsdl";
#Test
public void validateWSDL2() throws WSDLException {
String wsdlUri = null;
try {
wsdlUri = this.getClass().getResource(wsdlFileName).toURI().toString();
}
catch( URISyntaxException urise) {
urise.printStackTrace();
fail( "Unable to retrieve wsdl: " + urise.getMessage());
}
WSDLFactory factory = WSDLFactory.newInstance("org.apache.woden.internal.OMWSDLFactory");
WSDLReader reader = factory.newWSDLReader();
reader.setFeature(WSDLReader.FEATURE_VALIDATION, true);
reader.readWSDL(wsdlUri);
}
}
And should you need a unit test for WSDL 1.1, see the following:
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.fail;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.stream.XMLStreamException;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.sun.xml.ws.api.model.wsdl.WSDLModel;
import com.sun.xml.ws.api.server.SDDocumentSource;
import com.sun.xml.ws.api.wsdl.parser.WSDLParserExtension;
import com.sun.xml.ws.api.wsdl.parser.XMLEntityResolver;
public class WSDLValidationTest {
String wsdlFileName = "/MyService.wsdl";
String wsdlUri = null;
URL wsdlUrl = null;
#Before
public void before()
{
try {
wsdlUrl = this.getClass().getResource(wsdlFileName);
wsdlUri = wsdlUrl.toURI().toString();
}
catch( URISyntaxException urise) {
urise.printStackTrace();
fail( "Unable to retrieve wsdl: " + urise.getMessage());
}
}
#Test
public void parseAndValidateWSDL1_1WithWSDL4J() throws WSDLException
{
WSDLReader wsdlReader = null;
try {
WSDLFactory factory = WSDLFactory.newInstance();
wsdlReader = factory.newWSDLReader();
}
catch( WSDLException wsdle) {
wsdle.printStackTrace();
fail( "Unable to instantiate wsdl reader: " + wsdle.getMessage());
}
// Read WSDL service interface document
Definition def = wsdlReader.readWSDL(null, wsdlUri);
assertNotNull(def);
}
#Test
public void parseAndValidateWSDL1_1WithJaxWS() throws IOException, XMLStreamException, SAXException
{
final SDDocumentSource doc = SDDocumentSource.create(wsdlUrl);
final XMLEntityResolver.Parser parser = new XMLEntityResolver.Parser(doc);
WSDLModel model = WSDLModel.WSDLParser.parse( parser, null, false, new WSDLParserExtension[] {} );
assertNotNull(model);
}
}