JDBC connectivity issue - jdbc

I'm using the NetBeans IDE(6.8). I have a DB class :
package garits;
import java.io.Serializable;
import java.sql.*;
import java.util.Properties;
public class DB implements Serializable{
private static final long serialVersionUID = 1L;
String dbURL = "jdbc:mysql:///team_project";
String user = "root";
String pwd = "arsenal";
String dbDriver = "com.mysql.jdbc.Driver";
private Connection dbCon;
private ResultSet r;
private Statement s;
public DB()
{}
public boolean connect() throws ClassNotFoundException,SQLException{
Class.forName(dbDriver);
Properties props = new Properties();
props.put(user, "root");
props.put(pwd, "arsenal");
props.put("charSet", "UTF-8");
props.put("lc_ctype", "UTF-8");
dbCon = DriverManager.getConnection(dbURL,props);
//dbCon = DriverManager.getConnection(dbURL,user,pwd);
return true;
}
public void close() throws SQLException{
dbCon.close();
if(r!=null)
r.close();
if(s!=null)
s.close();
}
public ResultSet execSQL(String sql) throws SQLException{
s = dbCon.createStatement();
r = s.executeQuery(sql);
return (r == null) ? null : r;
}
public int updateSQL(String sql) throws SQLException{
s = dbCon.createStatement();
int r = s.executeUpdate(sql);
return (r == 0) ? 0 : r;
}
public int updateSQL(String sql, String getID) throws SQLException{
s = dbCon.createStatement();
int autoIncValue = -1;
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
if (rs.next()) {
autoIncValue = rs.getInt(1);
}
return autoIncValue;
}
}
The jar file is im my library, but whenever I try to connect:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String result ="";
DB db = new DB();
try{
db.connect();
String query = "Select Role From User_Account Where Username=jTextField1.getText()AND Where Password=jTextField2.getText(); ";
ResultSet rs=db.execSQL(query);
while(rs.next())
{
result = rs.getString("Role");
}
if(result.equals(""))
{
JOptionPane.showMessageDialog(loginButton,"Access denied","Error Message",JOptionPane.ERROR_MESSAGE);
}
else if(result.equals("Administrator"))
{
MainPage_Admin admin = new MainPage_Admin();
}
}
catch(Exception e)
{
System.out.println("An error has occurred");
}
}
I get an error(the exception is caught)-the name of the database is "team_project" and password is "arsenal"-any ideas appreciated. I'm new to JDBC.

First step: use at least e.printStackTrace() in your catch-block to get some information from the exception. Otherwise you'll just be guessing.

MySQL database url connection property is wrong
jdbc:mysql://localhost:3306/<your database name>
instead of you are giving
jdbc:mysql:///team_project
modify and execute the program and better to handle the exception within the try/catch block instead of throws.

Related

Mockito tests pass except one verify

