CodeNameOne InfiniteProgress Issue - infinite

I am having issues with rendering next screen if Infinite Progress is used and if this piece of code is uncommented then I am able to show the next screen where it displays a list.
final Form poList = (Form) super.createContainer(getResourceFilePath(), "POList");
ConnectionRequest request = new ConnectionRequest()
{
Hashtable response = null;
protected void readResponse(InputStream input)
{
//Read and parse the response
}
protected void postResponse()
{
if (response != null)
{
try
{
//Get a sorted List from the response and use it to fill the list
poList.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
request.setUrl(poListUrl);
request.setPost(false);
request.addRequestHeader("Authorization","Bearer "+accessToken);
request.setContentType("text/xml");
/*
If these three lines are commented then the next form is shown properly
*/
InfiniteProgress ip = new InfiniteProgress();
Dialog dlg = ip.showInifiniteBlocking();
request.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueue(request);

You have a race condition between disposing the infinite progress and the showing of the next form.
Move the dialog showing code before
ConnectionRequest request = new ConnectionRequest()
Then
dlg.dispose();
//Get a sorted List from the response and use it to fill the list
poList.show();

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;

connection and Toastbar not displaying issue

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.

How do I get Codenameone to capture video?

I am using the following code to try to capture video with codenameone 2.0
tProperty.setHint("name the property that is a media");
final CheckBox cbVideo = new CheckBox("Video");
final Button bCapture = new Button("Capture Media");
final MediaPlayer mpPlayer = new MediaPlayer();
bCapture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ect){
try {
if (cbVideo.isSelected()) {
String value = Capture.captureVideo();
mpPlayer.setDataSource(value);
mpPlayer.setName(tProperty.getText());
}else {
String value = Capture.captureAudio();
mpPlayer.setDataSource(value);
mpPlayer.setName(tProperty.getText());
}
}catch (Exception e){
}
}
});
cM.addComponent(tProperty);
cM.addComponent(cbVideo);
cM.addComponent(bCapture);
cM.addComponent(mpPlayer);
Command [] cmds = new Command[1];
cmds[0] = new Command("Done") {
public void actionPerformed(ActionEvent evt) {
//do Option1
}
};
Dialog.show(editType, cM, cmds);
When running in the simulator, clicking on the CaptureMedia button, it will present the file chooser interface. But then I am unable to choose any file at all whether audio or video because the choose file button is diabled.
How do I get to test the video capture in the simulator?
I think it's a layout problem, you are adding the MediaPlayer component before the video was created, so it's preferred size is 0.
Try to place the video in the border layout center so it's preferred size is ignored and the player will have enough space to display.
Try this:
final Form hi = new Form("Hi World");
hi.setLayout(new BorderLayout());
final Button bCapture = new Button("Capture Media");
bCapture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ect) {
try {
final MediaPlayer mpPlayer = new MediaPlayer();
String value = Capture.captureVideo();
System.out.println("Captured Video " + value);
if (value != null) {
System.out.println("Playing Video");
InputStream is = FileSystemStorage.getInstance().openInputStream(value);
String strMime = "video/mp4";
System.out.println("Input Stream" + is.available());
mpPlayer.setName("bla");
mpPlayer.setDataSource(is, strMime, new Runnable() {
public void run() {
System.out.println("reset the clip for playback");
}
});
hi.addComponent(BorderLayout.CENTER, mpPlayer);
hi.revalidate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
hi.addComponent(BorderLayout.NORTH, bCapture);
hi.show();
There is a regression in playing local videos in the Codename One simulator although it should work on the device. The next update of Codename One will fix it but for now you can workaround it by playing from a stream which should work just fine.
Just use the FileSystemStorage class to get an InputStream to the video and invoke the appropriate playback code. Note that this is less efficient than the play via URL API so when the regression is fixed you should probably return to the URL based API.

show dialog then call method in it's OnLoad method

I use C#, Winforms.
From MainForm, I instantiate MailSendForm dialog form which sends an email, the send method is in it's OnLoad method, there is progress bar on this form that shows the sending progress.
The problem is that the form doesn't show up, untill the send finishes and the message box that shows "Success", is closed.
Is there a way to show the sending form before the send begins?
//--- MainForm
private void SendOrder(...)
{
var sm = new MailSendForm(...);
sm.ShowDialog();
}
//--- MailSendForm
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
SendEmail();
}
private void SendEmail()
{
....
// Send mail.
var success = mailman.SendEmail(email);
if (success)
{
MessageBox.Show("email sent successfully");
}
else
{
MessageBox.Show(mailman.LastErrorText);
}
}
public void mailman_OnPercentDone(object source, Chilkat.PercentDoneEventArgs args)
{
progressBar.EditValue = args.PercentDone;
if (_cancelled)
{
args.Abort = true;
}
Application.DoEvents();
}
the Shown event solved my problem.
Thank you Eiríkur Fannar Torfason.

Windows phone 7 How to create events to update UI

Hi I'm making an app that when it launches makes a HttpWebRequest, receives some XML and puts it in a list. This code is in the Application_Launching method in App.xaml.cs . This list is then used in a listpicker on the first page of the app.
However because HttpWebRequest executes on a different thread the list is not populated when I assign it to to the Listpickers itemSource.
I've been told I should have an event that fires after the list is full and a listener on my first page to populate the list when this happens. How would I declare this event and its listener?
You can use HttpWebRequest and make AsyncCallback or use WebClient class which has an event DownloadStringCompleted. An example.
public void GetXMLfromServer()
{
try
{
string url = "";//your url here
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.BeginGetResponse(new AsyncCallback(GetXMLfromServerCompleted),
request);
}
catch (Exception ex)
{
}
}
private void GetXMLfromServerCompleted(IAsyncResult asynchronousResult)
{
try
{
string resultString = "";
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
{
resultString = streamReader1.ReadToEnd();
}
//**Put your code here to populate the list**
}
catch (Exception ex)
{
}
}

Resources