connection and Toastbar not displaying issue - codenameone

1)ConnectionRequest using actionListener as parameter
ArrayList<Map<String, Object>> responses;
public void groupConnection(StateMachine sm, ActionListener al) {
ConnectionRequest connectionRequest = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jSONParser = new JSONParser();
Map<String, Object> parsedData = jSONParser.parseJSON(new InputStreamReader(input));
responses = (ArrayList<Map<String, Object>>) parsedData.get("root");
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
al.actionPerformed(null);
}
});
}
#Override
protected void handleException(Exception err) {
//System.out.println("handleException " + err);
}
#Override
protected void handleIOException(IOException err) {
//toastbar doesnt work here but dialogBox works, if showForm("Groups") is used, toastbar is also shown along with dialogbox
//ToastBar.showErrorMessage("Please check your network connection", 4000);
//sm.showForm("Groups", null);
Dialog.show("", "Please check your network connection", "ok", null);
}
};
AllUrl allUrl = new AllUrl();
connectionRequest.setUrl(allUrl.groupsMenu);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
connectionRequest.setDisposeOnCompletion(d);
NetworkManager.getInstance().addToQueue(connectionRequest);
}
In connectionRequest code above, if there is no network connection, it gives IoException: unreachable which is handled by handleIOException method below but if i use dialogBox there, it works. Instead toastbar doesnt work there, why is that? If I use showForm("Form",null) along with dialogBox and toastbar, the same form is called repeatedly and toastbar is also seen with dialog box appearing multiple times.
2)postForm(Form f) method
connectionGroup = new GroupConnection();
connectionGroup.groupConnection(StateMachine.this, new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//checking connectionGroup.responses == null doesnt work since the connectionRequest gives IOException if no network.So Toastbar doesnt work here.
if (connectionGroup.responses == null) {
ToastBar.showErrorMessage("Please check your network connection", 4000);
}
if (connectionGroup.responses != null) {
for (Map<String, Object> element : connectionGroup.responses) {
String tableName = (String) element.get("name");
TextArea nameLabel = new TextArea(tableName.toUpperCase());
f.add(singleRowContainerr);
}
}
}
}
In postForm method above, I used to check if there is network connection or not by checking: if (connectionGroup.responses == null) { do smth...}, it doesnt work here since the connectionRequest gives IoException & doesnt run code inside connectionRequest.
How to solve this problem? I have to show "check connection" in toastBar and a label with text "no connection" as well. PS I need to put all my components & connectionRequest in postForm since I need to go to the form before connectionRequest is called.

ToastBar is bound to a specific Form whereas Dialog will block any form to show itself.
You've set the ToastBar to one form then transitioned to another Form.

Related

Selenium Java : stale excpetion for dropdown

