Drag and drop testing in selenium on html5 (Using java) - javascript

This is my first question ever so please go light on me. I am trying to test the drag and drop feature on HTML5 using selenium and java as my main language. However I am fully aware that it is not supported by selenium webdriver itself but there is a workaround on the stackoverflow forum where a user used a javsacript file to simulate the drag and drop action.
The link to that javascript workaround is HERE
I have tried to follow the instructions but since i am quite new to coding, I am wasting my time messing around. However, I have tried my best but now i am having problems with loading scripts. Thanks.
(Turned out that I was not correctly executing the drop.js script. The working code is below:)
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class check {
public static void main(String[] args) throws InterruptedException, IOException {
System.setProperty("webdriver.Firefox.driver", "Path_executable");
WebDriver driver= new FirefoxDriver();
driver.get("http://html5demos.com/drag#");
final String JQUERY_LOAD_SCRIPT = ("C:\\jQuerify.js");
String jQueryLoader = readFile(JQUERY_LOAD_SCRIPT);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(
jQueryLoader /* , http://localhost:8080/jquery-1.7.2.js */);
// ready to rock
js.executeScript("jQuery(function($) { " + " $('input[name=\"q\"]').val('bada-bing').closest('form').submit(); "
+ " }); ");
String filePath = "C://drop.js";
String source = "#one";
String target = "#bin";
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
while((line = br.readLine())!=null)
buffer.append(line);
String javaScript = buffer.toString();
javaScript = javaScript + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
((JavascriptExecutor)driver).executeScript(javaScript);
}
private static String readFile(String file) throws IOException {
Charset cs = Charset.forName("UTF-8");
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
stream.close();
}
}
}
My code is:-
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import javax.script.ScriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class drag {
public static void main(String[] args) throws ScriptException, NoSuchMethodException, IOException {
System.setProperty("webdriver.Firefox.driver", "Address_Executable");
WebDriver driver = new FirefoxDriver();
driver.get("http://html5demos.com/drag");
final String JQUERY_LOAD_SCRIPT = ("C:\\jQuerify.js");
String jQueryLoader = readFile(JQUERY_LOAD_SCRIPT);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(
jQueryLoader /* , http://localhost:8080/jquery-1.7.2.js */);
// ready to rock
js.executeScript("jQuery(function($) { " + " $('input[name=\"q\"]').val('bada-bing').closest('form').submit(); "
+ " }); ");
final String DROP = ("C:\\drop.js");
String scriptLoader = readFile(DROP);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js1 = (JavascriptExecutor) driver;
js1.executeScript(
scriptLoader /* , http://localhost:8080/jquery-1.7.2.js */);
((JavascriptExecutor) driver).executeScript(js1 + "$('#one').simulateDragDrop({ dropTarget: '#bin'});");
}
private static String readFile(String file) throws IOException {
Charset cs = Charset.forName("UTF-8");
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
stream.close();
}
}
}

Related

Print multiple texts from multiple elements with same class name

Im trying to print all the product names from an e commerce website in selenium using java but its printing only the first name of the product from the first class it finds. How to print all the product names from all the classes with same class name?
This is my code:
package introduction;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Getproductnames {
private static int i;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:/Temp/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.get("https://www.fipola.in/chicken");
driver.findElement(By.id("DelLocation")).sendKeys("600020");
driver.findElement(By.className("top_pincode_select")).click();
Thread.sleep(3000);
List<WebElement> products=driver.findElements(By.cssSelector("a.product-item-link"));
for(int i=0; i<products.size(); i++);
{
String[] names = new String[]{products.get(i).getText()};
System.out.println(names[i] + "");
}
}
}
You can use the below to print all the products name
List<WebElement> products=driver.findElements(By.cssSelector("a.product-item-link"));
for(int i =0;i<products.size();i++) {
String elementText = products.get(i).getText();
System.out.println(elementText);
}

Generating signin KEY in Java for Post request

