How to skip the locator which does not exist in selenium webdriver? - selenium-webdriver

I have around 50 rows in a page. But those items are in sequence.
The problem is when someone entered and deleted that table row. That id would not be there in page..
Example:
User added 1st record: id 101 added.
User added 2nd record: id 102 added
User added 3rd record: id 103 added.
If user deletes 2nd record, then two records would be there on the page but with id 101, 103.
I am trying to write that if that id is present then get the text else leave that in the for loop. I am getting only records till it found if that id is not found getting NoSuchElementException is displayed.
Please correct the code. But i want to the solution that if that id not exist, skip and run the else part.
for (int i = counterstart; i <= counterend; i++) {
if(driver.findElement(By.xpath("//*[#id='" + i + "']/a")).isDisplayed()){
System.out.println(i+" is present");
String Projects = driver.findElement(By.xpath("//*[#id='" + i + "']/a")).getText();
System.out.println(Projects);
} else{
System.out.println(i+" is NOT present");
}
}
The exception that I get:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with xpath == //*[#id='7593']/a (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 503 milliseconds

Try this method isPresent instead of isDisplayed.
public boolean isPresent(WebElement e) {
boolean flag = true;
try {
e.isDisplayed();
flag = true;
}
catch (Exception e) {
flag = false;
}
return flag;
}

How about this:
for (int i = counterstart; i <= counterend; i++) {
WebElement element;
try{
element = driver.findElement(By.xpath("//*[#id='" + i + "']/a"));
}catch(NoSuchElementException n)
{
element = null;
}
if(element !=null){
System.out.println(i+" is present");
String Projects = driver.findElement(By.xpath("//*[#id='" + i + "']/a")).getText();
System.out.println(Projects);
}else{
System.out.println(i+" is NOT present");
}
}

Find all the parent of all the elements you want to get the text from and use it to drill down, this way you won't get the exception
Assuming the html looks like this
<div id="parent">
<div id="11">
<a>text</a>
</div>
<div id="12">
<a>text</a>
</div>
<div id="13">
<a>text</a>
</div>
</div>
You can do this
// get all the elements with id
List<WebElement> ids = driver.findElements(By.cssSelector("#parent > div"));
// get all the texts using the id elements
for (WebElement id :ids) {
String projects = id.findElement(By.tagName("a")).getText();
System.out.println(projects);
}

Related

An unexpected null key in HashSet, the first be added not the rest

I'm learning Activiti 7, I drew a BPMN diagram as below:
When the highlight1 UserTask has been completed but the highlight2 UserTask is still pending, I ran the following code to highlight the completed flow element.
private AjaxResponse highlightHistoricProcess(#RequestParam("instanceId") String instanceId,
#AuthenticationPrincipal UserInfo userInfo) {
try {
// Get the instance from the history table
HistoricProcessInstance instance = historyService
.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
BpmnModel bpmnModel = repositoryService.getBpmnModel(instance.getProcessDefinitionId());
Process process = bpmnModel.getProcesses().get(0);
// Get all process elements, including sequences, events, activities, etc.
Collection<FlowElement> flowElements = process.getFlowElements();
Map<String, String> sequenceFlowMap = Maps.newHashMap();
flowElements.forEach(e -> {
if (e instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) e;
String sourceRef = sequenceFlow.getSourceRef();
String targetRef = sequenceFlow.getTargetRef();
sequenceFlowMap.put(sourceRef + targetRef, sequenceFlow.getId());
}
});
// Get all historical Activities, i.e. those that have been executed and those that are currently being executed
List<HistoricActivityInstance> actList = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.list();
// Each history Activity is combined two by two
Set<String> actPairSet = new HashSet<>();
for (HistoricActivityInstance actA : actList) {
for (HistoricActivityInstance actB : actList) {
if (actA != actB) {
actPairSet.add(actA.getActivityId() + actB.getActivityId());
}
}
}
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
// Get the completed Activity
List<HistoricActivityInstance> finishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.finished()
.list();
// Highlight the completed Activity
Set<String> highActSet = Sets.newHashSet();
finishedActList.forEach(point -> highActSet.add(point.getActivityId()));
// Get the pending highlighted node, i.e. the currently executing node
List<HistoricActivityInstance> unfinishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.unfinished()
.list();
Set<String> unfinishedPointSet = Sets.newHashSet();
unfinishedActList.forEach(point -> unfinishedPointSet.add(point.getActivityId()));
...
return AjaxResponse.ajax(ResponseCode.SUCCESS.getCode(),
ResponseCode.SUCCESS.getDesc(),
null);
} catch (Exception e) {
e.printStackTrace();
return AjaxResponse.ajax(ResponseCode.ERROR.getCode(),
"highlight failure",
e.toString());
}
}
Please see this piece of code:
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
It was expected to get 2 elements in the highSequenceSet, but it got 3, with a unexpected null.
The log printed in the console was:
Why is the first null added to the HashSet but not the rest?
Why is the first null added to the HashSet but not the rest?
HashSet implements the Set interface, duplicate values are not allowed.