I am doing below steps in my test case
1.Open main page
2.Click on one link which opens a new page(tab)
3.Query data (Click on Query button. Page gets reloaded)
4.Select one drop down – “request” , fill some text data and click save
5.Close this tab
6.From Main page , again click on the link to open this page (tab)
7.Query some data ( Click on Query button . page gets reloaded)
8.Select one drop down - “response” , fill some data and click save
I am getting error at Step-8 while selecting drop-down "Response". The same drop-down while selecting “request” worked fine. Also, I am able to select “response” if I open the page only once (exclude steps- 3,4,5). What is happening here? I am new to selenium and tried almost every solution available for stale exception.
The same code is working fine in my colleagues system without any issues . ( same chrome version)
I also tried by giving sleep time . Also while execution it is expanding the drop-down and I could see the “response” , but still it is not selecting the response.
These are my code snippets. Using chrome browser.
************************ Testcase ******************************
public class TC_004 extends BaseClass{
#Test
public void TNRangeConfirm() throws InterruptedException{
driver.get(baseURL);
LoginUS login=new LoginUS();
login.loginTest();
Thread.sleep(10000);
logger.info("Starting Multiline Creation");
PageActions icp=new PageActions();
logger.info("Sending request");
icp.PortReq();
logger.info("Sending response");
Thread.sleep(5000);
icp.PortRes();
LogoutUS logout=new LogoutUS();
logger.info("Logging out");
logout.logoutTest();
}
}
*********************************************************
**********************Reusable Action***********************
public class PageActions extends BaseClass{
String currentWindow = driver.getWindowHandle();
MainMenuPage mmp=new MainMenuPage(driver);
ActionsPage ipdP=new ActionsPage(driver);
public void PortReq() throws InterruptedException{
System.out.println(" Creation Multi Line : Started");
System.out.println(" Click on Actions page");
mmp.clickPRRADM(); // It expands the link
Thread.sleep(1000);
mmp.clickIPD(); // Opens the page
Thread.sleep(60000);
//Switch tab
//ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
//driver.switchTo().window(tabs.get(1));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(currentWindow)) {
driver.switchTo().window(handle);
}
}
//Read Data from Excel
//objExcelFile
MngTestData mtd=new MngTestData();
try {
TN1 = mtd.readExcel(filePath, fileName, sheetName, "New_TN");
TN2 = mtd.readExcel(filePath, fileName, sheetName, "TN1");
TN3 = mtd.readExcel(filePath, fileName, sheetName, "TN2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("TN : "+TN);
ipdP.selectPortType("Request");
ipdP.setPortNo(TN);
ipdP.selectOwner(TN1);
Thread.sleep(10000);
ipdP.clickQuery();
Thread.sleep(10000);
Boolean isPresent = driver.findElements(By.id("INFO_MSD_ID_0")).size() >0 ;
if((isPresent) && (ipdP.isExist("NO RECORDS FOUND"))){ */
System.out.println("Multi Line Creation Started");
ipdP.selectPortAction("Request");
Thread.sleep(10000);
ipdP.selectNNSP(TN1);
Thread.sleep(6000);
ipdP.selectONSP(TN2);
Thread.sleep(10000);
ipdP.clickSave();
Thread.sleep(30000);
driver.close();
driver.switchTo().window(currentWindow);
Thread.sleep(10000);
}
public void PortRes() throws InterruptedException{
String currentWindow = driver.getWindowHandle();
mmp.clickPRRADM();
Thread.sleep(1000);
mmp.clickPRRADM();
Thread.sleep(5000);
mmp.clickIPD(); // opens page
Thread.sleep(30000);
//Read Data from Excel
//objExcelFile
MngTestData mtd=new MngTestData();
try {
TN = mtd.readExcel(filePath, fileName, sheetName, "New_TN");
onsp = mtd.readExcel(filePath, fileName, sheetName,"Old_Network");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create Response
System.out.println("Response Started");
//Switch tab
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
waitUntil wt= new waitUntil();
boolean isFound=wt.waitForElement(driver, By.id("select-REC_TYPE_ID"));
System.out.println("isFound"+isFound);
wt.waitTillDropdownElementLoads(By.id("select-REC_TYPE_ID"), "Request");
wt.waitTillListOfElementsVisibility(By.id("QRY_NUM_ID"));
Thread.sleep(40000);
ipdP.setPortNo(TN);
wt.waitTillDropdownElementLoads(By.id("select-QRY_OWNER_ID"), owner);
ipdP.selectOwner(owner);
Thread.sleep(10000);
ipdP.clickQuery();
Thread.sleep(40000);
ipdP.selectMultiPortAction("Response"); // My code fails at this point stale excecption.
Thread.sleep(10000);
driver.close();
driver.switchTo().window(currentWindow);
Thread.sleep(10000);
}
}
************************************************************************************
***********************************PageObject class ********************************
public class ActionsPage {
WebDriver ldriver;
public ActionsPage (WebDriver rdriver){
ldriver=rdriver;
PageFactory.initElements(rdriver,this);
}
#FindBy(id="select-DETAILS_ACTION_ID")
#CacheLookup
WebElement selAction;
public void selectPortAction(String action){
Select portAction = new Select(selAction);
portAction.selectByValue(action);
}
******************************************************************************************
I commented out #CacheLookup and it started working without any issues. But I dont know what is the reason behind this.
In PageObject class comment out #CacheLookup and this resolved my error.
#FindBy(id="select-DETAILS_ACTION_ID")
//#CacheLookup
WebElement selAction;

ConnectionRequest when the app is in the background

I've tested Geofence example by cn1 where it sets local notification. When the app is closed(get destroyed), it still gives notification. But I want to get location through GPS and run connectionRequest to save them in the server. I replaced the connectionRequest code instead of LocalNotification in following code but it doesnot work. What should I do to run the connectionRequest when the app is closed(not when it is minimized but destroyed) so that once the user installs and close (destroys) it, the app sent his/her location data in the server forever untill the app is uninstalled.
Geofence gf = new Geofence("test", loc, 100, 100000);
LocationManager.getLocationManager().addGeoFencing(GeofenceListenerImpl.class, gf);
Geofence with localNotification:
public class GeofenceListenerImpl implements GeofenceListener {
#Override
public void onExit(String id) {
}
#Override
public void onEntered(String id) {
if(Display.getInstance().isMinimized()) {
Display.getInstance().callSerially(() -> {
Dialog.show("Welcome", "Thanks for arriving", "OK", null);
});
} else {
LocalNotification ln = new LocalNotification();
ln.setId("LnMessage");
ln.setAlertTitle("Welcome");
ln.setAlertBody("Thanks for arriving!");
Display.getInstance().scheduleLocalNotification(ln, 10, LocalNotification.REPEAT_NONE);
}
}
}
Why the following doesnot work? (it only work when the app is running or is minimized but not when it is destroyed.)
public class GeofenceListenerImpl implements GeofenceListener {
#Override
public void onExit(String id) {
System.out.println("geofence onExit");
}
#Override
public void onEntered(String id) {
if(Display.getInstance().isMinimized()) {
Display.getInstance().callSerially(() -> {
System.out.println("geofence isMinimized");
});
} else {
System.out.println("geofence when app is closed");
//I want to run connectionRequest here but is not working
}
}
}
PS. I've used background fetch but it only works when the app is minimized.
Update1: Demo of how I used connectionRequest outside of minimized() method...
public class GeofenceListenerImpl implements GeofenceListener {
#Override
public void onExit(String id) {
System.out.println("geofence onExit");
}
#Override
public void onEntered(String id) {
if(Display.getInstance().isMinimized()) {
Display.getInstance().callSerially(() -> {
});
} else {
System.out.println("geofence when app is closed");
Connection c = new Connection();
c.liveTrackConnectionMethod("22" , "23");
}
}
}
Connection class
public class Connection {
ArrayList<Map<String, Object>> response;
public void liveTrackConnectionMethod(String lat, String lon) {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jSONParser = new JSONParser();
Map parser = jSONParser.parseJSON(new InputStreamReader(input));
response = null;
}
};
cr.setPost(true);
cr.setUrl("http://url.com");
cr.addArgument("userid", Preferences.get(AllUrls.userIdPreference, null));
cr.addArgument("lat", lat + "");
cr.addArgument("long", lon + "");
cr.addRequestHeader("Accept", "application/json");
NetworkManager.getInstance().addToQueueAndWait(cr);
}
}
I think an app will always return false for isMinimized() when the app is closed or minimized (i.e. not currently running in the foreground) I may be wrong about this.
Try calling your connectionRequest script outside the isMinimized(). After all, you will want to keep track of user location whether they are using the app or not.
Your first solution with LocalNotification will show users a notification by calling the else part, rather than the Dialog when they're using the app, because isMinimized() will be false.

Request a connection after the form is opened as in postForm in statemachine

I've shifted to barebone code from statemachine. Here I've code(connectionRequest) inside constructor.Hence connection is called before the new form is opened. What I need is that: after the new form is opened, the connection should be called. In statemachine, if I request a connection in postForm, the form will open and then the connectionRequest is called. How can I do that here?
Home.java
public class Home extends Form {
public Home() {
Button test = new Button("Test");
add(test);
test.addActionListener(e->{
new Test().show();
});
}
}
Test.java
public class Test extends Form{
public Test(){
Label nameLabel = new Label("");
add(nameLabel);
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jp = new JSONParser();
Map parser = jp.parseJSON(new InputStreamReader(input));
String name = (String) parser.get("name");
nameLabel.setText(name);
}
};
cr.setUrl("test.com");
NetworkManager.getInstance().addToQueueAndWait(cr);
}
}
You can use addShowListener and call the connection request there.

