The code below was written to capture the session id by going to the Network in selenium. The problem I have is Im not being able to capture the session ID outside of the lambda scope, it's null. However when i log the captured session id from within the lambda, i can actually see the session id printed in the console. Im reading articles saying it's because the variable in lambda are final and etc. but that's not helping me resolve the problem. Im think maybe I could resolve this issue by converting the lambda function to a java for loop (maybe) but im lacking some knowledge there. I'd appreciate if someone could give me a solution for this. To sum, I want to be able to grab that session id, assign it to some kinda variable in the class so I can use it from any method or any class I want for the given test.
static int count = 0;
protected synchronized String getSessionID(){
String[] IDs = new String[1];
DevTools devTools = ((ChromeDriver)Driver.getDriver()).getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
devTools.addListener(Network.responseReceived(), response -> {
if (count == 0) {
Response responsePayload = response.getResponse();
Optional<Object> optionalSessionID = Optional.ofNullable(responsePayload.getHeaders().get("session-id"));
if (optionalSessionID.isPresent() && !optionalSessionID.get().equals("null")) {
count++;
IDs[0] = optionalSessionID.get().toString();
logger.info("Session ID: " + IDs[0]); // here there's no issue. I see in the session id printed in the console
// THIS IS THE ONLY PLACE WHERE SESSION ID IS AVAILABLE, OUTSIDE FROM HERE, IT's NULL
}
}
});
return IDs[0]; // however it is retuning null at the end.
}
Related
I am using F.Promise in my async action in Playframework 2.4.6. I am able to get async calls to my DAO to work. I am able to use "map" and "flatMap" but I am not sure about the following situation.
I have an async call to find and object from the database. If that object is found, I then want to use parts of that object to then issue another async request to update that object in the database. This is part of an async update call in my controller. I am not doing something right though.
I am starting off with the following.
F.Promise<User> findUserPromise = userService.findAsync(id);
F.Promise<User> updateUserPromise = userService.updateAsync(updatedUser);
F.Promise<Result> resultPromise = findUserPromise.flatMap((foundUser){
// update foundUser with passed in Json criteria
foundUser.firstName = firstName; // etc...
return updateUserPromise.map((updatedUser) -> {
return ok(Json.toJson(u));
});
});
return resultPromise;
This doesn't seem to work. I do not want to define my updatedUserPromise until I get a response back from my findUserPromise, because maybe a user will not be found. If a user is not found, I will return F.Promise.pure(notFound("some json result")). If a user is found, then I want to update that user with the Json criteria that gets posted to my controller action. With my approach, it seems that I have to define the updateUserPromise's async call with an object (updatedUser) before I get back any results.
Can I define another promise inside the result of a promise?
I was thinking something like this, but this fails with compilation errors. inference variable B has incompatible bounds, equality constraints: play.mvc.Result, lower bounds: Play.libs.F.Promise.
F.Promise<User> findUserPromise = userService.findAsync(id);
F.Promise<Result> resultPromise = findUserPromise.map((foundUser) -> {
// foundUser is returned, now update it, or return not found...
// define our next promise with an updated foundUser object
F.Promise<User> userPromise = userService.updateAsync(foundUser);
F.Promise<Result> resultPromise2 = userPromise.map((u) -> {
return jsonResult(ok(Json.toJson(u)));
});
return resultPromise2;
});
return resultPromise;
Thanks for any help.
I am not sure if this is best way to do this, but this is working for my situation above.
F.Promise<User> findUserPromise = userService.findAsync(id);
return findUserPromise.flatMap((fu) -> {
if (fu == null) {
ObjectNode result = Json.newObject();
result.put("error", "Not found " + id);
return F.Promise.pure(jsonResult(notFound(result)));
}
// dynamically update fields on found user
fu.userName = userName;
fu.firstName = firstName;
// more updates...
// make a new promise that will use the updated foundUser object
F.Promise<User> updateUserPromise = userService.updateAsync(fu);
return updateUserPromise.map((uu) -> {
return jsonResult(ok(Json.toJson(uu)));
});
}
All the examples I found for chaining promises or nested promises, they seem to use web services as an example, and they all appear to be known at design time. In my situation, I do not know what my foundUser object will be until it is returned, so I need to create my inner promise inside the outer promise.
I have this constructor:
public Revaluator(File model,PrintStream ps) {
modelFile=model;
rsession=Rsession.newInstanceTry(ps, null);
rsession.eval("library(e1071)");
rsession.load(modelFile);
}
i want to load a model and predict with it.
the problem that Rsession.newInstanceTry(ps, null); is always the same session, so if i load another model, like:
Revaluator re1=new Revaluator(new File("model1.RData"),System.out);
Revaluator re2=new Revaluator(new File("model2.RData"),System.out);
Both re1 and re2 using the same model, since the var name is model, so only the last one loaded.
the evaluate function:
public REXP evaluate(Object[] arr){
String expression=String.format("predict(model, c(%s))", J2Rarray(arr));
REXP ans=rsession.eval(expression);
return ans;
}
//J2Rarray just creates a string from the array like "1,2,true,'hello',false"
i need to load about 250 predictors, is there a way to get every instance of Rsession as a new separated R Session?
You haven't pasted all of your code in your question, so before trying the (complicated) way below, please rule out the simple causes and make sure that your fields modelFile and rsession are not declared static :-)
If they are not:
It seems that the way R sessions are created is OS dependent.
On Unix it relies on the multi-session ability of R itself, on Windows it starts with Port 6311 and checks if it is still free. If it's not, then the port is incremented and it checks again, if it's free and so on.
Maybe something goes wrong with checking free ports (which OS are you working on?).
You could try to configure the ports manually and explicitly start different local R servers like this:
Logger simpleLogger = new Logger() {
public void println(String string, Level level) {
if (level == Level.WARNING) {
p.print("! ");
} else if (level == Level.ERROR) {
p.print("!! ");
}
p.println(string);
}
public void close() {
p.close();
}
};
RserverConf serverConf = new RserverConf(null, staticPortCounter++, null, null, null);
Rdaemon server = new Rdaemon(serverConf, this);
server.start(null);
rsession = Rsession.newInstanceTry(serverConf);
If that does not work, please show more code of your Revaluator class and give details about which OS you are running on. Also, there should be several log outputs (at least if the log level is configured accordingly). Please paste the logged messages as well.
Maybe it could also help to get the source code of rsession from Google Code and use a debugger to set a breakpoint in Rsession.begin(). Maybe this can help figuring out what goes wrong.
I have a Java code using partner API for connecting to Salesforce.
I am trying to get the number of records/rows for my salesforce object. All my tries were unsuccessful.
I went through a sample code that uses AggregateResult class for this purpose.When I try to implement it, the program throws error(Cannot cast from SObject to AggregateResult).
How can I do it.
The following may work for you. In my system I have an object Device that is a child of Account. There is also an object Alert that is a child of Device. I used an aggregate query to get the account ids for Alert records that meet a certain condtion.
StringBuilder openAlertQuery = new StringBuilder();
openAlertQuery.append("SELECT Device__r.Account__c");
openAlertQuery.append(" FROM Alert__c WHERE Cleared__c = FALSE GROUP BY Device__r.Account__c");
List<SObject> alertRecords = sfdcServer.doQuery(openAlertQuery.toString());
List<String> accountIds = new ArrayList<String>();
for (SObject alert : alertRecords)
{
String accountId = (String) alert.getChild("Account__c").getValue();
accountIds.add(accountId);
}
Notice the SObject method is getChild(name) rather than the usual getField(name). getChild(name) returns an com.sforce.ws.bind.XmlObject which has the getValue() method.
This is my class reponsible for new item entries, and from the start it has been a complete nightmare, I can't seem to resolve the issues I am facing which are:
setStock(float) in Item cannot be applied to ()
Item entry:
private void writeItemRecord()
{
// Check to see if we can connect to database table
if ( DataBaseHandler.makeConnectionToitemDB() == -1)
{
JOptionPane.showMessageDialog (frame, "Unable to connect to database table (Item)");
}
else // Ok, so first read data from the text fields
{
// Read data from form and store data
String Itemname = ItemnameTxtField.getText();
String Itemcode = ItemcodeTxtField.getText();
String Description = DescriptionTxtField.getText();
String Unitprice = UnitpriceTxtField.getText();
String Style = StyleTxtField.getText();
String Finish = FinishTxtField.getText();
String Stock = StockTxtField.getText();
// Convert priceStr to a float
Float fvar = Float.valueOf(Unitprice);
float price = fvar.floatValue();
Float svar = Float.valueOf(Stock);
float stock = svar.floatValue();
// Create a Item oject
Item Item = new Item();
// Set the attributes for the Item object
Item.setItemname (Itemname);
Item.setItemcode (Itemcode);
Item.setDescription (Description);
Item.setUnitprice (price);
Item.setStock(stock);
Item.setStyle(Style);
Item.setFinish(Finish);
// Write Item record. Method writeToItemTable() returns
// 0 of OK writing record, -1 if there is a problem. I store
// the returned value in a variable called error.
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
Item.setStock(),
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address)
);
// Check if there is a problem writing the record, in
// which case error will contain -1
if (error == -1)
{
JOptionPane.showMessageDialog (frame, "Problem writing record to Item Table");
}
// Clear the form - actual method is coded below
clearForm();
// Close database connection. Report an error message
// if there is a problem.
if ( DataBaseHandler.closeConnection() == -1 )
{
JOptionPane.showMessageDialog (frame, "Problem closing data base conection");
}
}
} // End
Any help is much appreciated!
And item extracts:
public void setStock(float StockIn)
{
Stock = StockIn;
}
public float getStock()
{
return Stock;
}
For starters, adhere to Java naming conventions. Nothing except class/interface names is allowed to use CamelCase. Use lowerCamelCase. As for your "problem", you wrote
Item.setStock(),
so obviously it's giving you the error. It is also giving you the exact line number of the error, something that would obviously have helped us to diagnose your problem.
Solution: use Item.getStock() (i suppose, it's hard to tell). Calling Item.setStock at that position (as an argument to a method call) is meaningless anyway, given that setStock is a void method.
Java compiler errors come with a line number - pay attention to it. This is your problem:
Item.setStock()
setStock() requires a parameter, you are trying to call it without one. Perhaps you meant getStock()? And I suspect that all the calls to set methods in the parameter list to writeToItemTable are also wrong, as those set methods will have void as return value, so you can't use them that way.
The setStock method looks like this:
public void setStock(float StockIn)
To call it, you need to pass a float as an argument. Somewhere in your code, you call the method, like this:
Item.setStock(),
The method needs to be called with the float argument, but instead it's called with none, hence you see a compilation error.
In this code:
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
// Right here --> Item.setStock(),
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address)
);
Notice that you're calling Item.setStock(), Item.setStyle(Style), etc. instead of Item.getStock(), Item.getStyle(), etc. This is probably the source of your problem - you're trying to call the setStock() method with no arguments, hence the error.
Hope this helps!
This line
// Create a Item oject
Item Item = new Item();
Is problematic. Not only is it bad style in Java to use uppercase names for variables, this particular instance results in a compile error. Also, you're calling setStock without a parameter. You need to fix that as well.
Here is your error:
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
Item.setStock(), // <<< here! should be getStock()
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address));
But again... consider naming/coding conventions.
I am writing a small integration piece to to retrive the testcases from TestCase Management tool in java, in which i have the following scenarios:-
1) I have testcase which is “failed”, that time I am checking whether there is any defect which is already exists in the Defect management tool for the failed testcase using the testcase name , because the testcase name and the defect name are same in our case.
If not I am logging the new defect. This is fine.
2) In another case, I have testcase which is “Passed” at the first time, for that also I am checking the whether there are any duplicate defect is present in the Defect management tool , eventhough I am not going to log any defect.
This I am doing because, I don’t know whether the testcase is “Pass” or “Fail” in the first attempt or not. Hence I am doing this mandatory check , to see whether the duplicate defect exists or not for both “pass” and “fail” testcase.
I know that it is wrong to check the duplicate existence of the defect for the “pass” testcase. But there is no option I have. Is there any way we can ignore calling duplicate existence of the defect method if the testcase is “passed”?
I want your guys opinion on this.
This is the code which i have:-
private int NOT_TESTED = 0;
private int PASSED_1 = 0;
private int PASSED_2 = 0;
private int FAILED =0;
private String testStatus = "pass"; // will be fetched dynamically
private void execute(){
if(testStatus.equalsIgnoreCase("fail")){
//FAILED--;
FAILED = FAILED + 1;
System.out.println("the failed value is:"+FAILED);
}else if(testStatus.equalsIgnoreCase("pass")){// first attempt
PASSED_1 = PASSED_1 + 1;
System.out.println("the Passed_1 value is:"+PASSED_1);
if(PASSED_1 == 1){
System.out.println("Passed in the first attempt, hence no need to create a defect");
}
}else if(testStatus.equalsIgnoreCase("pass") && FAILED ==1){// second attempt
PASSED_2 = PASSED_2+1;
System.out.println("the Passed_2 value is:"+PASSED_2);
if(PASSED_2 ==1){
System.out.println("Passed in the second attempt, create a defect");
// logic to create a new defect
}
}else {
System.out.println("The test not tested");
}
}
This code is not working as it always go to the first pass attempt state, hence please do provide a solution to find if the testcase is passed in the second attempt (FAIL->PASS) so that we can take appropriate action on this.
Thanks in advance.
if the condition (testStatus.equalsIgnoreCase("pass") && FAILED ==1) is true, it means that the condition before it is also true:
if(testStatus.equalsIgnoreCase("pass"))
Since you used if-else, it will go into the first condition and then skip the rest.
Switching between those two will give you the desired result I think.