Remove Object from runTransactionBlock Array [Swift Firebase]

I'm trying to use Firebase and runTransactionBlock to update an Array on a server. I previously was able to add the uid of userToFollow to user's Following node using the solution found on Synchronized Array (for likes/followers) Best Practice [Firebase Swift]. Now I am trying to enable unfollowing by removing the uid of userToFollow from user's Following node, but despite the runTransactionBlock succeeding the data is not getting updated. Here is my code:
static func unfollow(user: FIRUser, userToUnfollow: FIRUser) {
self.database.child("users/"+(user.uid)+"/Following").runTransactionBlock({ (currentData: FIRMutableData!) -> FIRTransactionResult in
var value = currentData?.value as? Array<String>
if (value == nil) {
print("unfollow - user has never followed user ID " + userToUnfollow.uid)
FIRTransactionResult.abort()
} else {
value = value!.filter() {$0 != userToUnfollow.uid}
}
currentData.value = value!
return FIRTransactionResult.successWithValue(currentData)
}) { (error, committed, snapshot) in
if let error = error {
print("unfollow - update user unfollowing transaction, please try again - EXCEPTION: " + error.localizedDescription)
} else {
print("unfollow - update user unfollowing success")
}
}
}
I am trying to update the array by first sorting out the uid of userToUnfollow then syncing this data with Firebase. How can I get this to actually remove the node? Thanks.

Set field Accessibility to Custom Salesforce Lead field from Java code

I am working around with Salesforce and force.com API and metadata API, version 36.
I can create a custom field in a Lead object but by default I can see it's hidden and this means I cannot create a new Lead with these custom fields because it returns a bad request (400 status code).
Is there any way by Code to set the custom field Visible?
public boolean createCustomExtTextField(String name, LoginResult metadataLoginResult, int length) {
boolean success = false;
CustomField cs = new CustomField();
cs.setFullName("Lead."+name+"__c");
cs.setLabel("Custom"+name+"Field");
cs.setType(FieldType.LongTextArea);
cs.setLength(length);
cs.setVisibleLines(50); // max 50
try {
MetadataConnection metadataConnection = createMetadataConnection(metadataLoginResult);
SaveResult[] results = metadataConnection.createMetadata(new Metadata[] { cs });
for (SaveResult r : results) {
if (r.isSuccess()) {
success = true;
} else {
System.out.println("Errors were encountered while creating " + r.getFullName());
for (com.sforce.soap.metadata.Error e : r.getErrors()) {
System.out.println("Error message: " + e.getMessage());
System.out.println("Status code: " + e.getStatusCode());
}
}
}
} catch (ConnectionException e) {
e.printStackTrace();
}
return success;
}
I am googling a lot and don't find something that actually helped. So, any hints are welcomed. Thank you.
Finally found a solution to this. I final one for me was to make all custom fields REQUIRED.
CustomField cs = new CustomField();
cs.setFullName("Lead.YourCompanyName" + name + "__c");
cs.setLabel("YourCompanyName" + name);
cs.setRequired(true);
...
com.sforce.soap.enterprise.LoginResult metadataLoginResult = operations.loginToMetadata(username, password, "https://login.salesforce.com/services/Soap/c/36.0");
...
private boolean createFieldInMetadata(LoginResult metadataLoginResult, CustomField cs) {
boolean success = false;
try {
MetadataConnection metadataConnection = createMetadataConnection(metadataLoginResult);
SaveResult[] results = metadataConnection.createMetadata(new Metadata[] { cs });
for (SaveResult r : results) {
if (r.isSuccess()) {
success = true;
} else {
System.out.println("Errors were encountered while creating " + r.getFullName());
for (com.sforce.soap.metadata.Error e : r.getErrors()) {
System.out.println("Error message: " + e.getMessage());
System.out.println("Status code: " + e.getStatusCode());
}
}
}
} catch (Exception e) {
}
return success;
}
And so it will appear in the page layout. Very important to know, a required field cannot have just an empty value set, it must be something. So if not all custom fields are required in your logic and you wanna avoid the entire process of unzipping page layout and zipping it back (however it may be done) just add "N/A" or any char at choice to the required by code but not your project custom fields.
I managed to make the custom Field Level Security visible for "Admin" profile but not Field Accessability to visible. The latter is untested.