I need to send a POST request to api.example.com. I need to generate singin KEY to send a POST request. The KEY must be generated by the following formula
HEX (HMAC-SHA384({apiPath} + {nonce} + JSON({body}),{secretKey}))
I've found a sample of Javascript code how to genereate signing key
javascript
const crypto = require('crypto');
const publicKey = '';
const secretKey = '';
const apiPath = '/v3/auth/kuna_codes/issued-by-me';
const nonce = new Date().getTime();
const body = {};
const signatureString = `${apiPath}${nonce}${JSON.stringify(body)}`;
const signature = crypto
.createHmac('sha384', secretKey)
.update(signatureString)
.digest('hex');
console.log(signature);
I need a Java code that generates a signing key by the formula provided above
Something like this
package com.vorontsov.tbe.main;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public class KunaSignatureGenerator {
private static final String ALGORITHM = "HmacSHA384";
private static final String API_PATH = "/v3/auth/kuna_codes/issued-by-me";
private static final String SECRET_KEY = "secret";
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, JsonProcessingException {
var signature = new KunaSignatureGenerator().generateSignature(new RequestParams("stringVal"));
System.out.println(signature);
}
private String generateSignature(RequestParams requestParams) throws NoSuchAlgorithmException, InvalidKeyException, JsonProcessingException {
var nonce = "" + System.currentTimeMillis();
var body = new ObjectMapper().writeValueAsString(requestParams);
final String signatureString = API_PATH + nonce + body;
SecretKeySpec signingKey = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
final Mac mac = Mac.getInstance(ALGORITHM);
mac.init(signingKey);
return HexFormat.of().formatHex(mac.doFinal(signatureString.getBytes()));
}
private static record RequestParams(#JsonProperty("stringParam") String stringParams) {
}
}

android studio webview to use javascript for the link

this question is how to apply java script by link to webview https://dl.dropboxusercontent.com/s/lmibwymtkebspij/background.js after the page is fully loaded the background should turn green here is a sample code for loading the page
webView = findViewById(R.id.Web);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyWebChromeClient());
thank you in advance
maybe someone will come in handy load the text of the script into the script variable using get request to link the address of the script like this:
#SuppressLint("StaticFieldLeak")
class ProgressTask extends AsyncTask<String, Void, String> {
#Override
public String doInBackground(String... path) {
try {
content = getContent(path[0]);
} catch (IOException ex) {
content = ex.getMessage();
}
return content;
}
#Override
public void onPostExecute(String content) {
scriptbg = content;
Log.d("debug", scriptbg);
}
public String getContent(String path) throws IOException {
BufferedReader reader = null;
try {
URL url = new URL(path);
HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(10000);
c.connect();
reader = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder buf = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
buf.append(line + "\n");
}
return (buf.toString());
} finally {
if (reader != null) {
reader.close();
}
}
}
then we apply the script to our webView when the page is fully loaded like this:
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:" + Script);
Log.d("debug", "finish");
}

how to send base64 string in android?

