I am a bit confused with my situation as i am new to Gaia environment.
The situation is,
I have 2 databases one is Oracle(External Database) and another is Mysql in Mariadb platform. The ultimate goal is to transfer the data from Oracle to MariaDB through Springboot application.
I have a Issue now, I am able to get through Connections through GaiaConfig file,
package com.jpmc.pulsar.config;
#Configuration
#Profile({"gaia"})
public class GaiaConfig {
#Autowired
private Environment env;
private static final Logger LOG = LoggerFactory.getLogger(GaiaConfig.class);
#Autowired
private DataSource oracleDataSource;
#Autowired
private DataSource mysqlDataSource;
#Bean
public Cloud cloud() {
return new CloudFactory().getCloud();
}
#Bean(name = "oracleDb")
public DataSource oracleDataSource(final Cloud cloud) {
return createDataSource("external-database", cloud);
}
#Bean(name = "oracleJdbcTemplate")
public JdbcTemplate oracleJdbcTemplate() {
return new JdbcTemplate(oracleDataSource);
}
private DataSource createDataSource(final String serviceName, final Cloud cloud) {
final ExternalDependency externalDependency = cloud
.getServiceConnector(serviceName, ExternalDependency.class, null);
if (externalDependency == null) {
throw new InvalidConfigurationException(
String.format("Error getting ServiceConnector for External Dependency with serviceName=[%s]", serviceName)
);
}
HikariDataSource dataSource = null;
try {
final HikariConfig config = new HikariConfig();
config.setDriverClassName(requiredStringProperty("driverClassName", externalDependency, serviceName));
config.setJdbcUrl(requiredStringProperty("jdbcUrl", externalDependency, serviceName));
config.setUsername(requiredStringProperty("username", externalDependency, serviceName));
config.setPassword(requiredStringProperty("password", externalDependency, serviceName));
config.setConnectionTestQuery(requiredStringProperty("connectionTestQuery", externalDependency, serviceName));
config.setMinimumIdle(intProperty("minimumIdle", externalDependency, serviceName, 1));
config.setMaximumPoolSize(intProperty("maximumPoolSize", externalDependency, serviceName, 5));
dataSource = new HikariDataSource(config);
String dataSourceDetails = dataSourceDetails(dataSource);
LOG.info("Available DataSource: [{}]", dataSourceDetails);
} catch (Exception e) {
LOG.info("{}", e);
}
return dataSource;
}
private String dataSourceDetails(final HikariDataSource dataSource) {
final StringBuilder sb = new StringBuilder();
sb.append("driverClassName=[").append(dataSource.getDriverClassName()).append("],");
sb.append("jdbcUrl=[").append(dataSource.getJdbcUrl()).append("],");
sb.append("username=[").append(dataSource.getUsername()).append("],");
sb.append("connectionTestQuery=[").append(dataSource.getConnectionTestQuery()).append("],");
sb.append("validationTimeout=[").append(dataSource.getValidationTimeout()).append("],");
sb.append("maximumPoolSize=[").append(dataSource.getMaximumPoolSize()).append("],");
sb.append("minimumIdle=[").append(dataSource.getMinimumIdle()).append("],");
sb.append("connectionTimeout=[").append(dataSource.getConnectionTimeout()).append("],");
sb.append("connectionInitSql=[").append(dataSource.getConnectionInitSql()).append("],");
sb.append("maxLifetime=[").append(dataSource.getMaxLifetime()).append("]");
return sb.toString();
}
private Boolean booleanProperty(final String propertyName, final ExternalDependency externalDependency) {
final String value = externalDependency.getCredential(propertyName);
if (value != null) {
return Boolean.parseBoolean(value);
}
return Boolean.FALSE;
}
private Integer intProperty(final String propertyName, final ExternalDependency externalDependency,
String serviceName, final int defaultValue) {
final String value = externalDependency.getCredential(propertyName);
if (value != null) {
try {
return Integer.valueOf(value);
} catch (NumberFormatException ex) {
throw new InvalidConfigurationException(
String.format("Property [%s] is not a valid int in External Dependency with serviceId=[%s]",
propertyName, serviceName), ex);
}
}
return defaultValue;
}
private String requiredStringProperty(final String propertyName, final ExternalDependency externalDependency,
String serviceName) {
final String value = stringProperty(propertyName, externalDependency);
if (value == null || value.trim().length() == 0) {
throw new InvalidConfigurationException(
String.format("No property [%s] defined as part of External Dependency with serviceId=[%s]",
propertyName, serviceName));
} else {
return value;
}
}
private String stringProperty(final String propertyName, final ExternalDependency externalDependency) {
return externalDependency.getCredential(propertyName);
}
//MySQL Bean and jdbcTemplate Working Fine
#Primary
#Bean(name = "mysqlDb")
public DataSource mysqlDataSource(final Cloud cloud) {
final String serviceId = "bsc-mariadb";
// https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html
final Properties mysqlProperties = new Properties();
mysqlProperties.setProperty("cachePrepStmts", "true");
mysqlProperties.setProperty("prepStmtCacheSize", "250");
mysqlProperties.setProperty("prepStmtCacheSqlLimit", "2048");
mysqlProperties.setProperty("useServerPrepStmts", "true");
mysqlProperties.setProperty("useLegacyDatetimeCode", "false");
mysqlProperties.setProperty("serverTimezone", "UTC");
mysqlProperties.setProperty("connectionCollation", "utf8mb4_unicode_ci");
// https://github.com/brettwooldridge/HikariCP#configuration-knobs-baby
final Map<String, Object> poolProperties = new HashMap<>();
poolProperties.put("poolName", serviceId + "-pool");
poolProperties.put("maximumPoolSize", 10);
poolProperties.put("maxLifetime", Duration.ofMinutes(5).toMillis());
poolProperties.put("connectionInitSql", "SET character_set_client = utf8mb4;");
poolProperties.put("dataSourceProperties", mysqlProperties);
final DataSourceConfig serviceConfig = new DataSourceConfig(poolProperties);
final DataSource dataSource = cloud.getServiceConnector(serviceId, DataSource.class, serviceConfig);
LOG.info("Available DataSource: [{}]", dataSource);
return dataSource;
}
#Bean(name = "mysqlJdbcTemplate")
public JdbcTemplate jdbcTemplate(#Qualifier("mysqlDb") DataSource dsMySQL) {
return new JdbcTemplate(dsMySQL);
}
}
and My Repository class looks like this,
#Autowired
private JdbcTemplate mysqlJdbcTemplate;
#Autowired
private JdbcTemplate oracleJdbcTemplate;
private String tableName = "BSC_INCIDENT_STG";
private String sql = "INSERT INTO `BSC_INCIDENT_STG`(`INCIDENT_NUMBER`,`APPLICATION_ID`,`CATEGORY`,`OPEN_TIME`,`SEVERITY_CODE`,`ASSIGNMENT`,`STATUS`,`CLOSE_TIME`,`ELAPSED_TIME`,`RESOLUTION_CODE`,`TYPE`,`OPEN_GROUP`,`RESOLVED_GROUP`,`RESOLVED_TIME`,`USER_PRIORITY`,`JP_ACCT_LOB`,`JP_ACCT_APP_RTO`,`JP_IMPACT`,`JP_IMPACT_DURATION_MIN`,`JP_OUTAGE_DURATION_MIN`,`JP_TTR_D1`,`JP_TTR_D2`,`JP_TTR_R1`,`JP_TTR_R2`,`JP_TTR_D2R2`,`LOGICAL_NAME`,`JP_EXTERNAL_ID`,`JP_EXTERNAL_SYSTEM`,`JP_CONFIG_ITEM`,`JP_MASTER_HOST`,`JP_SITE`,`JP_APPSERVICE_NAME`,`JP_APPSERVICE_ID`,`JP_VERUMIDENTIFIER`)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
public boolean truncateAndLoad(final List<Incident> incidentList) {
mysqlJdbcTemplate.execute("TRUNCATE BSC_INCIDENT_STG");
mysqlJdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, incidentList.get(i).getIncidentNumber());
ps.setString(2, incidentList.get(i).getApplicationId());
ps.setString(3, incidentList.get(i).getCategory());
ps.setString(4, incidentList.get(i).getOpenTime());
ps.setString(5, incidentList.get(i).getSeverityCode());
ps.setString(6, incidentList.get(i).getAssignment());
ps.setString(7, incidentList.get(i).getStatus());
ps.setString(8, incidentList.get(i).getCloseTime());
ps.setString(9, incidentList.get(i).getElapsedTime());
ps.setString(10, incidentList.get(i).getResolutionCode());
ps.setString(11, incidentList.get(i).getType());
ps.setString(12, incidentList.get(i).getOpenGroup());
ps.setString(13, incidentList.get(i).getResolvedGroup());
ps.setString(14, incidentList.get(i).getResolvedTime());
ps.setString(15, incidentList.get(i).getUserPriority());
ps.setString(16, incidentList.get(i).getJpAcctLob());
ps.setString(17, incidentList.get(i).getJpAcctAppRto());
ps.setString(18, incidentList.get(i).getJpImpact());
ps.setString(19, incidentList.get(i).getJpImpactDurationMin());
ps.setString(20, incidentList.get(i).getJpOutageDurationMin());
ps.setString(21, incidentList.get(i).getJpTtrD1());
ps.setString(22, incidentList.get(i).getJpTtrD2());
ps.setString(23, incidentList.get(i).getJpTtrR1());
ps.setString(24, incidentList.get(i).getJpTtrR2());
ps.setString(25, incidentList.get(i).getJpTtrD2R2());
ps.setString(26, incidentList.get(i).getLogicalName());
ps.setString(27, incidentList.get(i).getJpExternalId());
ps.setString(28, incidentList.get(i).getJpExternalSystem());
ps.setString(29, incidentList.get(i).getJpConfigItem());
ps.setString(30, incidentList.get(i).getJpMasterHost());
ps.setString(31, incidentList.get(i).getJpSite());
ps.setString(32, incidentList.get(i).getJpAppserviceName());
ps.setString(33, incidentList.get(i).getJpAppserviceId());
ps.setString(34, incidentList.get(i).getJpVerumidentifier());
}
#Override
public int getBatchSize() {
return incidentList.size();
}
});
return true;
}
public String getTableName() {
return tableName;
}
public List<Incident> listAll() {
String cprSql = "SELECT a.NUMBERPRGN as INCIDENT_NUMBER,"
+ "a.JP_ACCT_APP_APPID as APPLICATION_ID,"
+ "a.CATEGORY,"
+ "to_char(a.OPEN_TIME_EST,'DD-MON-YYYY hh24:mi:ss') OPEN_TIME,"
+ "a.SEVERITY_CODE,"
+ "a.ASSIGNMENT,"
+ "a.STATUS,"
+ "to_char(a.CLOSE_TIME_EST,'DD-MON-YYYY hh24:mi:ss') CLOSE_TIME,"
+ "to_char(a.ELAPSED_TIME,'DD-MON-YYYY hh24:mi:ss') ELAPSED_TIME,"
+ "a.RESOLUTION_CODE,"
+ "a.TYPE,"
+ "a.OPEN_GROUP,"
+ "a.RESOLVED_GROUP,"
+ "to_char(a.RESOLVED_TIME,'DD-MON-YYYY hh24:mi:ss') RESOLVED_TIME,"
+ "a.USER_PRIORITY,"
+ "a.JP_ACCT_LOB,"
+ "a.JP_ACCT_APP_RTO,"
+ "a.JP_IMPACT,"
+ "a.jp_impact_duration_min,"
+ "a.JP_OUTAGE_DURATION_MIN,"
+ "a.JP_TTR_D1,"
+ "a.JP_TTR_D2,"
+ "a.JP_TTR_R1,"
+ "a.JP_TTR_R2,"
+ "a.JP_TTR_D2R2,"
+ "a.LOGICAL_NAME,"
+ "b.JP_EXTERNAL_ID,"
+ "b.JP_EXTERNAL_SYSTEM,"
+ "b.JP_CONFIG_ITEM,"
+ "b.JP_MASTER_HOST,"
+ "b.JP_SITE,"
+ "b.JP_APPSERVICE_NAME,"
+ "b.JP_APPSERVICE_ID,"
+ "b.JP_VERUMIDENTIFIER "
+ "FROM SCUSER.PROBSUMMARYM1 a LEFT JOIN SCUSER.DEVICEM1 b ON (DECODE(a.LOGICAL_NAME,b.LOGICAL_NAME,1,0)=1) "
+ "where a.SEVERITY_CODE IN ('P1/S1','P1/S2','P1/S3') "
+ "and a.CPR_BUSINESS_OPERATIONS = 'f' "
+ "and a.ASSIGNMENT like 'X%' "
+ "and (TRUNC(OPEN_TIME_EST) >=TRUNC(SYSDATE-30) OR TRUNC(CLOSE_TIME_EST) >=TRUNC(SYSDATE-30)) and (a.JP_CONFIDENTIAL IS NULL OR a.JP_CONFIDENTIAL= 'f')";
logger.info(cprSql);
return oracleJdbcTemplate.query(cprSql, new IncidentMapper());
The issue is when i am running these files in local i am able to get the data from oracle to mysql(MariaDB) but when i deploy the same in cloud(Gaia) I am getting a conflict. The Conflict is that the cprSql query in Repository class is connecting to mysql in gaia environment.
Below is the issue when i access the url
Mon Oct 15 12:21:49 UTC 2018
There was an unexpected error (type=Internal Server Error, status=500).
StatementCallback; bad SQL grammar [
SELECT a.NUMBERPRGN as INCIDENT_NUMBER,a.JP_ACCT_APP_APPID as APPLICATION_ID,
a.CATEGORY,to_char(a.OPEN_TIME_EST,'DD-MON-YYYY hh24:mi:ss') OPEN_TIME,
a.SEVERITY_CODE,a.ASSIGNMENT,a.STATUS,
to_char(a.CLOSE_TIME_EST, 'DD-MON-YYYY hh24:mi:ss') CLOSE_TIME,
to_char(a.ELAPSED_TIME, 'DD-MON-YYYY hh24:mi:ss') ELAPSED_TIME,
a.RESOLUTION_CODE, a.TYPE,a.OPEN_GROUP,a.RESOLVED_GROUP,
to_char(a.RESOLVED_TIME, 'DD-MON-YYYY hh24:mi:ss') RESOLVED_TIME,
a.USER_PRIORITY, a.JP_ACCT_LOB,a.JP_ACCT_APP_RTO,a.JP_IMPACT,
a.jp_impact_duration_min, a.JP_OUTAGE_DURATION_MIN,a.JP_TTR_D1,
a.JP_TTR_D2,a.JP_TTR_R1, a.JP_TTR_R2,a.JP_TTR_D2R2,a.LOGICAL_NAME,
b.JP_EXTERNAL_ID, b.JP_EXTERNAL_SYSTEM,b.JP_CONFIG_ITEM,b.JP_MASTER_HOST,
b.JP_SITE,b.JP_APPSERVICE_NAME,b.JP_APPSERVICE_ID,b.JP_VERUMIDENTIFIER
FROM SCUSER.PROBSUMMARYM1 a
LEFT JOIN SCUSER.DEVICEM1 b ON (DECODE(a.LOGICAL_NAME,b.LOGICAL_NAME,
1,0)=1
)
where a.SEVERITY_CODE IN ('P1/S1','P1/S2','P1/S3')
and a.CPR_BUSINESS_OPERATIONS = 'f'
and a.ASSIGNMENT like 'X%'
and (TRUNC(OPEN_TIME_EST) >=TRUNC(SYSDATE-30)
OR TRUNC(CLOSE_TIME_EST) >=TRUNC(SYSDATE-30)
)
and (a.JP_CONFIDENTIAL IS NULL
OR a.JP_CONFIDENTIAL= 'f'
)
]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Incorrect parameter count in the call to native function 'DECODE'
Could someone please help ..I am stuck with this from morning!!..
I'm creating a registration form for my web application and I'm getting the following error when I try to access register a new user:
java.lang.VerifyError: (class: eBooks/Data/UserDB, method: <init> signature: ()V) Constructor must call super() or this() java.lang.VerifyError: (class: eBooks/Data/UserDB, method: <init> signature: ()V) Constructor must call super() or this()
at eBooks.controller.RegisterUserServlet.doPost(RegisterUserServlet.java:62)
This is the UserDB class:
package eBooks.Data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import eBooks.business.User;
import eBooks.util.DBUtil;
public class UserDB {
public static int insert(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query =
"INSERT INTO User (fName, lName, email_address, password, dataOfBirth, phone,"
+ " address, city, state, country, zipcode, accountType)"
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getfName());
ps.setString(2, user.getlName());
ps.setString(3, user.getEmailAddress());
ps.setString(4, user.getPassword());
ps.setString(5, user.getDateOfBirth());
ps.setString(5, user.getPhone());
ps.setString(6, user.getAddress());
ps.setString(7, user.getCity());
ps.setString(8, user.getCountry());
ps.setString(9, user.getState());
ps.setString(10, user.getZipcode());
//ps.setString(11, user.getAccountType()); -- Ask Jassin
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static int update(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE User SET"
+ "fName = ?"
+ "lName = ?"
+ "password = ?"
+ "dateOfBirth = ?"
+ "phone = ?"
+ "address = ?"
+ "city = ?"
+ "state_or_Region = ?"
+ "country = ?"
+ "zip = ?"
+ ""
+ "WHERE email_address= ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getfName());
ps.setString(2, user.getlName());
ps.setString(3, user.getEmailAddress());
ps.setString(4, user.getPassword());
ps.setString(5, user.getDateOfBirth());
ps.setString(5, user.getPhone());
ps.setString(6, user.getAddress());
ps.setString(7, user.getCity());
ps.setString(8, user.getCountry());
ps.setString(9, user.getState());
ps.setString(10, user.getZipcode());
//ps.setString(11, user.getAccountType()); -- Ask Jassin
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static int delete(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "DELETE FROM User" +
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getEmailAddress());
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static boolean emailExists(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT email_address FROM User"+
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
return rs.next();
}
catch(SQLException e)
{
e.printStackTrace();
return false;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static User selectUser(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM User"+
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
User user = null;
if (rs.next())
{
user = new User();
user.setfName(rs.getString("fName"));
user.setlName(rs.getString("lName"));
user.setEmailAddress(rs.getString("emailAddress"));
user.setPassword(rs.getString("password"));
user.setPhone(rs.getString("phone"));
user.setDateOfBirth(rs.getString("dateOfBirth"));
user.setAddress(rs.getString("address"));
user.setCity(rs.getString("city"));
user.setCountry(rs.getString("country"));
user.setState(rs.getString("state"));
user.setZipcode(rs.getString("zip"));
// user.setAccountType(rs.getString("accountType")); -- Ask Jassin
}
return user;
}
catch(SQLException e)
{
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
This is the RegisterUserServlet:
package eBooks.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import eBooks.business.User;
import eBooks.business.Account;
import eBooks.Data.UserDB;
public class RegisterUserServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession();
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String emailAddress = request.getParameter("emailAddress");
String password = request.getParameter("password");
String dateOfBirth = request.getParameter("dateOfBirth");
String phone = request.getParameter("phohe");
String address = request.getParameter("address");
String city = request.getParameter("city");
String country = request.getParameter("country");
String state = request.getParameter("country");
String accountType = request.getParameter("accountType");
//TO DO: Account acctTypeList = request.getParameter("acctTypeList"); add this an object first
User user = new User();
user.setfName(fName);
user.setlName(lName);
user.setEmailAddress(emailAddress);
user.setPassword(password);
user.setDateOfBirth(dateOfBirth);
user.setAddress(address);
user.setCity(city);
user.setCountry(country);
user.setState(state);
user.setZipcode(phone);
//TODO: user.setAccountType(accTypeList); -- Ask Jassin
// Add information to the database
if(UserDB.emailExists(emailAddress))
UserDB.update(user);
else
UserDB.update(user);
session.setAttribute("User", user);
Cookie emailCookie = new Cookie("emailCookie", emailAddress);
emailCookie.setMaxAge(60*60*24*365*2);
emailCookie.setPath("/");
response.addCookie(emailCookie);
String url = "WEB-INF/view/registration_confirmation.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
I'm new to web development and I just need a push in the right direction to fix this issue.
I'm using glassfish and mysql.
Just fixed the problem – moved all the files to a new project and manually created the web.xml and it's is working fine now. Thanks #ErnestFriedman-Hill
I'm using Tomcat 7, MySql Workbench 5.2.27, JSF 2.0 and this exception comes from the ManagedBean(TripTableBean.java) of my web page(Trip Record.xhtml). It comes up whenever I click to go to Trip Record.xhtml after navigating through my other web pages. Pardon my horrible codes...
TripTableBean.java
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:114)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at Database.DBController.readRequest(DBController.java:21)
at Database.TripTableBean.retrieve(TripTableBean.java:389)
at Database.TripTableBean.<init>(TripTableBean.java:69)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
at org.apache.el.parser.AstValue.getTarget(AstValue.java:94)
at org.apache.el.parser.AstValue.getType(AstValue.java:82)
at org.apache.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:176)
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
at org.primefaces.component.datatable.DataTable.isLazy(DataTable.java:904)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:177)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:103)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The method where the exception originates : (TripTableBean.java:389) points to rs2 = db.readRequest(dbQuery2);
public void retrieve() throws SQLException, NamingException {
t = new ArrayList<TripSearchy>();
ResultSet rs = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
DBController db = new DBController();
db.setUp();
//SQL: change select statement here
String dbQuery = "select * from (trip inner join agency on trip.id=agency.trip_id inner join tourguide on trip.id=tourguide.trip_id inner join accommodation on trip.id=accommodation.trip_id)";
rs = db.readRequest(dbQuery);
try{
while(rs.next()){
//add to list
id = rs.getInt("trip.id");
name = rs.getString("trip.name");
startDate = rs.getString("trip.startDate");
endDate = rs.getString("trip.endDate");
costOfTrip = rs.getString("trip.costOfTrip");
maxNoOfParticipants = rs.getString("trip.maxNoOfParticipants");
closingDateOfApplication = rs.getString("trip.closingDateOfApplication");
instructions = rs.getString("trip.instructions");
psea = rs.getString("trip.psea");
fasop = rs.getString("trip.fasop");
ktpiop = rs.getString("trip.ktpiop");
opId = rs.getInt("trip.overseasprogramme_id");
overseasProgramme = rs.getString("trip.overseasProgrammeName");
tourGuideName = rs.getString("tourguide.name");
tourGuideContact = rs.getString("tourguide.contact");
companyName = rs.getString("agency.companyName");
agentName = rs.getString("agency.agentName");
agentContact = rs.getString("agency.agentContact");
airlineChoice = rs.getString("agency.airlineChoice");
placeOfLodging = rs.getString("accommodation.placeOfLodging");
startDateOfLodging = rs.getString("accommodation.startDate");
endDateOfLodging = rs.getString("accommodation.endDate");
String dbQuery2 = "Select * from tripstaff where trip_id = '" + id + "'";
rs2 = db.readRequest(dbQuery2);
String lec;
ArrayList<String> dbQueryM = new ArrayList<String>();
while (rs2.next()){
lec = rs2.getString("tripstaff.lecturer_id");
dbQueryM.add("Select * from lecturer where id = '" + lec + "'");
}
ArrayList<NypStaff> nsf = new ArrayList<NypStaff>();
for (int i = 0; i < dbQueryM.size(); i++){
rs3 = db.readRequest(dbQueryM.get(i));
if (rs3.next()){
NypStaff temp = new NypStaff();
//set values retrieved from database into attributes
temp.setName(rs3.getString("lecturer.name"));
temp.setEmail(rs3.getString("lecturer.email"));
temp.setContact(rs3.getString("lecturer.contact"));
nsf.add(temp);
}
}
try {
Calendar c = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
Calendar c3 = Calendar.getInstance();
Calendar c4 = Calendar.getInstance();
Calendar c5 = Calendar.getInstance();
try {
c.setTime(formatter.parse(startDate));
c2.setTime(formatter.parse(endDate));
c3.setTime(formatter.parse(startDateOfLodging));
c4.setTime(formatter.parse(endDateOfLodging));
c5.setTime(formatter.parse(closingDateOfApplication));
}
catch (ParseException e1) {
e1.printStackTrace();
}
c.add(Calendar.DATE, 1);
c2.add(Calendar.DATE, 1);
c3.add(Calendar.DATE, 1);
c4.add(Calendar.DATE, 1);
c5.add(Calendar.DATE, 1);
startDate = formatter.format(c.getTime());
endDate = formatter.format(c2.getTime());
startDateOfLodging = formatter.format(c3.getTime());
endDateOfLodging = formatter.format(c4.getTime());
closingDateOfApplication = formatter.format(c5.getTime());
startDated = formatter.parse(startDate);
endDated = formatter.parse(endDate);
startDatedOfLodging = formatter.parse(startDateOfLodging);
endDatedOfLodging = formatter.parse(endDateOfLodging);
closingDatedOfApplication = formatter.parse(closingDateOfApplication);
c.add(Calendar.DATE, -1);
c2.add(Calendar.DATE, -1);
c3.add(Calendar.DATE, -1);
c4.add(Calendar.DATE, -1);
c5.add(Calendar.DATE, -1);
startDate = formatter.format(c.getTime());
endDate = formatter.format(c2.getTime());
startDateOfLodging = formatter.format(c3.getTime());
endDateOfLodging = formatter.format(c4.getTime());
closingDateOfApplication = formatter.format(c5.getTime());
}
catch (ParseException e1) {
e1.printStackTrace();
}
t.add(new TripSearchy (id, opId, overseasProgramme, name, startDated, startDate, endDated, endDate, costOfTrip, ns, nsf, staffName, tourGuideName, tourGuideContact, companyName, agentName, agentContact, airlineChoice, placeOfLodging, startDatedOfLodging, startDateOfLodging, endDatedOfLodging, endDateOfLodging, maxNoOfParticipants, closingDatedOfApplication, closingDateOfApplication, instructions, psea, fasop, ktpiop));
}
}catch (Exception e) {
e.printStackTrace();
}
db.terminate();
}
It seems that I have exhausted my connection =\ May I know how do I reduce my usage of the connection/increase the capacity of the connection?
Update:
DBController.java
public class DBController {
private DataSource ds;
Connection con;
public void setUp() throws NamingException{
//connect to database
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/it2299");
}
public ResultSet readRequest(String dbQuery){
ResultSet rs=null;
try{
con = ds.getConnection();
Statement stmt = con.createStatement();
rs = stmt.executeQuery(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return rs;
}
public int updateRequest(String dbQuery){
int count=0;
try{
con = ds.getConnection();
Statement stmt = con.createStatement();
count=stmt.executeUpdate(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return count;
}
public void terminate(){
try {con.close();}
catch(Exception e){e.printStackTrace();}
}
}
Update 2:
This exception occurs when the scope of my ManagedBean(TripTableBean.java) is ViewScoped, it doesn't occur when I change it to SessionScoped. However if it is SessionScoped, I'll need to find a way to kill session and recreate a new session whenever I come to this web page if not my dataTable on this page won't load updated changes from the database.
As you hinted yourself, your code is horrible. You need to ensure that all JDBC resources are acquired and closed in the shortest possibe scope in a try-finally block. Rewrite your code so that it follows the following standard JDBC idiom:
public List<Entity> list() throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<Entity> entities = new ArrayList<Entity>();
try {
connection = Database.getConnection();
statement = connection.prepareStatement("SELECT id, foo, bar FROM entity");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setFoo(resultSet.getString("foo"));
entity.setBar(resultSet.getString("bar"));
entities.add(entity);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return entities;
}
See also:
If I use a singleton class for a database connection, can one user close the connection for everybody?
JDBC MySql connection pooling practices to avoid exhausted connection pool
what are you connection pool settings can you post whats in DBController?
Tip: db.terminate() should be in finally{} block, may be you are lossing connections on exceptions.
Update:
Posting some of the modifications that might help you, but DO CLEAN UP THE CODE for maintenance sake. Look for comments where changes have been made.
public class DBController {
private DataSource ds;
private Connection con;// NEW CHANGE
public void setUp() throws NamingException{
//connect to database
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/it2299");
con = ds.getConnection(); // NEW CHANGE
}
public ResultSet readRequest(String dbQuery){
ResultSet rs=null;
try{
//REMOVED CODE FROM HERE
Statement stmt = con.createStatement();
rs = stmt.executeQuery(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return rs;
}
public int updateRequest(String dbQuery){
int count=0;
try{
//REMOVED CODE FROM HERE
Statement stmt = con.createStatement();
count=stmt.executeUpdate(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return count;
}
public void terminate(){
try {con.close();}
catch(Exception e){e.printStackTrace();}
}
}
Code cannot be improved beyond this by me, but I suggest have a look at some of the best practices over net and as suggested by #BalusC.
Remember: To close the connection object when done.