I have all my tests pass except this line in the first test
verify(reimbursementDAO).getById(REIMBURSEMENT_TO_PROCESS.getId());
see code below.
package com.revature.services;
public class ReimbursementServiceTest {
private static ReimbursementService reimbursementService;
private static ReimbursementDAO reimbursementDAO;
private Reimbursement REIMBURSEMENT_TO_PROCESS;
private Reimbursement GENERIC_REIMBURSEMENT_1;
private Optional<Reimbursement>
GENERIC_REIMBURSEMENT_2;
private List<Reimbursement> GENERIC_ALL_PENDING_REIMBURSEMENTS;
private User GENERIC_EMPLOYEE_1;
private User GENERIC_FINANCE_MANAGER_1;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
reimbursementDAO=mock(ReimbursementDAO.class);//(IReimbursementDAO.class);
reimbursementService = new ReimbursementService(reimbursementDAO);
//reimbursementDAO=new ReimbursementDAO();
}
#Before
public void setUp() throws Exception {
GENERIC_EMPLOYEE_1 = new User(1, "genericEmployee1", "genericPassword", Role.EMPLOYEE);
GENERIC_FINANCE_MANAGER_1 = new User(1, "genericManager1", "genericPassword", Role.FINANCE_MANAGER);
REIMBURSEMENT_TO_PROCESS = new Reimbursement(2, Status.PENDING, GENERIC_EMPLOYEE_1, null, 150.00);
GENERIC_REIMBURSEMENT_1 = new Reimbursement(1, Status.PENDING, GENERIC_EMPLOYEE_1, null, 100.00);
GENERIC_REIMBURSEMENT_2 = Optional.ofNullable(new Reimbursement(2, Status.APPROVED, GENERIC_EMPLOYEE_1,
GENERIC_FINANCE_MANAGER_1, 150.00));
GENERIC_ALL_PENDING_REIMBURSEMENTS = new ArrayList<Reimbursement>();
GENERIC_ALL_PENDING_REIMBURSEMENTS.add(GENERIC_REIMBURSEMENT_1);
}
#Test
public void testProcessPassesWhenUserIsFinanceManagerAndReimbursementExistsAndUpdateSuccessful()
throws Exception{
when(reimbursementDAO.getById(anyInt())).thenReturn(Optional.of(GENERIC_REIMBURSEMENT_1));
when(reimbursementDAO.update(any())).thenReturn(GENERIC_REIMBURSEMENT_2);
assertEquals(GENERIC_REIMBURSEMENT_2,
reimbursementService.process(REIMBURSEMENT_TO_PROCESS, Status.APPROVED,
GENERIC_FINANCE_MANAGER_1));
//verify(reimbursementDAO).getById(REIMBURSEMENT_TO_PROCESS.getId());
verify(reimbursementDAO).update(REIMBURSEMENT_TO_PROCESS);
}
#Test
public void testGetReimbursementByStatusPassesWhenReimbursementsAreSuccessfullyReturned() {
when(reimbursementDAO.getBystatus(any())).thenReturn(GENERIC_ALL_PENDING_REIMBURSEMENTS);
assertEquals(GENERIC_ALL_PENDING_REIMBURSEMENTS,
reimbursementService.getReimbursementsByStatus(Status.PENDING));
verify(reimbursementDAO).getBystatus(Status.PENDING);
}
}
public class ReimbursementDAO extends AbstractReimbursement
{
public Optional< Reimbursement> getById(int id) {
try(Connection conn = ConnectionFactory.getConnection())
{
String sql="select * from ers_reimbursements where reimb_id=?;";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setInt(1,id);
ResultSet rs= ps.executeQuery();
Reimbursement reimb=null;
UserService usrv=new UserService();
//reimb_id ,amount, submitted,resolved,description,author,receipt ,resolver,status,reimb_type
while(rs.next())
{
int reid=rs.getInt("reimb_id");
double ramount=rs.getInt("reimb_amount");
int res=rs.getInt( "resolver");
User resolver=null;
String description=rs.getString("description");
User rauthor= usrv.getUserById( rs.getInt("author")).get();
if(res>0)
{ resolver= usrv.getUserById(res).get(); }
int rstatus= rs.getInt("reimb_status");
Status r_status=Status.values()[--rstatus];
int reimb_type= rs.getInt("reimb_type");
ReimbType retype=ReimbType.values()[--reimb_type];
User oth=rauthor;
User re=resolver;
reimb=new Reimbursement(reid, r_status,oth,re,ramount);
return Optional.ofNullable(reimb);
}
}catch(SQLException e) { e.printStackTrace();};
return Optional.empty();
}
public List<Reimbursement> getBystatus(Status status) {
try(Connection conn = ConnectionFactory.getConnection())
{
String sql="select * from ers_reimbursements where reimb_status=?;";
PreparedStatement ps=conn.prepareStatement(sql);//,Statement.RETURN_GENERATED_KEYS);
int sta_id= status.ordinal()+1;
ps.setInt(1,sta_id);
ResultSet rs= ps.executeQuery();
Reimbursement reimb=null;
List<Reimbursement> reimbList=new ArrayList<Reimbursement>();
IUserService usrv=new UserService();
//reimb_id ,amount, submitted,resolved,description,author,receipt ,resolver,status,reimb_type
while(rs.next())
{
//int id, Status status, User author, User resolver, double amount
int reid=rs.getInt("reimb_id");
double ramount=rs.getInt("reimb_amount");
Optional<User> rauthor= usrv.getUserById( rs.getInt("author"));
User oth=null;
if(rauthor.isPresent())
{ oth=rauthor.get(); }
int resol=rs.getInt( "resolver");
Optional<User> resolver= usrv.getUserById(resol);
User re=null;
if(resolver.isPresent())
{ re=resolver.get(); }
else {re=null;}
int rstatus= rs.getInt("reimb_status");
Status r_status=Status.values()[--rstatus];//.PENDING;
int reimb_type= rs.getInt("reimb_type");
ReimbType retype=ReimbType.values()[--reimb_type];//.TRAVEL;
reimb=new Reimbursement(reid, r_status,oth,re,ramount);
reimbList.add(reimb);
}
return reimbList;
}catch(SQLException e) { e.printStackTrace();};
return null;
}
public Optional<Reimbursement> update(Reimbursement unprocessedReimbursement) {
try(Connection conn=ConnectionFactory.getConnection()) {
String sql="update ers_reimbursements set reimb_status=?,"
+ " resolver=?, resolved=? where reimb_id=?;";
PreparedStatement ps=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
int id=unprocessedReimbursement.getId();
Status st=unprocessedReimbursement.getStatus();
ps.setObject(1,st);
ps.setInt(2,unprocessedReimbursement.getResolver().getId());
ps.setObject(3, LocalDateTime.now());
ps.setInt(4,id);
ps.executeUpdate();
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
int reimid=generatedKeys.getInt(1);
Optional<Reimbursement> reim=getById(reimid);
System.out.println("Reimb " + reim.get()+ " upLocalTimed!");
return reim;
}
}catch(SQLException e) {};
}catch(SQLException e) { e.printStackTrace();}
return Optional.empty();
}
}
public class ReimbursementService{
{
private final ReimbursementDAO reimbDao;
public ReimbursementService() {
this(new ReimbursementDAO());
}
public ReimbursementService(ReimbursementDAO userDAO2) {
this.reimbDao = userDAO2;
}
public Optional< Reimbursement> process(Reimbursement unprocessedReimbursement,
Status finalStatus, User resolver) throws Exception{
if (!resolver.getRole().equals(Role.FINANCE_MANAGER)) {
throw new RegistrationUnsuccessfulException("Resolver must be Finance Manager ");
}
// List<Reimbursement> l=DAO.getByStatus(Status.PENDING);
if(unprocessedReimbursement.getId()==0)
{ throw new Exception(" reimbursement not found"); }
if(unprocessedReimbursement.getStatus().equals(Status.PENDING))
{
unprocessedReimbursement.setResolver(resolver);
unprocessedReimbursement.setStatus(finalStatus);
Optional<Reimbursement> reimb=this.reimbDao.update(unprocessedReimbursement );
if(reimb.isPresent())
{ return reimb; }
else { throw new Exception("unsuccessful update");}
}
return Optional.ofNullable(null);
}
}
The verification
verify(reimbursementDAO).getById(REIMBURSEMENT_TO_PROCESS.getId());
fails because your service does not call the getById() method of your DAO.
It happens that your real DAO's update() method calls its own getById() method, but in your test you are using a mock DAO, where all functionality has been stubbed out. The update() method of the mock DAO does nothing more than return GENERIC_REIMBURSEMENT_2 because that's what your test sets it up to do.

Glassfish RAR5035:Unexpected Exception While Destroying Resource From Pool

I have a Java EE web application. I am connecting database with JDBC and I am using JDBC connection pool. My application's main page is login page. After I enter the login page and wait for a while, I take this glassfish server(4.1.0) warning consistently.
Warning: RAR5035:Unexpected exception while destroying resource from
pool OraclePool. Exception message: Error while destroying resource
:IO Error: Socket read timed out
Even if I don't do any action on the page. When I monitore the statistics of the connection pool, NumConnCreated is increasing continuously. How can I solve the problem?. Thank you.
This is my managed bean class.
#ManagedBean
#SessionScoped
public class Login implements Serializable{
private String userName;
private String password;
private User user;
private #EJB DBRemote db;
public void test(){
String[] params1 = {"user","1234"};
int[] getParams = {Types.INTEGER,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR};
CallableStatement statement = db.run("TBL.USERLOGIN(?,?,?,?,?,?)", params1 , getParams);
try {
int isLogin = statement.getInt(3);
if (isLogin==1) {
String uName = statement.getString(4);
String uId = statement.getString(5);
user = new User(uId, uName, isLogin);
System.out.println("LOGGED IN " + uName + "\t" + uId);
}else{
String errMessage = statement.getString(6);
user = new User(errMessage,isLogin);
System.out.println("LOG IN FAILURE " + errMessage);
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}finally{
db.close();
FacesContext.getCurrentInstance().addMessage("infoback", new FacesMessage(FacesMessage.SEVERITY_INFO,
"TEST","Test Works"));
}
}
}
This my interface class
#Remote
public interface DBRemote {
CallableStatement run(String query, String[] setParams, int[] getParams);
void close();
String getErrorMessage();
String getSql();
}
This is my Stateless Bean class
#Stateless
public class DB implements DBRemote{
#Resource(mappedName = "pwresource")
private DataSource ds;
private String sql;
private String errorMessage;
private CallableStatement statement;
private Connection connection;
public DB() {
}
#Override
public CallableStatement run(String query, String[] setParams, int[] getParams){
sql = "{call " + query + "}";
int getParamIndex = setParams.length + 1;
try {
connection = ds.getConnection();
statement = connection.prepareCall(sql);
for (int i = 0; i < setParams.length; i++) {
statement.setString(i+1, setParams[i]);
}
for (int getParam : getParams) {
statement.registerOutParameter(getParamIndex, getParam);
getParamIndex++;
}
statement.execute();
}catch (SQLException ex) {
if (ex.getErrorCode()==17008) {
errorMessage = "Timeout";
}else{
errorMessage = "System Error";
}
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
close();
}
return statement;
}
#Override
public void close(){
try {
if (statement != null) {
statement.close();
}
if(connection != null){
connection.close();
}
errorMessage = null;
} catch (SQLException e) {
errorMessage = "Close Connection Error";
}
}
#Override
public String getErrorMessage() {
return errorMessage;
}
#Override
public String getSql() {
return sql;
}
}
I have solved my problem. My problem is because of the connection between connection pool and database. Database closes the connections automically because of the server and database in different networks caused timeout issue.

Class not found Kryo exception in hive 0.13 - Hadoop

I have a GenericUDF (see code below) that was running fine on Hadoop-1 and Hive-0.12. But when testing the same GenericUDF using Hive-0.13 + Hadoop-2, I am getting the below error.
Vertex failed, vertexName=Map 12, vertexId=vertex_1409698731658_42202_1_00, diagnostics=[Vertex Input: ccv initializer failed., org.apache.hive.com.esotericsoftware.kry
o.KryoException: Unable to find class: com.xxx.xxx.Id1
Here is the code for my UDF.
package com.xxx.xxx;
import org.apache.hadoop.hive.*;
public class Id1 extends GenericUDF {
private MapredContext context;
private long sequenceNum = 0;
private static final int padLength = 10;
StringBuilder sb = null;
public ObjectInspector initialize(ObjectInspector[] arguments)
throws UDFArgumentException {
sequenceNum = 0;
sb = new StringBuilder();
return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
}
public Object evaluate(DeferredObject[] arguments) throws HiveException {
int sbLength = sb.toString().length();
if (sbLength > 0)
sb.replace(0, sbLength, "");
String taskId = null;
if (context.getJobConf() != null)
taskId = context.getJobConf().get("mapred.taskid");
sequenceNum++;
if (taskId != null) {
sb.append(taskId.replace("attempt_", ""));
}
int i = 0;
String seqStr = String.valueOf(sequenceNum);
sb.append(seqStr);
return sb.toString();
}
public String getDisplayString(String[] children) {
return "id1()";
}
#Override
public void configure(MapredContext context) {
this.context = context;
}
}
I am certain this has something to do with Hive-0.13, but not able to see any post related to this error.

InstantiationException when using SQLData and OracleCallableStatement Struct Mapping

I cannot figure out an answer to the following problem. Hope somebody can help me. I am mapping JAVA class to a Struct as described here:
http://docs.oracle.com/cd/F49540_01/DOC/java.815/a64685/samapp4.htm
I have an Oracle Object:
create or replace TYPE DK1 AS OBJECT( zahl CHAR(1) );
and corresponding JAVA class:
public class DK1 implements SQLData {
private String sql_type;
public static final int _SQL_TYPECODE = OracleTypes.STRUCT;
private String zahl;
public DK1(String sql_type, String z) {
this.sql_type = sql_type;
setZahl(z);
}
public String getSQLTypeName() throws SQLException {
return sql_type;
}
public void readSQL(SQLInput stream, String typeName) throws SQLException {
sql_type = typeName;
this.setZahl(stream.readString());
}
public void writeSQL(SQLOutput stream) throws SQLException {
stream.writeString(getZahl());
}
public String getSql_type() {
return sql_type;
}
public void setSql_type(String sql_type) {
this.sql_type = sql_type;
}
public String getZahl() {
return zahl;
}
public void setZahl(String zahl) {
this.zahl = zahl;
}
}
my test method is the following:
public class SQLDataExample {
public static void main(String args[]) throws Exception {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
OracleConnection conn = (OracleConnection) DriverManager.getConnection(
"jdbc:oracle:thin:#................", "...",
"...");
Dictionary<String, Class<?>> map = (Dictionary) conn.getTypeMap();
map.put("BONI.DK1", Class.forName("com.gwb.db.objects.DK1"));
OracleCallableStatement cs = (OracleCallableStatement) conn.prepareCall("{call BOX.DK(?)}");
DK1 dd = new DK1("BONI.DK1", "1");
cs.setObject(1, dd);
cs.registerOutParameter(1, OracleTypes.STRUCT, "BONI.DK1");
cs.execute();
DK1 df = (DK1) cs.getObject(1);
}
}
Now, the last step
DK1 df = (DK1) cs.getObject(1);
in this procedure fails and although I have tried so many things in the last couple of days, I cannot get it to run! I get a
Exception in thread "main" java.sql.SQLException: Inconsistent Java-
ans SQL-Objecttypes: InstantiationException: com.gwb.db.objects.DK1
If I replace getObject with getSTRUCT I see that the DB procedure works and returns values as expected. I cannnot figure out why a I unable to map a JAVA Object.
I would be very grateful for any help or tipps!
Thank you in advance
I forgot the default constructor
public DK1() { }

How to show Oracle DB Tables on my JDeveloper Swing projects frame?

I want to show my Oracle DB tables on my application. I create a new database connection DBConnection1. But I don't bind DBConnection1 in my class. How to do it?
OK. I solve my question.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection connection = DriverManager.getConnection(connStr,"scott","tiger");
Connector conn = new Connector(connStr);
Statement stmt = conn.getConnection().createStatement();
ResultSet rset = stmt.executeQuery(sql);
ResultSetMetaData metaData = rset.getMetaData();
int rowCount = metaData.getColumnCount();
for(i=1;i<=rowCount;i++)
headers.add(metaData.getColumnLabel(i).toString());
while(rset.next()){
Vector tmp = new Vector();
for(i=1;i<=rowCount;i++) {
tmp.add(rset.getString(i));
}
lists.add(tmp);
index++;
Here is the my connector class.
package client;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connector
{
private String connection_string;
private Statement stmt;
private Connection connection;
public Connector(String conn)
{
//String connection_string = "jdbc:oracle:thin:#<host>:<port>:<db name>";
try
{
connection_string = conn;
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection(conn,"scott","tiger");
} catch(Exception f)
{
f.printStackTrace();
}
}
public ResultSet execute(String sql)
{
try
{
stmt = connection.createStatement();
return stmt.executeQuery(sql);
} catch (Exception f)
{
f.printStackTrace();
}
return null;
}
public void setConnection_string(String connection_string)
{
this.connection_string = connection_string;
}
public String getConnection_string()
{
return connection_string;
}
public void setStmt(Statement stmt)
{
this.stmt = stmt;
}
public Statement getStmt()
{
return stmt;
}
public void setConnection(Connection connection)
{
this.connection = connection;
}
public Connection getConnection()
{
return connection;
}
}

Resources