ConnectionRequest issue

I called 'new NewForm(res).show()' in postResponse but though the connection succeed, the particular form is not seen. I found out that if I comment out 'cr.setDisposeOnCompletion(d)', then it works fine.
But infinite progress runs infinitely if any exception occurs and so on. Is this a bug? It occured after I updated to new cn1 library update. If you want to see the project, its here:
https://drive.google.com/file/d/0B8ATnICIY2S8LUdta0F5NXYzamM/view?usp=sharing
Button checkButton = new Button("Check");
checkButton.addActionListener(e -> {
ConnectionCheck cc = new ConnectionCheck(theme);
cc.connectionCheckMethod();
});
ConnectionCheck class
public class ConnectionCheck {
Resources res;
Dialog d;
public ConnectionCheck(Resources res) {
this.res = res;
}
public void connectionCheckMethod() {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jsonp = new JSONParser();
Map<String, Object> parser = jsonp.parseJSON(new InputStreamReader(input));
System.out.println("bibek " + parser);
}
#Override
protected void postResponse() {
new NewForm(res).show();
// d.dispose();
}
#Override
protected void handleErrorResponseCode(int code, String message) {
System.out.println("login ErrorResponseCode " + code + "msg: " + message);
// d.dispose();
}
#Override
protected void handleException(Exception err) {
System.out.println("login Exception " + err);
// d.dispose();
}
#Override
protected void handleIOException(IOException err) {
System.out.println("login IOException " + err);
// d.dispose();
}
#Override
protected void handleRuntimeException(RuntimeException err) {
System.out.println("login RuntimeException " + err);
// d.dispose();
}
};
cr.setPost(true);
cr.setUrl("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo");
cr.setTimeout(30000);
cr.addRequestHeader("Accept", "application/json");
InfiniteProgress ip = new InfiniteProgress();
d = ip.showInifiniteBlocking();
cr.setDisposeOnCompletion(d); //if this line is commented, the newForm is shown
NetworkManager.getInstance().addToQueueAndWait(cr);
}
}
NewForm class
public class NewForm extends Form{
public NewForm(Resources res){
setTitle("new Form");
add(new Label("new Form"));
}
}
You need to dispose the dialog before calling the show of the new form. Dispose on completion will dispose the dialog when the connection is done which is sometimes unpredictable.
When a dialog is disposed it returns to the previous form i.e. the one shown before the dialog was shown.

