How to select multiple lines using java Selenium automation testing? - automated-tests

I tried to select multiple lines using selenium automation like below.
this.selectLineInTable(Locator.LOCATOR_LIST, "name", t1.getName()).
this.selectLineInTable(Locator.LOCATOR_LIST,"name",t2.getName()));
but its not working. Can anyone help me how to solve this issue?

try something like below:
Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).moveToElement(driver.findElement(By.xpath("first element to select"))).click().build().perform();
act.moveToElement(driver.findElement(By.xpath("second element to select"))).click().release().build().perform();

Actions act = new Actions(driver);
String m1 = this.selectLineInTable(Constant.LOCATOR_LIST_MOFULL, "name",psv.getName());//1st element
String m2=this.selectLineInTable(Constant.LOCATOR_LIST_MOFULL, "name",psTest.getName());// 2nd element
act.keyDown(Keys.CONTROL).moveToElement(driver.findElement(By.name(m1))).click().build().perform();
act.moveToElement(driver.findElement(By.name(m2))).click().release().build().perform();
protected String selectLineInTable(String scLocatorBody, String key, String value) throws Exception {
String scLocatorLine = this.findLineInTable(scLocatorBody, key, value);
if (scLocatorLine == null) {
// No line for key / value
this.logError("The row [" + key + "=" + value + "] does not exist", null);
} else {
// Click on the line
StringBuffer lRow = new StringBuffer();
lRow.append(scLocatorLine).append("col[fieldName=").append(key).append("]/");
this.clickOnElement(lRow.toString());
sleep(500);
}
return scLocatorLine;
}
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"name","selector":"scLocator=//ListGrid[ID=\"ssr_grid\"]/body/row[0]/"}

Related

Pulling data from Sqlite cursor loader

OK I have a app that has a Listview and uses sqlite data to populate it. But I also want to be able to email the contents of each view for the body of the message. I tried doing this with a global string variable and catching the data in the CarCursorAdapter activity in the BindView section like this:
// Update the TextViews with the attributes for the current move
vinTxtView.setText(vinStr);
dateTxtView.setText(dateStr);
mvFromTxtView.setText(mvFrom);
mvToTxtView.setText(mvTo);
MyProperties.getInstance().bodyStrGlobal = MyProperties.getInstance().bodyStrGlobal+vinStr+"-"+mvFrom+"->"+mvTo+"-"+dateStr+"\n";
And then I use that string in the email intent. But the problem is it keeps adding to this string every time the listview is populated so I get all kinds of double entries. What would be the best way to just capture this once when the email feature is selected? Or reset the string to null at some place? Maybe just read from each listview item instead of from the cursor loader? There is probably a way to just cycle through the database table but I'm getting all kinds of errors and haven't had any luck.
Found this to work. My MainActivity is very busy now, but everything works.
public String getEmailText(){
String tempStr = "";
String[] projection = {
CarEntry._ID,
CarEntry.COLUMN_CAR_VIN,
CarEntry.COLUMN_CAR_DATE,
CarEntry.COLUMN_CAR_MOVEFROM,
CarEntry.COLUMN_CAR_MOVETO};
Cursor cursor = getContentResolver().query(Uri.parse("content://gregorykraft.com.scanvin/cars"),projection,null,null,null);
if
(cursor == null || cursor.getCount() < 1) {
Toast.makeText(this, getString(R.string.error_uri),
Toast.LENGTH_SHORT).show();
return "";
}
int i = 0;
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
i++;
String s =String.valueOf(i);
String vinStr = cursor.getString(cursor.getColumnIndex(CarEntry.COLUMN_CAR_VIN));
String mvFrom = cursor.getString(cursor.getColumnIndex(CarEntry.COLUMN_CAR_MOVEFROM));
String mvTo = cursor.getString(cursor.getColumnIndex(CarEntry.COLUMN_CAR_MOVETO));
String dateStr = cursor.getString(cursor.getColumnIndex(CarEntry.COLUMN_CAR_DATE));
tempStr = tempStr+s+") "+vinStr + "-" + mvFrom + "->" + mvTo + "-" + dateStr + "\n";
cursor.moveToNext();
}
cursor.close();
}
return tempStr;
}

