How to do Receipt printing using codenameone - codenameone

I would like my codenameone based android application to print receipts using a rego bluetooth printer. Is there any plugin / extension that is able to do this or i might have to go the cnlib route

There is a bluetooth extension for codenameone since 2016. I am not sure if it has been updated, but you can check it out here https://www.codenameone.com/blog/bluetooth-support.html It gives a small test code to get started. Search for the CNIBluetooth extension, add it to your project then refresh libs.
final Bluetooth bt = new Bluetooth();
Form main = new Form("Bluetooth Demo");
main.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
main.add(new Button(new Command("enable bluetooth") {
#Override
public void actionPerformed(ActionEvent evt) {
try {
if (!bt.isEnabled()) {
bt.enable();
}
if (!bt.hasPermission()) {
bt.requestPermission();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
main.add(new Button(new Command("initialize") {
#Override
public void actionPerformed(ActionEvent evt) {
try {
bt.initialize(true, false, "bluetoothleplugin");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));

Related

Infinite progress hide complety the screen on android

on Android in a Form with a browserComponent the Infinite progress hide complety the screen and can't see the content, on IOS works fine.
If the form has no a BrowserComponent works fine in Android and IOS and the screen goes to dark but we can see the content.
I attach a sample code (only the start method)
public void start() {
if(current != null){
current.show();
return;
}
Form hi2 = new Form("No browser Form", BoxLayout.y());
hi2.add(new Button(new Command("Show Infinite Progress") {
#Override
public void actionPerformed(ActionEvent evt) {
try {
Dialog ip = new InfiniteProgress().showInfiniteBlocking();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ip.dispose();
}
}).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}));
hi2.add(new Label("No browser Form"));
hi2.add(new Button(new Command("show browser Form") {
#Override
public void actionPerformed(ActionEvent evt) {
try {
Form hi = new Form("browser Form");
hi.setLayout(new BorderLayout());
BrowserComponent browserComponent = new BrowserComponent();
browserComponent.setURL("https://www.codenameone.com/");
hi.add(BorderLayout.CENTER, browserComponent);
hi.add(BorderLayout.SOUTH, new Button(new Command("Show Infinite Progress") {
#Override
public void actionPerformed(ActionEvent evt) {
try {
Dialog ip = new InfiniteProgress().showInfiniteBlocking();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ip.dispose();
}
}).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}));
hi.show();
} catch (Exception ex) {
Dialog.show("Error", ex.getMessage(), "OK", null);
ex.printStackTrace();
}
}
}));
hi2.show();
}
InfiniteProgress creates a Dialog which shows it in the center but effectively blocks input all around. BrowserComponent doesn't work well with dialogs because the background of a dialog needs to be "painted" and isn't the real underlying Form.
Normally the workaround is to use an InteractionDialog. You can also use the LayeredPane to place the InfiniteProgress and even color it appropriately so it will "look" the same. Reproducing the blocking behavior is harder though. I'm not sure if you'll be able to do that since native widgets handle their own events. It's pretty easy to block input from Codename One components but by the time you get the event it might have been processed by the native widget.
The only workaround for that aspect I can think of is doing that part in JavaScript.

CodenameOne MapContainer Zoom Level

I am using the MapContainer(cn1lib). so in android devices low relsolution the zoom works fine. But in android devices high resolution the zoom not works fine. The zoom in stay far. i attach a screen with the to max zoom in, it is a bug or i'm wrong?
SCREENSHOT
GUI-DESIGN
public class StateMachine extends StateMachineBase {
MapContainer mapContainer;
public StateMachine(String resFile) {
super(resFile);
// do not modify, write code in initVars and initialize class members there,
// the constructor might be invoked too late due to race conditions that might occur
}
/**
* this method should be used to initialize variables instead of the
* constructor/class scope to avoid race conditions
*/
protected void initVars(Resources res) {
}
#Override
protected void beforeShow(Form f) {
try {
this.mapContainer.setShowMyLocation(true);
this.mapContainer.zoom(new Coord(20.640086, -103.432207), 17);
this.mapContainer.setCameraPosition(new Coord(20.640086, -103.432207));
this.mapContainer.addMarker(
EncodedImage.createFromImage(fetchResourceFile().getImage("pin.png"), false),
new Coord(20.640086, -103.432207),
"Hi marker", "Optional long description",
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Dialog.show("Marker Clicked!", "You clicked the marker", "OK", null);
}
}
);
this.mapContainer.addPointerDraggedListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
mapContainer.clearMapLayers();
mapContainer.addMarker(EncodedImage.createFromImage(fetchResourceFile().getImage("pin.png"), false), mapContainer.getCameraPosition(), "Hi marker", "Optional long description", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Dialog.show("Marker Clicked!", "You clicked the marker", "OK", null);
}
});
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
super.beforeShow(f); //To change body of generated methods, choose Tools | Templates.
}
#Override
protected Component createComponentInstance(String componentType, Class cls) {
if (cls == MapComponent.class) {
this.mapContainer = new MapContainer();
return this.mapContainer;
}
return super.createComponentInstance(componentType, cls); //To change body of generated methods, choose Tools | Templates.
}
}
That is a MapComponent not a native map, so it uses the old open street maps support and relatively simple map rendering even on the device. We have support for native google maps which isn't exposed in the GUI builder but you can add it thru code.
This will embed the actual native GUI into place which will both look and feel better on the device although it will look the same on the simulator.

Test Automation Framework for Web Application using Java

I am beginning to write a Test Automation Framework in Java (language that I am comfortable with) for my Web Application. Currently, it is entirely tested on UI. No Backend / API testing in near sight.
I plan to use Selenium Web Driver. This framework will support both Functional/Integration and Performance testing.
I am building with Open Source Solutions for the first time (over using tools like LoadRunner) and my needs are this framework will work with Continuous Integration tools like Jenkins/Hudson and an in-house Test Management tool for reporting results.
I searched for this specific scenario but could not find one. I know there will be numerous integrations, plug-ins, etc... that needs to be built. My question is can you provide some pointers (even good reads is OK) towards beginning to build this framework with Open source solutions ?
Selenium will allow you to automate all your web (browsers) actions
automations.
Junit/TestNG as the testing framework,
including their default reports system
Maven for the project
management and lifecycle (including test phase with surefire
plugin)
Jenkins is a good integration tool that will easily
run the setup above
Good luck!
I am giving here framework functions which reduces code very much
public TestBase() throws Exception{
baseProp = new Properties();
baseProp.load(EDCPreRegistration.class.getResourceAsStream("baseproperties.properties"));
// Firefox profile creation
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.type", ProxyType.AUTODETECT.ordinal());
profile.setPreference("browser.cache.disk.enable", false);
profile.setPreference("network.proxy.http", "localhost");
profile.setPreference("network.proxy.http_port",8080);
driver = new FirefoxDriver(profile);
//System.setProperty("webdriver.ie.driver","E:\\Phyweb Webdriver\\IEDriverServer.exe");
//driver = new InternetExplorerDriver();
driver.manage().window().maximize();
}
//To find WebElement by id
public static WebElement FindElement(String id)
{
try
{
webElement= driver.findElement(By.id(id));
}
catch(Exception e)
{
Print(e);
}
return webElement;
}
//To find WebElement by name
public static WebElement FindElementByName(String name)
{
try
{
webElement= driver.findElement(By.name(name));
}
catch(Exception e)
{
Print(e);
}
return webElement;
}
//To find WebElement by Class
public static WebElement FindElementByClass(String classname)
{
try
{
webElement= driver.findElement(By.className(classname));
}
catch(Exception e)
{
Print(e);
}
return webElement;
}
//To get data of a cell
public static String GetCellData(XSSFSheet sheet,int row,int col)
{
String cellData = null;
try
{
cellData=PhyWebUtil.getValueFromExcel(row, col, sheet);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return cellData;
}
//To click a button using id
public static void ClickButton(String id,String label)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
PrintMessage(label+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//To click a button using class
public void ClickButtonByClass(String classname,String label)
{
try
{
WebElement webElement= FindElementByClass(classname);
Snooze();
webElement.click();
PrintMessage(label+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//To enter data into Textbox
public String editTextField(int rownum, int celnum,WebElement element ,XSSFSheet sheet,String Label)
{
XSSFRow row = sheet.getRow(rownum);
XSSFCell Cell = row.getCell(celnum);
String inputValue = Cell.getStringCellValue().trim();
element.clear();//To clear contents if present
try
{
element.sendKeys(inputValue);
String elementVal=element.toString();
if(elementVal.contains("password"))
{
PrintMessage("Password is entered");
}
else
{
PrintMessage("Value entered for "+Label+" is "+inputValue);
}
}
catch(Exception e){
Print(e);
//cv.verifyTrue(false, "<font color= 'red'> Failed due to : </font> "+e.getMessage());
}
return inputValue;
}
//To enter data into Textbox
public String editTextFieldDirect(WebElement element ,String text,String label)
{
element.clear();//To clear contents if present
try
{
element.sendKeys(text);
String elementVal=element.toString();
if(elementVal.contains("password"))
{
PrintMessage("Password is entered");
}
else
{
PrintMessage("Value entered for "+label+" is "+text);
}
}
catch(Exception e){
Print(e);
//cv.verifyTrue(false, "<font color= 'red'> Failed due to : </font> "+e.getMessage());
}
return text;
}
//To select Radio button
public void ClickRadioButton(String id)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
text=webElement.getText();
PrintMessage(text+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//To select Link
public void ClickLink(String id,String label)
{
try
{
ClickButton(id,label);
}
catch(Exception e)
{
Print(e);
}
}
//To Click an Image button
public void ClickImage(String xpath)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
text=GetText(webElement);
PrintMessage(text+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//Select a checkbox
public void CheckboxSelect(String id,String label)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
PrintMessage("Checkbox "+label+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//To select value in Combobox
public void SelectData(String id,String label,String cellval)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
String elementStr=webElement.toString();
int itemIndex=elementStr.indexOf("value");
if(itemIndex>-1)
{
int endIndex=elementStr.length()-3;
String item=elementStr.substring(itemIndex+7, endIndex);
if(cellval=="0")
{
PrintMessage(item+" is selected for "+label);
}
else
{
PrintMessage(cellval+" "+label+" is selected");
}
}
else
{
PrintMessage(cellval+" is selected for "+label);
}
}
catch(Exception e)
{
Print(e);
}
}
//To check if WebElement with id exists
public static boolean isExists(String id)
{
boolean exists = false;
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
try
{
exists=driver.findElements( By.id(id) ).size() != 0;
}
catch (Exception e)
{
Print(e);
}
if(exists==true)
return true;
else
return false;
}
//To check if WebElement with name exists
public static boolean isExistsName(String name)
{
boolean exists = false;
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
try
{
exists=driver.findElements( By.name(name) ).size() != 0;
}
catch (Exception e)
{
if(e.getMessage().contains("InvalidSelectorError"))
{
System.out.println("");
}
else
Print(e);
}
if(exists==true)
return true;
else
return false;
}
//Explicit wait until a element is visible and enabled using id
public void ExplicitlyWait(String id)
{
try
{
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id(id)));
}
catch(Exception e)
{
Print(e);
}
}
//Explicit wait until a element is visible and enabled using classname
public void ExplicitlyWaitByClass(String classname)
{
try
{
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.className(classname)));
}
catch(Exception e)
{
Print(e);
}
}
//Explicit wait until a element is visible and enabled using id
public void ExplicitlyWaitSpecific(int sec,String id)
{
try
{
WebElement myDynamicElement = (new WebDriverWait(driver, sec))
.until(ExpectedConditions.presenceOfElementLocated(By.id(id)));
}
catch(Exception e)
{
Print(e);
}
}
//Snooze for 10 seconds
public static void Snooze()
{
try
{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
catch(Exception e)
{
Print(e);
}
}
//Snooze for Secs
public static void SnoozeSpecific(int seconds)
{
try
{
driver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
}
catch(Exception e)
{
Print(e);
}
}
//Sleep for milliSeconds
public static void Sleep(int milisec) throws InterruptedException
{
Thread.sleep(milisec);
}
//To get text using text()
public static String GetText(WebElement element)
{
try
{
text=element.getText();
}
catch(Exception e){
Print(e);
}
return text;
}
//To get text using getAttribute("value")
public static String GetTextAttribute(WebElement element)
{
try
{
text=element.getAttribute("value");
}
catch(Exception e){
Print(e);
}
return text;
}
//To Print error messages to both Console and Results file
public static void Print(Exception e)
{
Reporter.log("Exception is :"+e.getMessage());
System.out.println(e);
}
//To Print messages to both Console and Results file
public static void PrintMessage(String str)
{
Reporter.log(str);
System.out.println(str);
}
//To Print Blank row
public static void BlankRow()
{
Reporter.log(" ");
System.out.println(" ");
}
//To Print Sub header
public static void Header(String str)
{
BlankRow();
Reporter.log("***********************"+str+" Verifications***********************");
System.out.println("***********************"+str+" Verifications***********************");
BlankRow();
}
//To Print Sub header
public static void SubHeader(String str)
{
BlankRow();
Reporter.log("-----------------------"+str+" Verifications-----------------------");
System.out.println("-----------------------"+str+" Verifications-----------------------");
BlankRow();
}
So long as you have a command line for kicking off your framework and you report back using the xunit log format then you should be good for integration with any number of Continuous integration frameworks.
Your trade off on running a browser instance under load will be fewer virtual users per host and a very careful examination of your load generator resources under load. Don't forget to include monitoring API in your framework for system metrics under load and an auto evaluation engine related to SLA metrics acceptance to determine pass of fail criteria under load at a given load point.
We are begining to develop something very related to your needs; Java, Webdriver, Jenkins, Maven, etc. We are quite new to automation here, but still have good Java ressources.
We are builing our framework based on Tarun Kumar from www.seleniumtests.com.
He's got a lot of good videos from Youtube (sounds quality is not so good), and he manage to create something very user friendly, using PageObjects Pattern.
If you don't have any clue where to start, I would start from there.
Good luck!
I created a java library on the top of selenium which simplifies test automation of a website. It has an implicit waiting mechanism and is easy to use:
https://github.com/gartenkralle/web-ui-automation
Example:
import org.junit.Test;
import org.openqa.selenium.By;
import common.UserInterface;
import common.TestBase;
public class Google extends TestBase
{
private final static String GOOGLE_URL = "https://www.google.com/";
private final static By SEARCH_FIELD = By.xpath("//input[#id='lst-ib']");
private final static By AUTO_COMPLETION_LIST_BOX = By.xpath("//*[#id='sbtc']/div[2][not(contains(#style,'none'))]");
private final static By SEARCH_BUTTON = By.xpath("//input[#name='btnK']");
#Test
public void weatherSearch()
{
UserInterface.Action.visitUrl(GOOGLE_URL);
UserInterface.Action.fillField(SEARCH_FIELD, "weather");
UserInterface.Verify.appeared(AUTO_COMPLETION_LIST_BOX);
UserInterface.Action.pressEscape();
UserInterface.Action.clickElement(SEARCH_BUTTON);
}
}
Selenium WebDriver is surely a tool for UI automation and we use it extensively to do cross Browser testing on Cloud Solutions like Browser Stack.
Our use case let us build an open source Framework "omelet" built in Java using TestNG as test runner , which takes care of almost everything related to web-testing and leaves us to actually automated application rather than thinking about reports , parallel run and CI integration etc.
Suggestion, Contribution always welcome :)
Documentation over here and
Github link over here
Do remember to checkout 5 min tutorial on website
For Functional Regression test:
Selenium Webdriver - Selenium a Web based automation tool that automates anything and everything available on a Web page. you use Selenium Webdriver with JAVA.
Watij- Web Application Testing in Java
Automates functional testing of web applications through real web browsers.
TestProject - It supports for testing both web and Mobile (Android & iOS).
For Non-functional test:
Gatling- For performance testing and Stress testing
Apache JMeter - For Volume, Performance, Load & Stress testing
CI tool:
Jenkins- Jenkins provides continuous integration services for software development.
For Functional Regression test:
TestProject
Selenium
Cucumber : It's a BDD tool
For Non-functional: Performance and Load testing:
JMeter
Note: TestComplete is a very good commercial tool.

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

Sending SMS from BlackBerry Simulator

I'm developing a BlackBerry Application where I should send Text SMS from BlackBerry Device.
As I'm new to Blackberry, started few days back I'm unable to proceed.
Can anyone Help with providing code snippets for send SMS from BlackBerry Device or Simulator?
Thanks in Advance.
Suresh.
public static void sendSMS(final String no, final String msg) {
// try {
new Thread() {
public void run() {
boolean smsSuccess = false;
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
// / send successfully
smsSuccess = true;
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
smsSuccess = false;
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector
.open("sms://" + no);
TextMessage tmsg = (TextMessage) conn
.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
conn.send(tmsg);
smsSuccess = true;
} catch (Exception e) {
smsSuccess = false;
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
if(smsSuccess)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("success");
}
});
}else
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("failure");
}
});
}
}
}.start();
}
Check out the the above code function .... to send SMS from Blackberry
You haven't specified what language you are developing in, but if you are developing in java and, if you are using Eclipse for your development with the Blackberry Java plugins, you will find a wealth of sample applications in the plugins folder hierarchy. The actual location will depend on where you have installed Eclipse, but e.g. on my machine they are at: C:\Program Files\Eclipse\eclipse 3.6.2 BlackBerry\plugins\net.rim.ejde.componentpack7.0.0_7.0.0.33\components\samples\com\rim\samples\device for the OS7 samples. Similar samples will exist for the different OS plugins you have installed.
There is a long standing sample in most OS sample sets called smsdemo which should give you all the code you need. Even if you are not developing in java, this sample should give you an indication of the path you need to take to fulfil your requirement.

Resources