Headless Exception - netbeans-8

I would like to ask for a solution to my problem:
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from
fulfilling this request.
exception
java.awt.HeadlessException
note The full stack traces of the exception and its root causes are available
in the GlassFish Server Open Source Edition 4.1.1 logs.
GlassFish Server Open Source Edition 4.1.1
There are a few tables in the database, but when I need to get records from the table "Student", it keeps showing this error.
domain file :
package domain;
import java.io.Serializable;
import java.util.Objects;
public class Student implements Serializable {
private String studID;
private String studName;
private int studIC;
private String gender;
private String address;
private int contactNo;
public Student(){}
public Student(String studID){
this.studID = studID;
}
public Student(String studID, String studName, int studIC, String gender, String address, int contactNo){
this.studID = studID;
this.studName = studName;
this.studIC = studIC;
this.gender = gender;
this.address = address;
this.contactNo = contactNo;
}
public String getStudID(){
return studID;
}
public void setStudID(String studID){
this.studID = studID;
}
public String getStudName(){
return studName;
}
public void setStudName(String studName){
this.studName = studName;
}
public int getStudIC(){
return studIC;
}
public void setStudIC(int studIC){
this.studIC = studIC;
}
public String getGender(){
return gender;
}
public void setGender(String gender){
this.gender = gender;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public int getContactNo(){
return contactNo;
}
public void setContactNo(int contactNo){
this.contactNo = contactNo;
}
}
da file :
package da;
import domain.Student;
import java.sql.*;
import javax.swing.*;
public class StudentDA {
private String host = "jdbc:derby://localhost:1527/hostelDB";
private String user = "nbuser";
private String password = "nbuser";
private String tableName = "Student";
private Connection conn;
private PreparedStatement stmt;
public StudentDA(){
createConnection();
}
public void addRecord(Student student) {
String insertStr = "INSERT INTO " + tableName + " VALUES(?, ?, ?, ?, ?, ?)";
try {
stmt = conn.prepareStatement(insertStr);
stmt.setString(1, student.getStudID());
stmt.setString(2, student.getStudName());
stmt.setInt(3, student.getStudIC());
stmt.setString(4, student.getGender());
stmt.setString(5, student.getAddress());
stmt.setInt(6, student.getContactNo());
stmt.executeUpdate();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
public Student getRecord(String studID) {
String queryStr = "SELECT * FROM " + tableName + " WHERE StudentID = ?";
Student student = null;
try {
stmt = conn.prepareStatement(queryStr);
stmt.setString(1, studID);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
student = new Student(studID, rs.getString("StudentName"), rs.getInt("StudentIC"), rs.getString("Gender"), rs.getString("Address"), rs.getInt("ContactNo"));
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
return student;
}
private void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection(host, user, password);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
private void shutDown() {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
}
}
servlet :
String studID = request.getParameter("studID");
Student stud = studDA.getRecord(studID);
out.println(stud);

Related

How to solve this issue about Java DB connection

There are my codes.
MemberDAO.java
package sec05.ex01;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class MemberDAO {
PreparedStatement pstmt;
Connection connection;
public List<MemberVO> listMembers() {
List<MemberVO> list = new ArrayList<>();
try {
connDB();
String query = "SELECT * FROM t_member";
System.out.println("preparedStatement: " + query);
pstmt = connection.prepareStatement(query);
ResultSet rs = pstmt.executeQuery(query);
while (rs.next()) {
String id = rs.getString("id");
String pwd = rs.getString("pwd");
String name = rs.getString("name");
String email = rs.getString("email");
Date joinDate = rs.getDate("joinDate");
MemberVO vo = new MemberVO();
vo.setId(id);
vo.setPwd(pwd);
vo.setName(name);
vo.setEmail(email);
vo.setJoinDate(joinDate);
list.add(vo);
}
rs.close();
pstmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
private void connDB() {
try {
String url = "jdbc:oracle:thin:#localhost:1521:XE";
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Loaded Oracle Driver");
connection = DriverManager.getConnection(url, "system", "oracle");
System.out.println("Connection created.");
System.out.println("PreparedStatement created.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
MemberServlet.java
package sec05.ex01;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.List;
#WebServlet("/member")
public class MemberServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
MemberDAO dao = new MemberDAO();
List<MemberVO> list = dao.listMembers();
out.print("<html><body>");
out.print("<table border=1><tr align='center' bgcolor='lightgreen'>");
out.print("<td>ID</td><td>PWD</td><td>NAME</td><td>EMAIL</td><td>DATE</td></tr>");
for (MemberVO memberVO : list) {
String id = memberVO.getId();
String pwd = memberVO.getPwd();
String name = memberVO.getName();
String email = memberVO.getEmail();
Date joinDate = memberVO.getJoinDate();
out.print("<tr><td" + id + "</td><td>" + pwd + "</td><td>" + name + "</td><td>" + email + "</td><td>" + joinDate + "</td></tr>");
}
out.print("</table></body></html>");
}
}
MemberVO.java
package sec05.ex01;
import java.sql.Date;
public class MemberVO {
private String id;
private String pwd;
private String name;
private String email;
private Date joinDate;
public MemberVO() {
System.out.println("MemberVO constructor called.");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
}
Error Message
But when I use console in IntelliJ, it works.
Database console in IntelliJ
Also, I added a jdbc library. (I'm using jdk17)
IntelliJ Library
I tried to change the library version to 8.
The ClassNotFoundException and NullPointerException occured.

Batch update for a CRUD spring-boot application every second

I have a spring boot application in which i edit a employee database with CRUD operations received from Postman.
My problem is that in this case i need to access the database with multiple threads, or with batches.
I decided to do a batch update.
This is my DAO in which i make the crud operations with sql connections.
#Repository
public class EmployeeDaoImpl implements EmployeeDao {
public EmployeeDaoImpl(NamedParameterJdbcTemplate template) {
this.template = template;
}
private static int maxCreateBatch = 50;
private static int maxUpdateBatch = 50;
private static int maxDeleteBatch = 50;
NamedParameterJdbcTemplate template;
#Override
public List<Employee> findAll() {
return template.query("select * from employee", new EmployeeRowMapper());
}
#Override
public void insertEmployee(Employee emp) {
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://10.10.45.147:5432/db", "db",
"pass");
PreparedStatement ps = conn.prepareStatement("insert into employee(employeeId, employeeName ) values(?,?)");
int i = 1, j = 0;
ps.setString(i++, emp.getEmployeeId());
ps.setString(i++, emp.getEmployeeName());
ps.addBatch();
j++;
i = 1;
if (j == maxCreateBatch) {
ps.executeBatch();
j = 0;
}
} catch (SQLException e) {
System.out.println("Connection failure");
e.printStackTrace();
}
}
#Override
public void updateEmployee(Employee emp) {
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://10.10.45.147:5432/db", "db",
"pass");
PreparedStatement ps = conn.prepareStatement("update employee set employeeName=? where employeeId=?");
int i = 1, j = 0;
ps.setString(i++, emp.getEmployeeName());
ps.setString(i++, emp.getEmployeeId());
ps.addBatch();
i = 1;
j++;
if (j == maxUpdateBatch) {
ps.executeBatch();
j = 0;
}
} catch (SQLException e) {
System.out.println("Connection failure");
e.printStackTrace();
}
}
#Override
public void executeUpdateEmployee(Employee emp) {
final String sql = "update employee set employeeName=:employeeName where employeeId=:employeeId";
Map<String, Object> map = new HashMap<String, Object>();
map.put("employeeId", emp.getEmployeeId());
map.put("employeeName", emp.getEmployeeName());
template.execute(sql, map, new PreparedStatementCallback<Object>() {
#Override
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
return ps.executeUpdate();
}
});
}
#Override
public void deleteEmployee(Employee emp) {
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://10.10.45.147:5432/db", "db",
"pass");
PreparedStatement ps = conn.prepareStatement("delete from employee where employeeId=?");
int j = 0;
ps.setString(1, emp.getEmployeeId());
ps.addBatch();
j++;
if (j == maxDeleteBatch) {
ps.executeBatch();
j = 0;
}
} catch (SQLException e) {
System.out.println("Connection failure");
e.printStackTrace();
}
}
}
This is my simple controller
#RestController
#RequestMapping("/postgressApp")
public class ApplicationController {
#Resource
EmployeeService employeeService;
#GetMapping(value = "/employeeList")
public List<Employee> getEmployees() {
return employeeService.findAll();
}
#PostMapping(value = "/createEmp")
public void createEmployee(#RequestBody Employee emp) {
employeeService.insertEmployee(emp);
}
#PutMapping(value = "/updateEmp")
public void updateEmployee(#RequestBody Employee emp) {
employeeService.updateEmployee(emp);
}
#PutMapping(value = "/executeUpdateEmp")
public void executeUpdateEmployee(#RequestBody Employee emp) {
employeeService.executeUpdateEmployee(emp);
}
#DeleteMapping(value = "/deleteEmpById")
public void deleteEmployee(#RequestBody Employee emp) {
employeeService.deleteEmployee(emp);
}
}
As you can see i have a preparedStatement for each operation and i add avery operation to a batch.
In this moment, all get sent to the database only when the batch limit is reached.
**But my problem is : ** i need to sent every one of those batches to the database every second.
How do i do that ? Cause i cant call the bathes outside of their methods.

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.