How to logically iterate through records using DataReader and then do something at each iteration

Please bear with me as I'm rather new to this.
I'm trying to iterate through a recordset using DataReader object, and do something at each iteration, but it doesn't seem to be getting passed the first record. I essentially want to look at each record and then assign a specific image to a specified location based on the data in a column in the recordset.
I'm using Visual Studio 2019 and using OleDataReader to read Access table. I've got the command object working properly, just can't seem to get passed the first record.
this is the method definition in my class
//Giving string variable names to the virtual paths of the images
private string whitePallet = "~/images/White.jpg";
private string redPallet = "~/images/Red.jpg";
private string bluePallet = "~/images/Blue.jpg";
private string blackPallet = "~/images/Black.jpg";
private string greenPallet = "~/images/Green.jpg";
private string racetrack = "~/images/Racetrack.jpeg";
public string Racetrack { get => racetrack; set => racetrack = value; }
public string OpenConnection(string connectString, String selectString)
{
using (OleDbConnection cn = new OleDbConnection(connectString))
{
cn.Open(); //Open the connection.
OleDbCommand cmd = new OleDbCommand(selectString, cn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string pallet;
if (reader["Status"].ToString() == "Blocked Location")
{
pallet = blackPallet;
return pallet;
}
if (reader["Status"].ToString() == "AP Purge")
{
pallet = redPallet;
return pallet;
}
if (reader["Status"].ToString() == "Open")
{
pallet = whitePallet;
return pallet;
}
if (reader["Status"].ToString() == "Order Complete")
{
pallet = greenPallet;
return pallet;
}
if (reader["Status"].ToString() == "Pallet Full")
{
pallet = bluePallet;
return pallet;
}
}
//Close the reader and the related connection.
reader.Close();
return null;
}
}
this is the instantiation of the class/method
'''
Definitions defs = new Definitions();
Image imgRacetrack = Image.FromFile(Server.MapPath(defs.Racetrack));
//Creating image panel to draw upon using w/h of racetrack image
Image img = new Bitmap(imgRacetrack.Width, imgRacetrack.Height);
using (Graphics gr = Graphics.FromImage(img))
{
//Background image
gr.DrawImage(imgRacetrack, new Point(0, 0));
//Defining the points on the left side:
Point p1 = new Point(125, 50);
Image imgPallet = Image.FromFile(Server.MapPath(defs.OpenConnection(connectString,selectString)));
gr.DrawImage(imgPallet, p1);
Point p2 = new Point(125, 100);
Image imgPallet2 = enter code hereImage.FromFile(Server.MapPath(defs.OpenConnection(connectString, selectString)));
gr.DrawImage(imgPallet2, p2);
}
I'm expecting to iterate through each record and then place the image with the correct color into the correct position, but it's only giving the results to each point/location based on the very first record only. What's wrong with my logic??
You declare pallet string pallet; then have several if statements in which you return pallet;.
First, you want to return a string, but you're doing
pallet = blackPallet; // pallet will not be a string.
pallet = "blackPallet"; // pallet will be a string.
Second, when you say return..., you leave the method; you don't continue after that, you are saying you are done - return this value and stop.
So you need to read the value from each row and store them, then return the collection of values. Then you can loop through the collection and plug in each value as needed.
That's one way. I didn't study what you have in complete detail so there might be a better way. Hope that's enough for now.

How do I fetch CSS Coverage data using chrome dev protocol?

I am working on creating a simple java class which would give me used & unused css on any given page.
public class coverage {
static String str;
public static void main(String[] args) throws JSONException {
String url = "https://www.amazon.com";
Launcher launcher = new Launcher();
try (SessionFactory factory = launcher.launch();
Session session = factory.create()) {
Command command = session.getCommand();
DOM dom = command.getDOM();
CSS css = command.getCSS();
session.navigate(url);
dom.enable();
css.enable();
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
HashMap<String, String> hmUsedCSS = new HashMap<String, String>();
css.startRuleUsageTracking();
List<RuleUsage> list = css.stopRuleUsageTracking();
for (RuleUsage coverage : list) {
if (!hm.containsKey(coverage.getStyleSheetId())) {
hm.put(coverage.getStyleSheetId(),
css.collectClassNames(coverage.getStyleSheetId()));
}
if (!coverage.isUsed()) {
String existingContent = hmUsedCSS.get(coverage
.getStyleSheetId());
String extraContent = css.getStyleSheetText(coverage
.getStyleSheetId());
hmUsedCSS.put(coverage.getStyleSheetId(),
existingContent == null ? extraContent
: existingContent + extraContent);
}
}
for (String name : hm.keySet()) {
List<String> value = hm.get(name);
System.out.println("Total " + name + "=>" + value);
}
for (String name : hmUsedCSS.keySet()) {
List<String> value = hm.get(name);
System.out.println("Used CSS " + name + "=>" + value);
}
}
}
}
As per official documentation, 'stopRuleUsageTracking' would tell us whether a particular CSS is being used or not by setting 'used' boolean in RuleUsage , but it is returning all the CSS available on the page with 'used' set to true.I figured out that the answer lies in startoffset & endoffset values as they tell us the positioning of used CSS.But I don't know how to convert these values into meaningful result of Used & Unused CSS ? Can someone help me out here?
As I pointed out in the question , the key was to fetch coverage data as per start & end offset values.I was able to write logic to do the same & got the required list of used & Unused CSS.

retrieve a row of data from documentum via DQL

I have a list of users in my list view which is populated by retrieving data from documentum . If I click on any row of this least (each row represent one user) I should be able to see all of their information listed down .(This is my problem )
public void selectedItemFromListView(){
selected = lwAllUserGrp.getSelectionModel().getSelectedItem();
System.out.println(selected);
String query =" select * from dm_user where user_name = '#aclName'" ;
String test = query.replace("#aclname", selected);
GetDataWithDqlProfile(_session , query , "user_login_name" , "user_address" , "user_state" );
System.out.println(user.getAddress());
System.out.println(user.getState());
System.out.println(user.getUsername());
}
if I click on a row of list view I can successfully see who is selected and I need to retrieve all the other attributes of that username (same person) from documentum via DQL .
private void GetDataWithDqlProfile(IDfSession session, String Query, String username , String address , String state ) {
try {
IDfQuery UpdateQuery = new DfQuery();
UpdateQuery.setDQL(Query);
IDfCollection col = UpdateQuery.execute(_session, IDfQuery.DF_QUERY);
user.setAddress(col.getString(username));
user.setUsername(col.getString(address));
user.setState(col.getString(state));
col.close();
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR, e.getMessage());
alert.showAndWait();
Logs.WriteLog(LoginController.Repository + ",User:" + LoginController.Username, "DQL Query", e.toString());
e.getStackTrace();
}
and my output is :
User's name
null
null
null
I've tried the DQL query in DQL tester and it works well
In order to fetch rows from IDfCollection you have to call next() on the collection object. This method both advances to the next row and returns a boolean if successful. Use a boolean test (e.g., while or if) to iterate, like this:
IDfCollection col = UpdateQuery.execute(_session, IDfQuery.DF_QUERY);
if (col.next()) {
user.setAddress(col.getString(username));
user.setUsername(col.getString(address));
user.setState(col.getString(state));
}
col.close();
The iteration is necessary even if the collection contains only one row. In other words, you need to manually advance to the first row.
1) As #eiviamu already mentioned, you have to call IDfCollection.next() to get the next row.
2) Your code, among other problems, has one documentum-related: closing of collection must happen always in finally block.
Otherwise you can get unclosed collection which might lead to memory leaks and weird application behavior (e.g. if I'm not mistaken there are 9 simultaneous open collections are allowed for one DCTM session by default, and if you exceed this limit an exception will be thrown)
For those of you referring to this question later here is how I solved the problem :
public ArrayList<User> GetDataWithDqlpro(IDfSession session, String Query, String username , String state , String address) {
try {
IDfQuery UpdateQuery = new DfQuery();
UpdateQuery.setDQL(Query);
IDfCollection col = UpdateQuery.execute(_session, IDfQuery.DF_QUERY);
while (col.next()) {
list.add( new User(col.getString(username),col.getString(address) , col.getString(state)));
}
col.close();
}catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR, e.getMessage());
alert.showAndWait();
Logs.WriteLog(LoginController.Repository + ",User:" + LoginController.Username, "DQL Query", e.toString());
e.getStackTrace();
}
return (ArrayList<User>) list;
}
public void selectedItemFromListView(){
selected = lwAllUserGrp.getSelectionModel().getSelectedItem();
System.out.println(selected);
String Query = "select user_login_name , user_state , user_address from dm_user where user_login_name ='#aclname'";
Query = Query.replace("#aclname",selected );
ArrayList<User> allUserNames = GetDataWithDqlpro(_session, Query, "user_login_name","user_address","user_state");
for (int i = 0 ; i <= allUserNames.size()-1 ; i++ ){
if (selected.compareToIgnoreCase(allUserNames.get(i).getUsername() ) == 0){
System.out.println(allUserNames.get(i).getState() );
System.out.println(allUserNames.get(i).getAddress() );
System.out.println(allUserNames.get(i).getUsername() );
}
}
}
Worth mentioning that I have a class called User with constructor and get and set methods
I hope it will help some one :)

Flex AIR Sqlite as embedded database

I am devloping an editor with spell check feature in Flex + AIR using Sqlite as an embedded database.
In database I have a table with the words. The table contains lacs of words. I have written the code to search for the word in table. I have used the sync method for all this. This pauses my application while searching.
I would like to use async method to stop application pause.
The code for Search word is as follows:
public function searchInDictionary(word:String):Boolean
{
if(word == "")
return true;
connection= new SQLConnection();
var query:SQLStatement = new SQLStatement();
query.sqlConnection = connection;
query.text = 'SELECT id FROM tbl_'+ CommonLanguageCode +' WHERE word LIKE "'+word+'"';
try
{
connection.open( dbfile,SQLMode.READ );
}
catch(ex:Error)
{}
if(!connection.connected)
connection.open( dbfile );
query.execute();
var result:SQLResult = query.getResult();
if( result.data == null )
{
return false;
}
else
{
var numRows:uint = result.data.length;
var id:String;
if(numRows>0)
return true;
return false;
}
return false;
}
If this function returns false(word not found) then i have to call the function to to red underline that word.
Please suggest me if I am going wrong. As I am using Sync method & it takes some milli seconds to search a word. & if I am wrting a paragraph then it makes my application sluggish.
Is there any other way I can store the words & search more fastly. If yes then please et me know.
Thanks in advance.
You'll need to reorganize your code a bit so that you call your function that does the red underline when the results come back instead of returning a Boolean from the method.
public function searchInDictionary(word:String):void
{
// Don't bother searching if no word was passed in
if(word == "") return;
// Open db connection asynchronously
var connection:SQLConnection = new SQLConnection();
connection.openAsync(dbfile, SQLMode.READ);
// Create statement
var statement:SQLStatement = new SQLStatement();
statement.sqlConnection = connection;
statement.text = 'SELECT id '
+ 'FROM tbl_'+ CommonLanguageCode +' '
+ 'WHERE word LIKE "' + word + '"';
// Add event listener
statement.addEventListener(SQLEvent.RESULT, function(event:SQLEvent):void{
var result:SQLResult = event.target.getResult();
if(result.data.length == 0) {
// ... call method to red underline word in text ...
}
});
// Execute statement
statement.execute();
}

Resources