NullPointer Exception when populating JTable - nullpointerexception

I get following error when I try to load data into JTable.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.tfc.cheque.handle.dao.impl.ChequeDAOImpl.getCheques(ChequeDAOImpl.java:23)
at com.tfc.cheque.handle.ui.ChequeGUI.(ChequeGUI.java:38)
at TestChequeDAO$1.run(TestChequeDAO.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
this is my main class:
public class TestChequeDAO {
public static void main(String[] args) throws SQLException{
DBConnection connection = new DBConnection();
connection.setUser("");
connection.setPswd("");
ChequeDAOImpl dao = new ChequeDAOImpl();
dao.setConnection(connection);
List<Cheque> cheques = dao.getCheques();
EventQueue.invokeLater(new Runnable() {
public void run() {
ChequeGUI cgui;
try {
cgui = new ChequeGUI();
cgui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cgui.pack();
cgui.setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
this is my gui class:
public class ChequeGUI extends JFrame {
JTable guiTable = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"Name","Amount","Date"});
public ChequeGUI() throws SQLException {
guiTable.setModel(model);
add(new JScrollPane(guiTable));
//Populate Table
ChequeDAOImpl chqdi = new ChequeDAOImpl();
List<Cheque> cheques = chqdi.getCheques();
for(Cheque cq : cheques){
model.addRow(new Object[]{cq.getName(),cq.getAmount(),cq.getDate()});
}
}
}
this is where i have written the query:
public class ChequeDAOImpl implements ChequeDAO{
//DB2 connection
private DBConnection dbConnection;
public List<Cheque> getCheques() throws SQLException{
List<Cheque> cheques = new ArrayList<Cheque>();
Connection connection = dbConnection.getConnection();
try{
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from LIB.DATA");
while(result.next()) {
Cheque cheque = new Cheque();
cheque.setAmount(result.getDouble("AMOUNT"));
cheque.setDate(result.getDate("DATE"));
cheque.setName(result.getString("NAME"));
cheques.add(cheque);
for(Cheque chq : cheques){
System.out.println("Name: " + result.getString("NAME"));
System.out.println("Amount: " + result.getDouble("AMOUNT"));
System.out.println("Date: " + result.getDate("DATE"));
}
}
}catch(Exception exception){
exception.printStackTrace();
}finally{
connection.close();
}
return cheques;
}
public DBConnection getConnection() {
return dbConnection;
}
public void setConnection(DBConnection connection) {
this.dbConnection = connection;
}
}

You need to initialize DBConnection dbConnection, and that much depends on a way how your application works

Related

I am getting java.lang.NullPointerException on onTestFailure to get the screenshot on extent report

This was not givving any issue if I call the function by creating the new object and passing the driver but when I made changes to each function to return the object of the next class in page object. then this issue is started appearing.
Listeners file
`
import java.io.IOException;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import MobileApp.BillGenratorMobileApp2.Utils.ReusableMethods;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
public class Listeners extends BaseClass implements ITestListener{
AndroidDriver driver;
ExtentReports extent= getExtentReporters.gettreporterObject();
ExtentTest test;
#Override
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub
ITestListener.super.onTestStart(result);
test= extent.createTest(result.getMethod().getMethodName());
}
#Override
public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub
ITestListener.super.onTestSuccess(result);
test.log(Status.PASS ,"Test Pass");
}
#Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
ITestListener.super.onTestFailure(result);
test.fail(result.getThrowable());
try {
driver = (AndroidDriver) result.getTestClass().getRealClass().getField("driver").get(result.getInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
test.addScreenCaptureFromPath(getScreenshotPath(result.getMethod().getMethodName(),driver), result.getMethod().getMethodName());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
`
Base Class file
`
public class BaseClass {
protected AndroidDriver driver;
WebDriver webdriver1;
AppiumDriverLocalService service;
ExtentReports extent;
public String CustomerServiceNo;
public String url;
public final String[] verifyContentInPDf1 = null;
public Properties propConnection = new Properties();
public Dashboard dashboard;
public SideNevigationMenu SideNevigationMenu;
public ReusableMethods ReusableMethods;
public UtiltiyFormStep1 utilityFormsStep1;
public UtilityFormStep2 utilityFormsStep2;
public UtiltiyFormStep3 utilityFormsStep3;
public FlashScreen flashscreen;
public LoginScreen loginScreen;
public W2FormStep1 W2FormStep1;
public W2FormStep2 W2FormStep2;
public W2FormStep3 W2FormStep3;
public W2FormStep4 W2FormStep4;
public W2FormStep5 W2FormStep5;
public W2FormStep6 W2FormStep6;
#BeforeTest
public void configuration() throws IOException {
FileInputStream inputstreemconnection = new FileInputStream(
System.getProperty("user.dir") + "\\src\\main\\java\\MobileApp\\dataResource\\Connection.properties");
FileInputStream inputstreemLoginData = new FileInputStream(
System.getProperty("user.dir") + "\\src\\main\\java\\MobileApp\\dataResource\\LoginData.properties");
FileInputStream inputstreemUtilityData = new FileInputStream(
System.getProperty("user.dir") + "\\src\\main\\java\\MobileApp\\dataResource\\UtilityData.properties");
FileInputStream inputstreemCommonData = new FileInputStream(
System.getProperty("user.dir") + "\\src\\main\\java\\MobileApp\\dataResource\\CommonData.properties");
FileInputStream inputstreemW2Data = new FileInputStream(
System.getProperty("user.dir") + "\\src\\main\\java\\MobileApp\\dataResource\\W2Data.properties");
propConnection.load(inputstreemconnection);
propConnection.load(inputstreemLoginData);
propConnection.load(inputstreemUtilityData);
propConnection.load(inputstreemCommonData);
propConnection.load(inputstreemW2Data);
String port = propConnection.getProperty("Port");
service = new AppiumServiceBuilder()
.withAppiumJS(new File(
"C:\\Users\\Marquee\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js"))
.withIPAddress(propConnection.getProperty("IPAddress")).usingPort(Integer.parseInt(port)).build();
service.start();
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "12");
desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "uiautomator2");
desiredCapabilities.setCapability("appPackage", "com.example.billgenerator");
desiredCapabilities.setCapability("appActivity", "com.example.billgenerator.MainActivity");
// UiAutomator2Options options = new UiAutomator2Options();
// options.setPlatformName("Android");
// options.setPlatformVersion("12");
// options.setDeviceName("Pixel_2_API_31");
// options.setAutomationName("uiautomator2");
// options.setAppPackage("com.example.billgenerator");
// options.setAppActivity("com.example.billgenerator.MainActivity");
// OR use 127.0.0.1:4723
driver = new AndroidDriver(new URL("http://0.0.0.0:4723"), desiredCapabilities);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
try {
FileUtils.forceDelete(new File(System.getProperty("user.dir") + "\\reports"));
} catch (IOException e) {
e.printStackTrace();
}
flashscreen = new FlashScreen(driver);
}
public String getScreenshotPath(String testCaseName, AndroidDriver driver) throws IOException {
File source1 = driver.getScreenshotAs(OutputType.FILE);
String destinationfile1 = System.getProperty("user.dir") + "\\reports\\FailTestCasesScreenshots\\"
+ testCaseName + ".png";
FileUtils.copyFile(source1, new File(destinationfile1));
return destinationfile1;
}
The test that got failed.
#Test(priority = 3)
public void verifyCouponCodeFunctionalityWithValidCode() {
SoftAssert softAssertion3 = new SoftAssert();
orderp.enterCoupenCode(propConnection.getProperty("CouponCode"));
nos_calls = orderp.pressApplyCouponButton();
if (orderp.getTotalAmount().equals(" $ 0.0")) {
softAssertion3.assertTrue(true);
} else {
softAssertion3.assertTrue(false, "Coupon not applied");
}
nos_calls += 1;
softAssertion3.assertAll();
}
`
Expecting the extent report to show the screenshot on test failure

why the public static void main(String args[]) error and it say illegal start of expression?

i'm newbie to netbeans and doing my schoolwork
i'm trying to connect to derby database but the public static void showing error i don't know what to do here is my code:
import java.sql.;
import javax.swing.;
public class addcriminal extends javax.swing.JFrame {
public addcriminal() {
initComponents();
}
#SuppressWarnings("unchecked")
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String url="jdbc:derby://localhost:1527/criminal records ";
String username ="naim";
String password = "12345";
Connection con = DriverManager.getConnection(url,username,password);
Statement stmt = con.createStatement ();
String Query;
Query = "INSERT INTO CRIMINAL RECORDS (ID, NAME, AGE, ICNO, SEX, CRIME, PERIODS)VALUES ('"+txtno.getText()+"' , '"+txtname.getText()+"', '"+txtage.getText()+"', '"+txtic.getText()+"','"+txtic.getText()+"', '"+combosex.getSelectedItem()+"', '"+txtcrime.getText()+"', '"+txtperiods.getText()+"')";
stmt.execute(Query);
JOptionPane.showMessageDialog(null, "criminal recorded");
txtno.setText(null);
txtname.setText(null);
txtage.setText(null);
txtic.setText(null);
combosex.setSelectedItem(null);
txtcrime.setText(null);
txtperiods.setText(null);
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
public static void main(String args[]) { <<ERROR HERE
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new addcriminal().setVisible(true);
}
});
}
Looks to me like you forgot the closing curly bracket in your catch statement.
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}

How to convert my Database class to Singleton

I'm a beginner in java and i'm practicing Singleton.
I'm trying to figure out how to convert my Database class to Singleton.
Also, part of my issue is how to use the Database class without passing the properties in the constructor.
public class Database {
public static final String DB_DRIVER_KEY = "db.driver";
public static final String DB_URL_KEY = "db.url";
public static final String DB_USER_KEY = "db.user";
public static final String DB_PASSWORD_KEY = "db.password";
private static Logger LOG = Logger.getLogger(Database.class.getName());
private static final Database theInstance = new Database();
private static Connection connection;
private static Properties properties;
private Database() {
}
public static void init(Properties properties) {
if (Database.properties == null) {
LOG.debug("Loading database properties from db.properties");
Database.properties = properties;
}
}
public static Connection getConnection() throws SQLException {
if (connection != null) {
return connection;
}
try {
connect();
} catch (ClassNotFoundException e) {
throw new SQLException(e);
}
return connection;
}
private static void connect() throws ClassNotFoundException, SQLException {
String dbDriver = properties.getProperty(DB_DRIVER_KEY);
LOG.debug(dbDriver);
Class.forName(dbDriver);
System.out.println("Driver loaded");
connection = DriverManager.getConnection(properties.getProperty(DB_URL_KEY),
properties.getProperty(DB_USER_KEY), properties.getProperty(DB_PASSWORD_KEY));
LOG.debug("Database connected");
}
/**
* Close the connections to the database
*/
public void shutdown() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
}
/**
* Determine if the database table exists.
*
* #param tableName
* #return true is the table exists, false otherwise
* #throws SQLException
*/
public static boolean tableExists(String tableName) throws SQLException {
DatabaseMetaData databaseMetaData = getConnection().getMetaData();
ResultSet resultSet = null;
String rsTableName = null;
try {
resultSet = databaseMetaData.getTables(connection.getCatalog(), "%", "%", null);
while (resultSet.next()) {
rsTableName = resultSet.getString("TABLE_NAME");
if (rsTableName.equalsIgnoreCase(tableName)) {
return true;
}
}
} finally {
resultSet.close();
}
return false;
}
/**
* #return the theinstance
*/
public static Database getTheinstance() {
return theInstance;
}
}
Well this little bit change into your existing class to make you understand.
public class Database {
public static final String DB_DRIVER_KEY = "db.driver";
public static final String DB_URL_KEY = "db.url";
public static final String DB_USER_KEY = "db.user";
public static final String DB_PASSWORD_KEY = "db.password";
private static Logger LOG = Logger.getLogger(Database.class.getName());
private static Database theInstance;
private static Connection connection;
private static Properties properties;
private Database() {
}
public static void init(Properties properties) {
if (Database.properties == null) {
LOG.debug("Loading database properties from db.properties");
Database.properties = properties;
}
}
public static Connection getConnection() throws SQLException {
if (connection != null) {
return connection;
}
try {
connect();
} catch (ClassNotFoundException e) {
throw new SQLException(e);
}
return connection;
}
private static void connect() throws ClassNotFoundException, SQLException {
String dbDriver = properties.getProperty(DB_DRIVER_KEY);
LOG.debug(dbDriver);
Class.forName(dbDriver);
System.out.println("Driver loaded");
connection = DriverManager.getConnection(
properties.getProperty(DB_URL_KEY),
properties.getProperty(DB_USER_KEY),
properties.getProperty(DB_PASSWORD_KEY));
LOG.debug("Database connected");
}
/**
* Close the connections to the database
*/
public void shutdown() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
}
/**
* Determine if the database table exists.
*
* #param tableName
* #return true is the table exists, false otherwise
* #throws SQLException
*/
public static boolean tableExists(String tableName) throws SQLException {
DatabaseMetaData databaseMetaData = getConnection().getMetaData();
ResultSet resultSet = null;
String rsTableName = null;
try {
resultSet = databaseMetaData.getTables(connection.getCatalog(),
"%", "%", null);
while (resultSet.next()) {
rsTableName = resultSet.getString("TABLE_NAME");
if (rsTableName.equalsIgnoreCase(tableName)) {
return true;
}
}
} finally {
resultSet.close();
}
return false;
}
/**
* #return the theinstance
*/
public static Database getInstance() {
if(theInstance == null){
theInstance = new Database();
}
return theInstance;
}
}

