I'm building a dummy app to see how it's working the pushregistry alarm, but I don't get it working.
When I run it, I don't see anything...
Any idea?
here is my code (LWUIT with SDK 2.0, S40)
package mobileapplication2;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.PushRegistry;
import javax.microedition.midlet.*;
/**
* #author S40
*/
public class Midlet extends MIDlet implements Runnable {
public Midlet() {
Display.init(this);
}
public void startApp() {
Display.getInstance().callSerially(this);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void run() {
try {
PushRegistry.registerAlarm(getClass().getName(), System.currentTimeMillis() + 100000);
Form f = new Form("Example");
f.addComponent(new Label("HOLA"));
f.show();
} catch (ClassNotFoundException ex) {
System.out.println("NOT FOUND");
ex.printStackTrace();
} catch (ConnectionNotFoundException ex) {
System.out.println("CONNECTION");
ex.printStackTrace();
}
}
}
I get it finally working
This is my final code if you want to take a look
java.util.Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.set(Calendar.MONTH, Calendar.NOVEMBER);
cal.set(Calendar.DAY_OF_MONTH, 18);
cal.set(Calendar.AM_PM, Calendar.PM);
cal.set(Calendar.HOUR_OF_DAY, 15);
cal.set(Calendar.MINUTE, 27);
cal.set(Calendar.SECOND, 0);
System.out.println("CALE " + cal.getTime().toString());
Date d = new Date();
long l = PushRegistry.registerAlarm(getClass().getName(), cal.getTime().getTime());
Related
How to generate extent report for cucumber + testng framework in such a way that on each scenario failure I can get the screen shot captured, without repeating the code with every scenario in step definition file
I have setup the Testing framework using Cucumber+Testng. However, I need extent reporting but not sure how to achieve it through testNG runner class without actually repeating the code with every scenario of step definition. So the idea is to write code in one place just like using cucumber hooks which will run for each and every scenario.
I Have already tried the approach with TestNG listener with Extent report but with this the drawback is I have to write the code every time for each and every scenario. LIke below I have ITestListnerImpl.java, ExtentReportListner and YouTubeChannelValidationStepDef where for each scenario I have to repeat the loginfo and screencapture methods
Code: ItestListerner.java
package com.testuatomation.Listeners;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
public class ITestListenerImpl extends ExtentReportListener implements ITestListener {
private static ExtentReports extent;
#Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
extent.flush();
System.out.println("Execution completed on UAT env ......");
}
#Override
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
extent = setUp();
System.out.println("Execution started on UAT env ......");
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0){
// TODO Auto-generated method stub
}
#Override
public void onTestFailure(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("FAILURE");
}
#Override
public void onTestSkipped(ITestResult arg0) {
System.out.println("SKIP");
}
#Override
public void onTestStart(ITestResult arg0) {
System.out.println("STARTED");
}
#Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("PASS-----");
}
}
ExtentReportListener. java
package com.testuatomation.Listeners;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentReportListener {
public static ExtentHtmlReporter report = null;
public static ExtentReports extent = null;
public static ExtentTest test = null;
public static ExtentReports setUp() {
String reportLocation = "./Reports/Extent_Report.html";
report = new ExtentHtmlReporter(reportLocation);
report.config().setDocumentTitle("Automation Test Report");
report.config().setReportName("Automation Test Report");
report.config().setTheme(Theme.STANDARD);
System.out.println("Extent Report location initialized . . .");
report.start();
extent = new ExtentReports();
extent.attachReporter(report);
extent.setSystemInfo("Application", "Youtube");
extent.setSystemInfo("Operating System", System.getProperty("os.name"));
extent.setSystemInfo("User Name", System.getProperty("user.name"));
System.out.println("System Info. set in Extent Report");
return extent;
}
public static void testStepHandle(String teststatus,WebDriver driver,ExtentTest extenttest,Throwable throwable) {
switch (teststatus) {
case "FAIL":
extenttest.fail(MarkupHelper.createLabel("Test Case is Failed : ", ExtentColor.RED));
extenttest.error(throwable.fillInStackTrace());
try {
extenttest.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (IOException e) {
e.printStackTrace();
}
if (driver != null) {
driver.quit();
}
break;
case "PASS":
extenttest.pass(MarkupHelper.createLabel("Test Case is Passed : ", ExtentColor.GREEN));
break;
default:
break;
}
}
public static String captureScreenShot(WebDriver driver) throws IOException {
TakesScreenshot screen = (TakesScreenshot) driver;
File src = screen.getScreenshotAs(OutputType.FILE);
String dest = "C:\\Users\\Prateek.Nehra\\workspace\\SeleniumCucumberBDDFramework\\screenshots\\" + getcurrentdateandtime() + ".png";
File target = new File(dest);
FileUtils.copyFile(src, target);
return dest;
}
private static String getcurrentdateandtime() {
String str = null;
try {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SSS");
Date date = new Date();
str = dateFormat.format(date);
str = str.replace(" ", "").replaceAll("/", "").replaceAll(":", "");
} catch (Exception e) {
}
return str;
}
}
YoutubeChannelValidationsStepDef.java
package com.testautomation.StepDef;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.GherkinKeyword;
import com.aventstack.extentreports.gherkin.model.Feature;
import com.aventstack.extentreports.gherkin.model.Scenario;
import com.testuatomation.Listeners.ExtentReportListener;
import com.testautomation.PageObjects.YoutubeChannelPage;
import com.testautomation.PageObjects.YoutubeResultPage;
import com.testautomation.PageObjects.YoutubeSearchPage;
import com.testautomation.Utility.BrowserUtility;
import com.testautomation.Utility.PropertiesFileReader;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class YoutubeChannelValidationsStepDef extends ExtentReportListener
{
PropertiesFileReader obj= new PropertiesFileReader();
private WebDriver driver;
#Given("^Open Chrome browser with URL$")
public void open_Chrome_browser_with_URL() throws Throwable
{
ExtentTest logInfo=null;
try {
test = extent.createTest(Feature.class, "Youtube channel name validation");
test=test.createNode(Scenario.class, "Youtube channel name validations");
logInfo=test.createNode(new GherkinKeyword("Given"), "open_Chrome_browser_with_URL");
Properties properties=obj.getProperty();
driver=BrowserUtility.OpenBrowser(driver, properties.getProperty("browser.name"), properties.getProperty("browser.baseURL"));
logInfo.pass("Opened chrome browser and entered url");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#When("^Search selenium tutorial$")
public void search_selenium_tutorial() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("When"), "search_selenium_tutorial");
new YoutubeSearchPage(driver).NavigateToResultPage("selenium by bakkappa n");
logInfo.pass("Searching selenium tutorial");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#When("^Search selenium tutorial \"([^\"]*)\"$")
public void search_selenium_tutorial(String searchString) throws Throwable
{
new YoutubeSearchPage(driver).NavigateToResultPage(searchString);
}
#When("^Click on channel name$")
public void click_on_channel_name() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("When"), "click_on_channel_name");
new YoutubeResultPage(driver).NavigateToChannel();
logInfo.pass("Clicked on the channel name");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#Then("^Validate channel name$")
public void validate_channel_name() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("Then"), "validate_channel_name");
String expectedChannelName="1Selenium Java TestNG Tutorials - Bakkappa N - YouTube";
String actualChannelName=new YoutubeChannelPage(driver).getTitle();
Assert.assertEquals(actualChannelName, expectedChannelName,"Channel names are not matching"); //
logInfo.pass("Validated channel title");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
System.out.println("closing browser");
driver.quit();
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
}
Your lofInfo is null, should be something like this
#Then("Open Chrome browser with URL")
public void open_Chrome_browser_with_URL() {
try {
logInfo = test.createNode(new GherkinKeyword("Then"), "open_Chrome_browser_with_URL");
//YOUR CODE HERE
logInfo.pass("Chrome opens URL");
}
catch (AssertionError | Exception e) {testStepHandle("FAIL", d, logInfo, e);
}
}
First, I'm sorry for my bad English. I'm a newbie J2ME
I wrote the below code after i watched some tutorial but it not working. I don't know what happen with it.
AnimationCanvas.java
package example;
import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;
public class AnimationCanvas extends GameCanvas implements Runnable {
private Sprite ca;
private int frameWidth = 14;
private int frameHeight = 14;
private boolean playing = true;
private int a=1;
public AnimationCanvas(){
super(true);
try {
ca = new Sprite(Image.createImage("ca.png"), frameWidth, frameHeight);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void start() {
Thread runner = new Thread(this);
runner.start();
}
public void run(){
while (playing){
drawDisplay(getGraphics());
try{
Thread.sleep(10);
} catch(Exception e){}
}
}
public void drawDisplay(Graphics g){
g.setColor(0x000000);
g.fillRect(0,0,getWidth(),getHeight());
ca.setFrame(1);
ca.paint(g);
flushGraphics();
}
public void stop(){
playing=false;
}
}
and AnimationMidlet.java
package example;
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class AnimationMidlet extends MIDlet {
private Display display;
private AnimationCanvas canvas;
public AnimationMidlet() throws IOException {
display = Display.getDisplay(this);
canvas = new AnimationCanvas();
}
private void initialize() {
// write pre-initialize user code here
// write post-initialize user code here
}
public void startMIDlet() {
// write pre-action user code here
// write post-action user code here
}
public void resumeMIDlet() {
// write pre-action user code here
// write post-action user code here
}
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
// write pre-switch user code here
Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
// write post-switch user code here
}
public Display getDisplay() {
return Display.getDisplay(this);
}
public void startApp() {
if(canvas!=null){
display.setCurrent(canvas);
canvas.start();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
canvas.stop();
}
}
and the output
Running in the identified_third_party security domain
java.io.IOException
Uncaught exception java/lang/NullPointerException.
at javax.microedition.lcdui.ImmutableImage.getImageFromStream(Image.java:968)
at javax.microedition.lcdui.ImmutableImage.(Image.java:939)
at javax.microedition.lcdui.Image.createImage(Image.java:313)
at example.AnimationCanvas.(AnimationCanvas.java:25)
at example.AnimationMidlet.(AnimationMidlet.java:25)
at java.lang.Class.runCustomCode(+0)
at com.sun.midp.midlet.MIDletState.createMIDlet(+34)
Thanks for your reading!
Good Evening to everybody!
i have the following trouble: i'm tryin to measure the decibels(of the voice) using the microphone of my mobile phone but dont know why it doesn´t work!!! any suggestions??thanks for help!!
The program is this:
`package com.dani;
import java.io.IOException;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class Pruebita2 extends Activity {
TextView TextView;
StringBuilder builder=new StringBuilder();
MediaRecorder mRecorder;
double powerDb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pruebita2);
TextView=new TextView(this);
setContentView(TextView);
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
try {
mRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRecorder.start();
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 0;
}
powerDb = 20 * log10(getAmplitude() / referenceAmp);//obtain the DECIBELS
}`
this code works for me:
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class Noise extends Activity {
TextView mStatusView;
MediaRecorder mRecorder;
Thread runner;
private static double mEMA = 0.0;
static final private double EMA_FILTER = 0.6;
final Runnable updater = new Runnable(){
public void run(){
updateTv();
};
};
final Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noiselevel);
mStatusView = (TextView) findViewById(R.id.status);
if (runner == null)
{
runner = new Thread(){
public void run()
{
while (runner != null)
{
try
{
Thread.sleep(1000);
Log.i("Noise", "Tock");
} catch (InterruptedException e) { };
mHandler.post(updater);
}
}
};
runner.start();
Log.d("Noise", "start runner()");
}
}
public void onResume()
{
super.onResume();
startRecorder();
}
public void onPause()
{
super.onPause();
stopRecorder();
}
public void startRecorder(){
if (mRecorder == null)
{
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
try
{
mRecorder.prepare();
}catch (java.io.IOException ioe) {
android.util.Log.e("[Monkey]", "IOException: " +
android.util.Log.getStackTraceString(ioe));
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " +
android.util.Log.getStackTraceString(e));
}
try
{
mRecorder.start();
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " +
android.util.Log.getStackTraceString(e));
}
//mEMA = 0.0;
}
}
public void stopRecorder() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public void updateTv(){
mStatusView.setText(Double.toString((getAmplitudeEMA())) + " dB");
}
public double soundDb(double ampl){
return 20 * Math.log10(getAmplitudeEMA() / ampl);
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 0;
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
return mEMA;
}
}
I am creating simple midlet for Bluetooth communication with server but I can't get it to work on my phone, when I Try to run it in Eclipse/Emulator everything works fine, but on the phone I get "Cannot create MIDlet instance: java.lang.ClassNotFoundException"
I saw somewhere that this exception is mostly path related, but I don't have any external jars or multiple packages.
Here is the code:
package j2meclient;
import java.io.OutputStream;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class J2MEClientMidlet extends MIDlet implements CommandListener,
Runnable {
Display d;
Command cmExit, cmConnect;
Form f;
Thread t;
String connString;
public J2MEClientMidlet() {
f = new Form("Client");
cmExit = new Command("Exit", Command.EXIT, 1);
cmConnect = new Command("Connect", Command.ITEM, 2);
f.addCommand(cmExit);
f.addCommand(cmConnect);
f.setCommandListener(this);
}
public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmConnect) {
t.start();
}
}
public void run() {
try {
LocalDevice local = LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
connString = agent.selectService(new UUID(
"86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
} catch (Exception e) {
}
if (connString != null) {
try {
StreamConnection conn = (StreamConnection) Connector
.open(connString);
OutputStream out = conn.openOutputStream();
Thread.sleep(2000);
out.write("Hello, World".getBytes());
out.close();
conn.close();
f.append("Message sent correctly");
} catch (Exception ex) {
f.append("IOException: ");
f.append(ex.getMessage());
}
} else {
f.append("Unable to locate service");
}
}
}
JAD;
MIDlet-1: J2MEClient,,J2MEClient
MIDlet-Jar-Size: 2254
MIDlet-Jar-URL: BTClient.jar
MIDlet-Name: BTClient Midlet Suite
MIDlet-Vendor: Midlet Suite Vendor
MIDlet-Version: 1.0.0
MicroEdition-Configuration: CLDC-1.1
MicroEdition-Profile: MIDP-2.0
Any ideas why I can't run this on phone?
Your class file for the midlet is named J2MEClientMidlet but on the jad file it is defined as J2MEClient. Midlet class file name must match the definition on jad to run successfully from jad.
I have a TextField in a form:
private TextField cc1F = new TextField("", "", 250, TextField.ANY);
Once click button OK, then set cc1F field's Constraints to:
cc1F.setConstraints(TextField.UNEDITABLE);
then I am getting an exception:
java.lang.NullPointerException
at com.sun.midp.lcdui.DefaultInputMethodHandler.setConstraints(+63)
at javax.microedition.lcdui.TextField$InputMethodClientImpl.setConstraints(+20)
at javax.microedition.lcdui.TextField.setConstraints(+37)
at com.zousys.j2me.zmail.gui.view.HeaderView.menuAction(+146)
.....................................
Anyone know this?
The example of code was tested with simulator WTK 3.0 and device Samsung Chat
http://www.gsmarena.com/samsung_ch#t_527-4096.php and the test passed. :)
I think that the problem is caused by device model or the object cc1F is null.
import java.io.UnsupportedEncodingException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class TextFieldMIDlet extends MIDlet implements CommandListener {
private Form form;
private Command cmdExit;
private Command cmdSetConstraints;
private Display display;
private TextField textField;
public TextFieldMIDlet() {
form = new Form("Testing constraints");
cmdExit = new Command("Exit",Command.EXIT, 1);
cmdSetConstraints = new Command("Set Constraints",Command.ITEM, 1);
textField = new TextField("", "", 250, TextField.ANY);
form.addCommand(cmdExit);
form.addCommand(cmdSetConstraints);
form.append(textField);
display = Display.getDisplay(this);
form.setCommandListener(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
this.notifyDestroyed();
} else if (c == cmdSetConstraints) {
try {
System.out.println("Set...");
if (textField.getConstraints() == TextField.UNEDITABLE) {
textField.setConstraints(TextField.ANY );
} else {
textField.setConstraints(TextField.UNEDITABLE );
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}