The given key was not present in the dictionary solrnet

Please note: I know for the question SolrNet - The given key was not present in the dictionary and I have initialized solr object just like Mauricio suggests.
I am using solr 4.6.0 and solrnet build #173, .net framework 4.0 and VS2012 for development. For some unknown reason I am receiving error 'The given key was not present in the dictionary'. I have a document with that id in solr, I've checked via browser. It's a document like any other document. Why is error popping up? My code (I've made a comment on the place where the error happens):
//establishes connection with solr
private void ConnectToSolr()
{
try
{
if (_solr != null) return;
Startup.Init<Register>(SolrAddress);
_solr = ServiceLocator.Current.GetInstance<ISolrOperations<Register>>();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//Returns snippets from solr as BindingSource
public BindingSource GetSnippets(string searchTerm, DateTime? startDate = null, DateTime? endDate = null)
{
ConnectToSolr();
string dateQuery = startDate == null
? ""
: endDate == null
? "savedate:\"" + convertDateToSolrFormat(startDate) + "\"" //only start date
: "savedate:[" + convertDateToSolrFormat(startDate) + " TO " +
convertDateToSolrFormat(endDate) + "]";//range between start and end date
string textQuery = string.IsNullOrEmpty(searchTerm) ? "text:*" : "text:*" + searchTerm + "*";
List<Register> list = new List<Register>();
SolrQueryResults<Register> results;
string currentId = "";
try
{
results = _solr.Query(textQuery,
new QueryOptions
{
Highlight = new HighlightingParameters
{
Fields = new[] { "*" },
},
ExtraParams = new Dictionary<string, string>
{
{"fq", dateQuery},
{"sort", "savedate desc"}
}
});
for (int i = 0; i < results.Highlights.Count; i++)
{
currentId = results[i].Id;
var h = results.Highlights[currentId];
if (h.Snippets.Count > 0)
{
list.Add(new Register//here the error "the given key was not present in the dictionary pops up
{
Id = currentId,
ContentLiteral = h.Snippets["content"].ToArray()[0].Trim(new[]{' ', '\n'}),
SaveDateLiteral = results[i].SaveDate.ToShortDateString()
});
}
}
BindingList<Register> bindingList = new BindingList<Register>(list);
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = bindingList;
return bindingSource;
}
catch(Exception e)
{
MessageBox.Show(string.Format("{0}\nId:{1}", e.Message, currentId), "Solr error");
return null;
}
}
I've found out what's causing the problem: saving empty documents into solr. If I make an empty query (with text:*) through solrnet (usually I do this if I want to see all saved documents) and empty document is one of saved docs, then 'The given key is not present in dictionary pops up'. If all of the documents have text in them, this error doesn't pop up.
If you document contains fields with types other than string and you index null value to a double or integer field you will get the same error.
solr query return the null field as:
<null name="fieldname"/>
should be
<double name="fieldname">0.0</double>
or
<double name="fieldname"/>

Salesforce App follow stopped working

My company has an app that they got off of the app exchange(Note: before I started) that allowed you to follow or unfollow large number of cases/accounts/opportunities etc in salesforce.com. Supposedly it worked before and now it isn't working. I need an idea of what is wrong with the code for each button. If I can't fix them, any ideas for a replacement app? The app is no longer on the app exchange any more.
here's the code for the follow button:
{!REQUIRESCRIPT("/soap/ajax/18.0/connection.js")}
//EDIT THE FOLLOWING LINE TO ALTER THE CODE FOR OTHER OBJECTS. USE THE PICKLISTS ABOVE TO SELECT FIELD TYPE = $ObjectType AND THE OBJECT NAME THEN REPLACE "$ObjectType.Case" WITH YOUR NEW OBJECT NAME
var records = {!GETRECORDIDS( $ObjectType.Case)};
function LBox() {
var box = new parent.SimpleDialog("steve"+Math.random(), true);
parent.box = box;`
box.setTitle("Follow Records");
box.createDialog();
box.setWidth(220);
box.setContentInnerHTML("<img src='/img/loading32.gif' alt='' /> Running");
box.setupDefaultButtons();`
box.show();
}
function CBox(){
box.setContentInnerHTML("You are now following "+follow_count+" records<br /><br />Close");
}
if (records[0] == null) {
alert("Please select at least one record.");
}
else {
var follow_count = 0;
LBox();
for (var i = 0; i < records.length; i++){
var fol=new sforce.SObject("EntitySubscription");
fol.ParentId = records[i];
fol.SubscriberId = '{!User.Id}';
try{
sforce.connection.create([fol]);
follow_count++;
}
catch(e){
alert(e);
}
}
CBox();
}
here's the unfollow button:
{!REQUIRESCRIPT("/soap/ajax/18.0/connection.js")}
// EDIT THE FOLLOWING LINE TO ALTER THE CODE FOR OTHER OBJECTS. USE THE PICKLISTS ABOVE TO SELECT FIELD TYPE = $ObjectType AND THE OBJECT NAME THEN REPLACE "$ObjectType.Case" WITH YOUR NEW OBJECT NAME
var records = {!GETRECORDIDS( $ObjectType.Case)};
// display running message popup
function LBox() {
var box = new parent.SimpleDialog("steve"+Math.random(), true);
parent.box = box;`
box.setTitle("Unfollow Records");
box.createDialog();
box.setWidth(220);
box.setContentInnerHTML("<img src='/img/loading32.gif' alt='' /> Running");
box.setupDefaultButtons();
box.show();
}
// display output message
function CBox(){
if (unfollow_count < records.length)
box.setContentInnerHTML("You have now unfollowed "+unfollow_count+" records. You were not following the other selected records. <br /><br />Close");
else
box.setContentInnerHTML("You have now unfollowed "+unfollow_count+" records. <br /><br />Close");
}
if (records[0] == null) {
alert("Please select at least one record.");
}
else {
var unfollow_count = 0;`
LBox();
try {
// find following records
var searchstring = "SELECT Id FROM EntitySubscription WHERE (ParentId IN (";
for (var i = 0; i < records.length - 1; i++) {
searchstring += "'" + records[i] + "',";
}
searchstring += "'" + records[records.length - 1] + "') AND SubscriberId ='{!User.Id}')";
var resultRecords = sforce.connection.query(searchstring).getArray("records");
// delete following records
var recordIds = [];
for (var i = 0; i < resultRecords.length; i++) {
recordIds.push(resultRecords[i].Id);
unfollow_count++;
}
sforce.connection.deleteIds(recordIds);
} catch(e) {
alert(e);
}
CBox();
}
The first error message has to do with permissions, I don't get this error because I have admin rights, the second error is only on the account tab's button. I'm more worried about the permissions problem, is there anything there about permissions. Any help is great!
I think the issue is a throttle in SFDC, you are limited to following only a certain number of records per user. If this app was designed as you described to mass-follow records, it's possible your hitting that throttle, which is kind of the impression I get from the error your co-worker is receiving about at most 1000, also if it worked before, it would make sense that you have maxed out a limit for the org/user
Queries on EntitySubscription by users who aren't system admins must contain a LIMIT. If you change the query code in the button to the following it should work:
// find following records
var searchstring = "SELECT Id FROM EntitySubscription WHERE (ParentId IN (";
for (var i = 0; i < records.length - 1; i++) {
searchstring += "'" + records[i] + "',";
}
searchstring += "'" + records[records.length - 1] + "') AND SubscriberId ='{!User.Id}') LIMIT 1000";

Resources