REST Web Service using Java and Jersey API: Unable to Read data from DB

I am creating a REST Web Service using Java and Jersey API. The basic REST service works fine,but when I add in a DB connection it gives me a Class Not Found Exception and a SQL Exception - No driver found. I have included the ojdbc6.jar file in the Eclipse build path. Using the same code if I create a Java application it runs fine.
I have added my code below. Can some one plz suggest something.
EDIT: I included the jar file in the WEB-INF lib directory. But when I try to execute the code I get the following error: HTTP Status 405 - Method Not Allowed
public class Note {
private int noteId;
private String content;
private Date createdDate;
public Note() {}
public Note(int noteId, String content, Date createdDate) {
this.noteId = noteId;
this.content = content;
this.createdDate = createdDate;
}
public int getNoteId() {
return noteId;
}
public void setNoteId(int noteId) {
this.noteId = noteId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Override
public String toString() {
return "Note [content=" + content + ", createdDate=" + createdDate
+ ", noteId=" + noteId + "]";
}
}
public class NoteDAO {
DatabaseAccess data;
Connection connection;
public NoteDAO()
{
try {
data = new DatabaseAccess();
connect();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void connect() throws SQLException
{
try
{
data.connect();
connection = data.connection;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public Note getNoteById(int id)
{
PreparedStatement prepStmt = null;
try {
String cSQL = "SELECT * FROM NOTE WHERE NOTEID = 12 ";
prepStmt = connection.prepareStatement(cSQL);
prepStmt.setInt(1, id);
ResultSet result = prepStmt.executeQuery();
Note note = new Note();
while (result.next())
{
note.setNoteId(result.getInt(1));
note.setContent(result.getString(2));
note.setCreatedDate( (Date) new java.util.Date(result.getDate(3).getTime()));
}
return note;
} catch (SQLException e) {
e.printStackTrace();
prepStmt = null;
return null;
}
}
}
#Path("/notes")
public class Notes {
#Context
UriInfo uriInfo;
#Context
Request request;
NoteDAO dao = new NoteDAO();
#Path("{note}")
#GET
#Produces(MediaType.APPLICATION_XML)
public Note getNote(
#PathParam("note") String idStr) {
int id = Integer.parseInt(idStr);
Note note = dao.getNoteById(id);
if(note==null)
throw new RuntimeException("Get: Note with " + id + " not found");
return note;
}
public class DatabaseAccess {
Connection connection = null;
public void connect() throws SQLException
{
String DRIVER = "oracle.jdbc.driver.OracleDriver";
String URL = "jdbc:oracle:thin:#xx.xxx.xx.xxx:1521:XXXX";
String UserName = "username";
String Password = "password";
try
{
Class.forName(DRIVER);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
connection = DriverManager.getConnection(URL,UserName,Password);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void disconnect() throws SQLException
{
connection.close();
}
}
If you are using datasources that are managed by the application server, you need to put the ojdbc6.jar library inside the lib folder of your application server.
On JBoss for example, it would be $JBOSS_HOME/server/default/lib.
This is required, because in such case, the datasource is being build when the server starts and independently from your application, which means the server cannot use your application JARs.
If, however, you are pooling the connections yourself, you need to make sure, that the ojdbc6.jar is inside the lib folder of your application WAR archive.

question about simple MINA client and server

I am just trying to create a simple MINA server and client to evaluate. Here is my code.
public class Server {
private static final int PORT = 8080;
static class ServerHandler extends IoHandlerAdapter {
#Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
cause.printStackTrace();
}
#Override
public void sessionCreated(IoSession session) {
System.out.println("session is created");
session.write("Thank you");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("session is closed.");
}
#Override
public void messageReceived(IoSession session, Object message) {
System.out.println("message=" + message);
session.write("Reply="+message);
}
}
/**
* #param args
*/
public static void main(String[] args) throws Exception {
SocketAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
acceptor.setHandler(new Server.ServerHandler());
acceptor.getSessionConfig().setReadBufferSize( 2048 );
acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("Listening on port " + PORT);
for (;;) {
Thread.sleep(3000);
}
}
}
public class Client {
private static final int PORT = 8080;
private IoSession session;
private ClientHandler handler;
public Client() {
super();
}
public void initialize() throws Exception {
handler = new ClientHandler();
NioSocketConnector connector = new NioSocketConnector();
connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.setHandler(handler);
for (;;) {
try {
ConnectFuture future = connector.connect(new InetSocketAddress(PORT));
future.awaitUninterruptibly();
session = future.getSession();
break;
} catch (RuntimeIoException e) {
System.err.println("Failed to connect.");
e.printStackTrace();
Thread.sleep(5000);
}
}
if (session == null) {
throw new Exception("Unable to get session");
}
Sender sender = new Sender();
sender.start();
session.getCloseFuture().awaitUninterruptibly();
connector.dispose();
System.out.println("client is done.");
}
/**
* #param args
*/
public static void main(String[] args) throws Exception {
Client client = new Client();
client.initialize();
}
class Sender extends Thread {
#Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.messageSent(session, "message");
}
}
class ClientHandler extends IoHandlerAdapter {
#Override
public void sessionOpened(IoSession session) {
}
#Override
public void messageSent(IoSession session, Object message) {
System.out.println("message sending=" + message);
session.write(message);
}
#Override
public void messageReceived(IoSession session, Object message) {
System.out.println("message receiving "+ message);
}
#Override
public void exceptionCaught(IoSession session, Throwable cause) {
cause.printStackTrace();
}
}
}
When I execute this code, the Client seems to keep sending a message instead of stopping after it sends. It looks to me that there is a recursive call in underlying MINA code. I know that I am doing something wrong.
Can somebody tell me how to fix this?
Thanks.
Try to initialize and start your sender and use the session within sessionOpened (ClientHandler)