I am trying to make hydrid application in which there is a "button" on HTML page .whenever I click on that button i want to call android code function (which is working fine when I called test function from javascript) .Now I want to capture image on button click
I take help from below url.
Capture Image from Camera and Display in Activity
I do like this
package com.example.myapp.myapplication;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webview);
// webView.loadUrl("http://1.5.20.97:3671");
webView.loadUrl("http://15.16.74.160:6019");
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.addJavascriptInterface(jsInterface, "JSInterface");
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
// Log.d("My map",photo,"");
}
}
public void checkTest(){
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
}
class JavaScriptInterface {
private MainActivity activity;
public JavaScriptInterface(MainActivity activity) {
this.activity = activity;
}
#JavascriptInterface
public void test() {
this.activity.checkTest();
}
#JavascriptInterface
public String bitMapToBase64()
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//add support for jpg and more.
bitMap.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
}
I am getting import error
I am trying to call a android function which open camera and capture image and return to javascript.
on javascript I am calling function like this
console.log(window.JSInterface.test())
So to go back to your webView when you capture the image from camera, change your onActivityResult method to this
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
if (webView != null)
webView.loadUrl("http://125.16.74.160:30019");
}
}
Also you should declare you bitmap as a global static variable like this
public static Bitmap photo;
Then bitMapToBase64 become like this
#JavascriptInterface
public String bitMapToBase64()
{
if (MainActivity.photo != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//add support for jpg and more.
MainActivity.photo.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
return "null image";
}
In the javascript side you check if bitMapToBase64 function has a return value different than "null image" you convert the base64 image to a blob or image object and show it in a div for example.
Here is an example how to convert your base64 string to an image object and append it to your body
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

Empty page using sendIntent.putExtras(bundle), page not filled Android studio

I'm trying to send some stuff via mail or Bluetooth etc but not working very well.
I would like to see a text like this:
" Respiration Rate: 0 2.0 5.0 16.0 "...
To do that I've implemented a button and Resut.java stuff. When I try to click on the button and I choose e-mail, app open a mail and the text is only "Respiration Rate"
here click-button:
SRR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bundle bundle = new Bundle();
bundle.putDoubleArray("TryThis",plot_array);
sendIntent.putExtras(bundle);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " );
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
result.java:
package com.google.android.gms.samples.vision.face.rPPG;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.PointsGraphSeries;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class RespirationResult extends AppCompatActivity {
private String Date;
int RR;
int il_risultato;
double [] plot_array;
int[] intArray;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
java.util.Date today = Calendar.getInstance().getTime();
private String[] RRtoSent=new String[300];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_respiration_result);
Date = df.format(today);
TextView RRR = (TextView) this.findViewById(R.id.RRR);
ImageButton SRR = (ImageButton)this.findViewById(R.id.SendRR);
//-------------------------------------------------------------------------risutato
Bundle b = getIntent().getExtras();
double result = b.getDouble("key");
plot_array=b.getDoubleArray("array");
il_risultato=(int) Math.round(result);
RRR.setText(String.valueOf(il_risultato)); //prima era RR, da mettere successivamente
RRtoSent = new String[plot_array.length];
for (int i = 0; i < RRtoSent.length; i++) {
RRtoSent[i] = String.valueOf(plot_array[i]);
}
//grafico
GraphView graph;
LineGraphSeries<DataPoint> series; //an Object of the PointsGraphSeries for plotting scatter graphs
graph = (GraphView) findViewById(R.id.graphico);
series= new LineGraphSeries<>(data()); //initializing/defining series to get the data from the method 'data()'
graph.addSeries(series); //adding the series to the GraphView
//series.setShape(PointsGraphSeries.Shape.POINT);
// activate horizontal and vertical zooming and scrolling
graph.getViewport().setScalableY(true);
graph.getGridLabelRenderer().setGridColor(Color.DKGRAY);
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.DKGRAY);
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.DKGRAY);
// graph.setTitle("Respiration Rate/min");
graph.getGridLabelRenderer().setHorizontalAxisTitle("time(sec)");
graph.getGridLabelRenderer().setVerticalAxisTitle("RR");
// set manual X bounds
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0.5);
graph.getViewport().setMaxX(100);
SRR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bundle bundle = new Bundle();
bundle.putDoubleArray("TryThis",plot_array);
sendIntent.putExtras(bundle);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " );
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
}
public DataPoint[] data(){
DataPoint[] values = new DataPoint[plot_array.length]; //creating an object of type DataPoint[] of size 'n'
for(int i=0;i<plot_array.length;i++){
DataPoint v = new DataPoint(i,plot_array[i]);
values[i] = v;
}
return values;
}
#Override
public void onBackPressed() {
Intent i = new Intent(RespirationResult.this, SplashScreen.class);
startActivity(i);
finish();
super.onBackPressed();
}
}
Does anyone have an idea about it?
what's wrong or missing?
Thanks in advance
From Android official site:
public static final String EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent. Note that this may
be a styled CharSequence, so you must use Bundle.getCharSequence() to
retrieve it.
So you should convert your double array to String first before calling email app.
Step 1: Write a method which convert a double array to a string.
private String convertDoubleArrayToString(double[] array) {
StringBuilder sb = new StringBuilder();
for (double number: array) {
sb.append(number).append(" ");
}
return sb.toString();
}
Step 2: Change your code to
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " + convertDoubleArrayToString(plot_array));
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
That's because all you want to show must be part of the EXTRA_TEXT:
sendIntent.putExtra(Intent.EXTRA_TEXT, "EVERYTHING YOU WANT TO PRINT HERE" );
So you have to build a string with your data, then you create the extra with the complete string.

Categories

Resources