Missing something to get values from mysql using java in an Xpage - xpages

I wrote a java class to get values from a Mysql db in an Xpage. The code is,
package com.vijay;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
String name;
String caty;
float price;
private Connection con;
private Statement st;
private ResultSet rs;
public String test(){
return "This is a class with just a single method";
}
public Test(){
}
public void db(){
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay","root","");
st=con.createStatement();
st.executeQuery("select * from prodet;");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.getMethod();
}
public void getMethod(){
try {
while(rs.next()){
name=rs.getString("name");
price=rs.getFloat("price");
caty = rs.getString("caty");
}
con.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I put a label in the page and Computed its value with SSJS
var v = new com.vijay.Test();
v.db();
v.getMethod();
return v.name;
Even i put those two methods in the constructor too. But doesn't work.
Where do i miss?

I think you must declare your field name as public.
public class Test {
public String name;
Or much better, create a getter function:
public class Test {
private String name;
public String getName() {
return name;
}
And then change your SSJS code to return v.getName().
By the way, there are two datasources in Extension Library (JDBCRowSet and JDBCQuery) which might be of interest to you.

Related

How to generate extent report for cucumber + testng framework

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

j2me sprite not working

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!

What does Post invalidate method do in Thread class

This is my code:
package com.example.analogclock;
import android.view.View;
public class MyThread implements Runnable {
private View view;
public MyThread(View v){
view = v;
}
public void run() {
while(true){
try {
Thread.sleep(1000);
view.postInvalidate();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Java SwingWorker not updating reference to object from GUI

So I load some data from Database and use SwingWorker for it.
public class LoadFromDatabase extends SwingWorker<ArrayList<Ucet>, GuiUpdate>{
private ArrayList<Ucet> ucty;
private JLabel lblStav;
private File dbPath;
private JProgressBar progress;
private int pocetUctov;
private JButton btnLoad;
private JButton btnStart;
public LoadFromDatabase(ArrayList<Ucet> ucty,JLabel lblStav,File dbpath,JProgressBar progress, JButton btnLoad,JButton btnStart){
this.ucty=ucty;
this.lblStav=lblStav;
this.dbPath=dbpath;
this.progress=progress;
this.btnLoad=btnLoad;
this.btnStart=btnStart;
}
#Override
protected ArrayList<Ucet> doInBackground() throws Exception {
String sqlLoadUcty="SELECT email,password FROM members";
ArrayList<Ucet> ucty2=new ArrayList<>();
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:"+dbPath.getPath());
Statement stmt = conn.createStatement();
stmt.setQueryTimeout(30);
ResultSet rs = stmt.executeQuery(sqlLoadUcty);
GuiUpdate gd=new GuiUpdate(GuiUpdate.GuiType.setStartLoading);
gd.setValue(0);
publish(gd);
pocetUctov=rs.getFetchSize();
gd=new GuiUpdate(GuiUpdate.GuiType.setMaxValue);
gd.setValue(pocetUctov);
publish(gd);
int counter=0;
while (rs.next()){
Ucet uct=new Ucet(
rs.getString("email"),
rs.getString("password")
);
gd=new GuiUpdate(GuiUpdate.GuiType.setValue);
gd.setValue(counter);
publish(gd);
ucty2.add(uct);
}
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException ex) {
System.out.println("Problem= "+ex);
} catch (SQLException ex) {
System.out.println("Problem= "+ex);
}
return ucty2;
}
#Override
public void process(List<GuiUpdate> update){
for (GuiUpdate guiUpdate : update) {
if (guiUpdate.getToDo()==GuiUpdate.GuiType.setStartLoading) {
lblStav.setText("Loading ...");
progress.setVisible(true);
} else if (guiUpdate.getToDo()==GuiUpdate.GuiType.setMaxValue) {
progress.setMaximum(guiUpdate.getValue());
pocetUctov=guiUpdate.getValue();
progress.setMinimum(0);
} else if (guiUpdate.getToDo()==GuiUpdate.GuiType.setValue) {
progress.setValue(guiUpdate.getValue());
}
}
}
#Override
public void done(){
progress.setVisible(false);
btnLoad.setEnabled(true);
try {
ucty=get();
} catch (InterruptedException ex) {
System.out.println("Problem= "+ex);
} catch (ExecutionException ex) {
System.out.println("Problem= "+ex);
}
if (ucty!=null && ucty.size()>0) {
btnStart.setEnabled(true);
lblStav.setText("Loaded "+ucty.size()+" accounts.");
}
}
}
This is whole SwingWorker. I basicly load data from DB and update progress bar.
Once loaded then done() method is called where reference to created ArrayList in doInbackground is set to arraylist which comes from mainGUI and some buttons are allowed and disallowed.
This is how I call SwingWorker from Gui:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileDb=new JFileChooser();
int returnVal=fileDb.showOpenDialog(this);
if (returnVal==JFileChooser.APPROVE_OPTION) {
databasePath=fileDb.getSelectedFile();
jButton4.setEnabled(false);
execurtor.execute(new LoadFromDatabase(naciatneUcty, jLabel9, databasePath, jProgressBar1, jButton4,jButton1));
}
}
This works great ,even if debug last line of code in SwingWorker done() I can clearly see that ArrayList ucty contians data from databse.
Once back to main gui , ArrayList naciatneUcty is still null.
But it should not be since I am sending it to SwingWorker where its reference should be updated...
Where is the problem ,why reference is not updated at all?
Java references are passed by value, so when you execute ucty = get() the reference inside the swingworker is changed, but that isn't going to update the reference for naciatneUcty. You'd be better off instantiating naciatneUcty before running the swingworker, have doInBackground() return void, scrap utcy2 and then just grab utcy in the done() method.

ASM ByteCode Instrumentation , Which Method is Executed

I am using ASM Bytecode Library to instrument Java Classes using pre-main.
How do we get the name of the method executed?
Thanks in advance...
In short, there is a name parameter on corresponding visit*() method call. You'll have to produce a more specific example to get more detailed answer.
Attached my Code for your reference
package com.eg.agent;
import java.lang.instrument.Instrumentation;
public class Agent {
private Agent(Instrumentation instrumentation){
}
public static void premain(String agentArgs, Instrumentation inst)
{
EgClassFileTransformer egClassFileTransformer =
new EgClassFileTransformer (agentArgs , inst);
}
}
package com.eg.agent;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.objectweb.asm.ClassReader;
public class EgClassFileTransformer implements ClassFileTransformer {
protected String agentArgString = "";
protected Instrumentation instrumentation;
public EgClassFileTransformer(String agentArgs, Instrumentation inst){
agentArgString = agentArgs;
instrumentation = inst;
instrumentation.addTransformer(this);
}
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException
{
//System.out.println("ClassName :"+className);
InputStream in = loader.getResourceAsStream(className.replace('.', '/') + ".class");
try{
ClassReader classReader=new ClassReader(in);
String superClassName = classReader.getSuperName();
String[] interfaces = classReader.getInterfaces();
if(interfaces!=null && interfaces.length > 0){
for(int k=0;k<interfaces.length;k++){
String inface = interfaces[k];
System.out.println(" \t interface :"+inface);
}
}
//System.out.println("superClassName :"+superClassName);
ArrayList thisList = new ArrayList();
thisList.add(superClassName);
ArrayList superList = printSuperClassNames(superClassName , thisList);
System.out.println("className :"+className +" ==>"+ " superList :"+superList);
} catch (IOException e) {
//e.printStackTrace();
System.out.println("[EXECEPTION] ..."+className);
}
return null;
}
public static ArrayList printSuperClassNames(String className, ArrayList list)
{
ClassReader cr=null;
try {
cr = new ClassReader(className);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String superName = cr.getSuperName();
//System.out.println("[superName]"+superName);
if(superName!=null && !superName.equals("java/lang/Object"))
{
list.add(superName);
String superClass = superName.replace('.', '/');
printSuperClassNames(superClass, list);
}
return list;
}
}

Resources