catching unknown host exception in codename one

I am building an app using codename one
So the thing is, I need to access a URL using the app. THe URL brings back some result which I show on the screen.
SO I use these lines to do that :
ConnectionRequest c = new ConnectionRequest() {
protected void readResponse(InputStream input) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int ch;
while ((ch = input.read()) != -1) {
bs.write(ch);
}
serverOutput = new String(bs.toByteArray());
bs.close();
}
};
c.setUrl("My URL HERE");
c.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(c);
So, now , if the gprs is active, this code works fine.
BUT , if the GPRS is inactive, it throws an Unknow Host Exception
SO to catch this error, i TRIED to use a try catch block like this:
try{
NetworkManager.getInstance().addToQueueAndWait(c);
}
catch(Exception e)
{
Sys.out.pln(e.troString());
}
But, i still get the error in the form of a dialog in the app. How do i catch this error and put my own handling for it?
UPDATE 1:
Am not sure this is necessarily a codename one specific questions, or related to java ...so just help me out with this.
Try this to handle generic errors for all connections:
NetworkManager.getInstance().addErrorListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//handle your error here consume the event
evt.consume();
}
});
Or override:
protected void handleErrorResponseCode(int code, String message) {
}
And:
protected void handleException(Exception err) {
}
In your connection request code to do this for just one class.
Try it...
public void init(Object context) {
Display.getInstance().addEdtErrorHandler(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
evt.consume();
Throwable exception = (Throwable) evt.getSource();
}
});
}

Resources