catching unknown host exception in codename one - codenameone

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();
}
});
}

Related

How to Implement Conditionally Running of Tests in TestNG?

I am stuck in a scenario, where user is allowed to rate the movie only once a day with same user credentials.
If user tried to rate the same movie or contract, error pop_up seen.
I want to Implement in a way, that if once any movie/contract is rated. The rating functionality should be skipped and Error pop should be Handled.
I am using Selenium eclipse 2017, Chrome browser 61.0 and Test-Ng
Please help in the same.
Thanks.
public class Ratings {
String driverPath = "F:/ChromeDriver/chromedriver.exe";
public WebDriver driver;
public Alert alert;
#BeforeTest
public void LaunchBrowser () throws InterruptedException {
System.out.println("WebBrowser open");
System.setProperty("webdriver.chrome.driver","F:/ChromeDriver/chromedriver.e
xe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
#Test (priority = 1, alwaysRun = true)
public void HomePageUSA() throws InterruptedException {
driver.navigate().to("Https://us.justdial.com");
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
AssertJUnit.assertEquals(expectedTitle, actualTitle);
System.out.println("Test Passed");
}
catch (Throwable e)
{
System.out.println("Test Failed");
}
Thread.sleep(3000);
}
#Test (priority = 2, dependsOnMethods = {"HomePageUSA"})
public void Login() throws Exception{
Thread.sleep(3000);
driver.findElement(By.xpath("/html/body/div/div[1]/div[1]/div[1]/div/div/div
/div[4]/aside/div/span/a[1]")).click();
driver.findElement(By.id("inputPassword3")).clear();
driver.findElement(By.id("inputPassword3")).sendKeys("testing.testjd#gmail.c
om");
driver.findElement(By.id("exampleInputPassword1")).clear();
driver.findElement(By.id("exampleInputPassword1")).sendKeys("justdial");
driver.findElement(By.xpath("/html/body/div[4]/div[2]/div[1]/section/div/div
[1]/div/form/div[3]/div/button")).click();
Thread.sleep(1000);
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
Assert.assertEquals(expectedTitle, actualTitle);
System.out.println("Login Successful");
}
catch (Throwable e)
{
System.out.println("Login Failed");
}
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div[1]/div/header/div/div[1]/a[2]")).click();
Thread.sleep(2000);
}
#Test (priority = 3)
public void Movies_Rating_page() throws Exception {
driver.findElement(By.xpath(".//*[#id='hotkeylnk106']/div[2]")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[3]/div[2]/div/div[1]/div[1]/div/a/span/img")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[2]/div[1]/ul/li[2]/span/a[2]/span[1]")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(".//*
[#id='AlreadyRated']/div/div/div/section/div/a")).click();
System.out.println("Rating Page Redirection Successful");
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[2]/span[2]/span[10]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[3]/textarea")).sendKeys("Very nice
movie, Must watch.");
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[4]/button[2]")).click();
Thread.sleep(3000);
System.out.println("Rating Successfully Submitted");
You can create a method and tag that method in your test method as dependsOnMethods . You can achieve it like below (i tried to answer to the best based on the info provided)
The idea here is that when your rated condition is met isMovieRated should throw exception so that Movies_Rating_page() will be skipped by testNG ,otherwise isMovieRated just returns true and nothing should be skip.
#Test
public static boolean isMovieRated(String locator) {
//check in "if" below that element has already clicked or is equal to something. I used 'AlreadyClicked' just to
give an idea as I dont have your application information.
if (driver.findElement(By.xpath(locator).getText()=="AlreadyClicked"){
throw new RuntimeException();
}
else {
return true;
}
}
Now your Movies_Rating_page() will look like this
#Test (priority = 3,dependsOnMethods = { "isMovieRated" })
public void Movies_Rating_page() throws Exception {
public static String YourLocator = "/html/body/...."
Ratings.isMovieRated(YourLocator);
..
}
here is a link for more info on testNG dependsOnMethods
Note:
The code above is not tested.
If you are doing things other than checking rating in Movies_Rating_page() then you should separate those things because everything will be skipped when an exception is thrown.
Hope this helps.

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.

Unable to display toast messages

I have download and use the code form the following URL
https://github.com/Pmovil/Toast to display toast message.
Initially I got NativeToastImpl Not implemented error. I have resolved by coping the native related code to my project. Now the System throws Runtime Exception "Toast is not supported in this platform."
Here is my code to display toast message.
public class MyApplication {
private Form current;
private static Object context;
public void init(Object context) {
MyApplication.context = context;
}
public static Object getContext() {
return context;
}
public void start() {
if (current != null) {
current.show();
return;
}
showLoginForm();
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
private void showLoginForm() {
Form form = new Form("WelCome ...");
Button b = new Button(" Login ");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" Came hgere ");
Log.p(" *** " + MyApplication.getContext());
Toast.makeText(MyApplication.getContext(), "HI", Toast.LENGTH_LONG);
}
});
form.addComponent(b);
form.show();
}}
I have used Net Beans IDE for development, OS : windows 8.1
Please let me know I am doing wrong in this code and
Is there any other way to display toast messages using codename one?.
Thanks in advance
please edit the following code and please test the toast in device . Toast is not available in emulator.
public void init(Object context) {
this.context = context;
}
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" Came hgere ");
Toast.makeText(context, "HI", Toast.LENGTH_LONG);
}
});
You missed the show() method on Toast.
Toast.makeText(MyApplication.getContext(), "HI", Toast.LENGTH_LONG).show();

Apache Camel - Exception - How caught an a exception

i'm newbie with apache camel (I'm using 2.8.1 version). I'm working with this framework and i understand (i hope) concept like route. Now i have this route definition
try {
context.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
// TODO Auto-generated method stub
from("vm:internal").
split().method(DefaultSplitLogic.class, "split").
dynamicRouter(bean(router, "route"));
}
});
}catch (DefaultSplitLogicException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is the DefaultSpliLogic.class
public class DefaultSplitLogic {
public Object[] split(Object o) throws DefaultSplitLogicException{
if(o instanceof Collection<?>){
Collection c = (Collection) o;
return c.toArray();
}
else {
throw new DefaultSplitLogicException("Default Splitting Logic not correct");
}
}
}
This is DefaultSplitLogicException.class
public class DefaultSplitLogicException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
public DefaultSplitLogicException(String msg) {
// TODO Auto-generated constructor stub
super(msg);
System.err.println(msg);
}
public DefaultSplitLogicException(Throwable cause) {
super(cause);
}
}
I leaved router definition.
Now i want to capture my exception (i'm sure that my exception is thrown).
I'm using the onException clause into the route definition
try {
context.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
// TODO Auto-generated method stub
onException(DefaultSplitLogicException.class).handled(false);
from("vm:internal").
split().method(DefaultSplitLogic.class, "split").
dynamicRouter(bean(router, "route"));
}
});
}catch (DefaultSplitLogicException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but i cannot manage my exception. I tried to use differently this clause without success. Why?
Thank you all
I think i found the answer. It should be a bug of 2.8.1. version, fixed with 2.8.2+
http://camel.465427.n5.nabble.com/Cannot-handle-Exception-thrown-from-Splitter-Expression-td3286043.html

WCF Data Services UpdateObject not working

I have a Silverlight client with a grid getting data from WCF Data Service. Works fine.
However if I want to update some changed grid row, the service data context UpdateObject is not working:
DataServiceContext.UpdateObject(MyGrid.SelectedItem);
foreach (Object item in DataServiceContext.Entities)
{
//
}
DataServiceContext.BeginSaveChanges(SaveChangesOptions.Batch, OnChangesSaved, DataServiceContext);
I just have created a loop to inspect the values for the entities items and the value is not updated at all. BeginSaveChanges works fine, but it just uses not updated values.
Any ideas how to fix that?
thanks
Right a fully flushed out SaveChanges that will show the error message if EndSaveChanges() fails, like the code sample below. Obviously you can't use the console to write out your message in silverlight, but you get the idea.
For instance, when I wrote the following sample, I found that I was getting a forbidden error, because my entity set had EntitySetRights.AllRead, not EntitySetRights.All
class Program
{
private static AdventureWorksEntities svc;
static void Main(string[] args)
{
svc =
new AdventureWorksEntities(
new Uri("http://localhost:5068/AWDataService.svc",
UriKind.Absolute));
var productQuery = from p in svc.Products
where p.ProductID == 740
select p;
var product = productQuery.First();
ShowProduct(product);
product.Color = product.Color == "Silver" ? "Gray" : "Silver";
svc.UpdateObject(product);
svc.BeginSaveChanges(SaveChangesOptions.Batch, OnSave, svc);
ShowProduct(product);
Console.ReadKey();
}
private static void ShowProduct(Product product)
{
Console.WriteLine("Id: {0} Name: {1} Color: {2}",
product.ProductID, product.Name, product.Color);
}
private static void OnSave(IAsyncResult ar)
{
svc = ar.AsyncState as AdventureWorksEntities;
try
{
WriteResponse(svc.EndSaveChanges(ar));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void WriteResponse(DataServiceResponse response)
{
if(response.IsBatchResponse)
{
Console.WriteLine("Batch Response Code: {0}", response.BatchStatusCode);
}
foreach (ChangeOperationResponse change in response)
{
Console.WriteLine("Change code: {0}", change.StatusCode);
if(change.Error != null)
{
Console.WriteLine("\tError: {0}", change.Error.Message);
}
}
}
}

Resources