Connection pool issue with Bean Datasource - Jasperserver - mysql

I have created a bean data source to connect to my database. My objective of creating this datasource is to switch datasource as per a parameter given. But when I run reports using the bean data source, it does not release the connection back into the pool. My connection pool size is 20, so when I run the 21st report, server hangs printing the following message on the JConsole
Name: pool-7-thread-9
State: WAITING on org.apache.commons.pool.impl.GenericObjectPool#1f8ed84
Total blocked: 0 Total waited: 4
Stack trace:
java.lang.Object.wait(Native Method)
java.lang.Object.wait(Object.java:485)
org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:748)
org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:95)
com.loits.jasper.ds.SwitchDS.setReportParameterValues(SwitchDS.java:75)
com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl.fillReport(EngineServiceImpl.java:1725)
com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl$ReportFill.runWithDataSource(EngineServiceImpl.java:1086)
com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl$ReportFill.runReport(EngineServiceImpl.java:1015)
com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl$ReportRunnable.run(EngineServiceImpl.java:908)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
Here what I have done in my bean
package com.loits.jasper.ds;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.sql.SQLException;
import net.sf.jasperreports.engine.JRParameter;
import org.springframework.security.context.SecurityContextHolder;
import com.jaspersoft.jasperserver.api.metadata.jasperreports.domain.ReportDataSource;
import com.jaspersoft.jasperserver.api.metadata.jasperreports.service.ReportDataSourceService;
import com.jaspersoft.jasperserver.api.metadata.user.domain.Role;
import com.jaspersoft.jasperserver.api.metadata.user.domain.client.ProfileAttributeImpl;
import com.jaspersoft.jasperserver.api.metadata.user.domain.impl.client.MetadataUserDetails;
import com.jaspersoft.jasperserver.api.common.domain.ExecutionContext;
import com.jaspersoft.jasperserver.api.common.service.BeanForInterfaceImplementationFactory;
import com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.JdbcDataSourceService;
import com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.JdbcReportDataSourceServiceFactory;
import com.jaspersoft.jasperserver.war.common.JasperServerUtil;
import com.jaspersoft.jasperserver.api.metadata.common.service.RepositoryService;
public class SwitchDS implements ReportDataSourceService {
private JdbcDataSourceService connection;
private RepositoryService repositoryService;
private BeanForInterfaceImplementationFactory dataSourceServiceFactory;
// private DataSourceServiceFactory dataSourceServiceFactory;
public SwitchDS(RepositoryService repositoryService,
BeanForInterfaceImplementationFactory dsServiceFactory) {
super();
this.repositoryService = repositoryService;
this.dataSourceServiceFactory = dsServiceFactory;
System.out.println("repositoryService " + repositoryService);
System.out.println("dataSourceServiceFactory "
+ dataSourceServiceFactory);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public void setReportParameterValues(Map parametersValue) {
String ds_name = (String) parametersValue.get("P_SCM");
String ds_uri = "";
if(ds_name.equalsIgnoreCase("D_001_S")){
ds_uri = "/datasources/lolc_fusion";
}
else if(ds_name.equalsIgnoreCase("D_005_S")){
ds_uri = "/datasources/lofc_fusion";
}
else if(ds_name.equalsIgnoreCase("D_009_S")){
ds_uri = "/datasources/lomc_fusion";
}
else if(ds_name.equalsIgnoreCase("D_010_S")){
ds_uri = "/datasources/clc_fusion";
}
else if(ds_name.equalsIgnoreCase("D_025_S")){
ds_uri = "/datasources/lofac_fusion";
}
if(connection == null){
connection = getRepositoryDatasource(ds_uri);
}
try {
parametersValue.put(JRParameter.REPORT_CONNECTION, connection
.getDataSource().getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
}
public JdbcDataSourceService getRepositoryDatasource(String repositoryURI) {
try {
ExecutionContext context = JasperServerUtil.getExecutionContext();
ReportDataSource datasource = (ReportDataSource) repositoryService
.getResource(context, repositoryURI);
System.out.println("datasource " + datasource.getName());
System.out.println("datasource class " + datasource.getClass());
JdbcReportDataSourceServiceFactory factory = (JdbcReportDataSourceServiceFactory) dataSourceServiceFactory
.getBean(datasource.getClass());
JdbcDataSourceService DSservice = (JdbcDataSourceService) factory
.createService(datasource);
return DSservice;
} catch (Exception ex) {
System.out.println(ex);
return null;
}
}
#Override
public void closeConnection() {
if (connection != null) {
connection.closeConnection();
System.out.println("Connection closed .. ");
}
}
public static void main(String[] args) {
}
}

Seems to me like you're closing the connection instead of returning it to the pool.
Simon

Related

Received Data Provider Mismatch error

Tried below code but receiving Data Provider Mismatch error. Could anyone help out on this?
package appModules;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
public class NewTest {
public WebDriver driver;
public WebDriverWait wait;
String appURL =
"https://dev.agencyport.rsagroup.ca:8443/agencyportal/ProcessLogoff";
//Locators
private By username = By.id("USERID");
private By password = By.id("PASSWORD");
#BeforeClass
public void testSetup() {
System.setProperty("webdriver.firefox.marionette",
"C:\\Automation\\geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider = "login")
public void Login(String Username, String Password) {
driver.findElement(username).sendKeys(Username);
driver.findElement(password).sendKeys(Password);
}
#DataProvider (name="login")
public Object[][] dp() throws Exception{
Object[][] arrayObject =
getExcelData("C:\\Automation\\testData.xls","New");
return arrayObject;
}
public String[][] getExcelData(String fileName, String sheetName) throws
Exception {
String[][] arrayExcelData = null;
try {
FileInputStream fs = new FileInputStream(fileName);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet(sheetName);
int totalNoOfCols = sh.getColumns();
System.out.println(totalNoOfCols);
int totalNoOfRows = sh.getRows();
System.out.println(totalNoOfRows);
arrayExcelData = new String[totalNoOfRows-1][totalNoOfCols];
for (int i=1 ; i <totalNoOfRows; i++) {
for (int j=0; j <totalNoOfCols; j++) {
arrayExcelData[i-1][j] = sh.getCell(j, i).getContents();
System.out.println(arrayExcelData[i-1][j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
#Test
public void tearDown() {
driver.quit();
}
}
Received below error -
org.testng.internal.reflect.MethodMatcherException:
Data provider mismatch
Method: Login([Parameter{index=0, type=java.lang.String,
declaredAnnotations=[]}, Parameter{index=1, type=java.lang.String,
declaredAnnotations=[]}])
Arguments: [(java.lang.String) agent,(java.lang.String) password,
(java.lang.String) ]
atorg.testng.internal.reflect.DataProviderMethodMatcher.getConformingArguments(DataProviderMethodMatcher.java:45)
at org.testng.internal.Parameters.injectParameters(Parameters.java:796)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:982)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)`
You are passing return value of arrayObject with incorrect Data Type,
You need to get String value from Excel File in Data Provider Method, and That you need to pass in Object.
Refer below Example, for Reference:
#DataProvider
public Iterator<Object[]> getTestData()
{
ArrayList<Object[]> testdata = new ArrayList<Object[]>();
try {
reader = new excelUtility(excelTestDataFile);
} catch (Exception e) {
e.printStackTrace();
}
sheetName = className;
for (int rowNumber = 2; rowNumber <= reader.getRowCount(sheetName); rowNumber++) {
String caseNo = reader.getCellData(sheetName, "Case", rowNumber);
String emailid = reader.getCellData(sheetName, "Email ID", rowNumber);
String password = reader.getCellData(sheetName, "Password", rowNumber);
String message = reader.getCellData(sheetName, "Expected Result", rowNumber);
Object ob[] =
{ caseNo, emailid, password, message };
testdata.add(ob);
}
return testdata.iterator();
}
And this is the #Test Receiver of Data Provider:
#Test(dataProvider = "getTestData")
public void calllogin(String caseNO, String emailid, String password, String expectedResult) throws Exception
{
******
}

NetworkOnMainThreadException when trying to read a json file

Good morning together from Germany!
I am trying to read a little json file from a webserver. When I start the app, I got the error message: android.os.NetworkOnMainThreadException.
The Target should be, that logcat is showing my json content:
{"first":"one","second":"two"}
Web server is working. When I access: 127.0.0.1/index.php, the browser shows me the upper line.
This is my Main:
package com.example.u0017007.jsonclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://127.0.0.1:80/index.php");
StringBuilder stringBuilder = new StringBuilder();
try {
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
Log.i(this.getClass().getSimpleName(), stringBuilder.toString());
} else {
Log.e(this.getClass().getSimpleName(), "Fehler");
}
} catch (ClientProtocolException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
}
}
}
That is the error log
FATAL EXCEPTION: main
Process: com.example.u0017007.jsonclient, PID: 16115
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u0017007.jsonclient/com.example.u0017007.jsonclient.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
at java.net.Socket.connect(Socket.java:586)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at com.example.u0017007.jsonclient.MainActivity.onCreate(MainActivity.java:29)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756
There are related questions that you can find and make use of them, but to give you the gist of the solutions available - you can solve them using any of the approaches given below:
You can refrain writing any Network related calls in your Main UI thread but use an AsyncTask to achieve what you want to, in it.
You can add the following code into your Main file by adding the following import as well.
The import:
import android.os.StrictMode;
The code:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Tomcat cannot find JDBC driver when connecting to DB [duplicate]

This question already has an answer here:
jdbc to MYSQL error: No suitable driver found for jdbc:mysql://localhost:3306/test?user='root'&password='' [duplicate]
(1 answer)
Closed 7 years ago.
I've put mysql driver in .../ROOT/WEB-INF/lib and Tomcat 8.0/lib but it has no effect. I'm using the following class to connect to DB:
package db;
import java.sql.*;
public class ConnectToDB implements AutoCloseable {
Connection con;
public ConnectToDB(String server, String database, String user,
String password) throws SQLException {
con = DriverManager.getConnection("jdbc:mysql://" + server + "/"
+ database, user, password);
}
#Override
public void close() throws SQLException {
con.close();
}
public Connection getConnection() {
return con;
}
}
The following classes are included in the Eclipse project:
1. src/nr3/model
package nr3.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import db.ConnectToDB;
public class MusikkHandler {
private ConnectToDB db;
private Connection con;
private String tableName;
private PreparedStatement pstmtGetRows;
public MusikkHandler(String server, String database, String user,
String password) throws SQLException {
db = new ConnectToDB(server, database, user, password);
con = db.getConnection();
tableName = "album";
}
public void close() throws SQLException {
db.close();
}
public ArrayList<Album> getRows(String genre) throws SQLException {
ArrayList<Album> list = new ArrayList<Album>();
pstmtGetRows = con.prepareStatement("SELECT * FROM " + tableName
+ " WHERE SJANGER = ?");
pstmtGetRows.setString(1, genre);
ResultSet rs = pstmtGetRows.executeQuery();
while (rs.next()) {
list.add(new Album(rs.getString(1), rs.getString(2), rs.getInt(3),
rs.getInt(4), rs.getString(5)));
}
rs.close();
pstmtGetRows.close();
return list;
}
}
-
package nr3.model;
public class Album {
private String tittel;
private String artist;
private int spor;
private int utgitt;
private String sjanger;
public Album (String artist, String tittel, int spor, int utgitt, String sjanger){
setArtist(artist);
setTittel(tittel);
setUtgitt(utgitt);
setSpor(spor);
setSjanger(sjanger);
}
public Album(){
this(null, null, 0, 0, null);
}
public void setTittel(String tittel){
this.tittel = tittel;
}
public void setArtist(String artist){
this.artist = artist;
}
public void setSpor(int spor) {
this.spor = spor;
}
public void setUtgitt(int utgitt) {
this.utgitt = utgitt;
}
public void setSjanger(String sjanger) {
this.sjanger = sjanger;
}
public String getTittel() {
return tittel;
}
public String getArtist() {
return artist;
}
public int getSpor() {
return spor;
}
public int getUtgitt() {
return utgitt;
}
public String getSjanger() {
return sjanger;
}
public String toString(){
return getTittel() + " (" + getArtist() + ")" + " Utgitt: "
+ getUtgitt();
}
}
2. src/nr3/servlets
package nr3.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nr3.model.Album;
import nr3.model.MusikkHandler;
public class MusikkValg extends HttpServlet {
private static final long serialVersionUID = 428937262021570370L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String genre = request.getParameter("sjanger");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
MusikkHandler mh;
out.println("<html>");
out.println("<head>");
out.println("<title>Musikk</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>MUSIKK-ANBEFALINGER</h1>");
out.println("<br/>");
out.println("<br/>");
out.println("<h3>Da bør du kanskje forsøke en av disse:</h3>");
out.println("<br/>");
out.println("<br/>");
try {
mh = new MusikkHandler(" ", " ", " ", " ");
for (Album a : mh.getRows(genre))
out.println("<p>" + a + "</p>");
} catch (SQLException e) {
e.printStackTrace(out);
}
out.println("</body>");
out.println("</html>");
}
}
Update: I've got the following error stacktrace in the browser:
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost/pg3100 at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
db.ConnectToDB.(ConnectToDB.java:10) at
nr3.model.MusikkHandler.(MusikkHandler.java:20) at
nr3.servlets.MusikkValg.doGet(MusikkValg.java:39) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:618) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:725) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2381)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2370)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
First, you must register your driver at the beginning so DriverManager can user it when getting a connection. It might vary on the implementation.
DriverManager.registerDriver (new com.mysql.jdbc.Driver());
or
Class.forName("com.mysql.jdbc.Driver");
Then you can perform a getConnection() because you'll have a driver registered to be used by DriverManager.
Second: /webapps/ROOT/WEB-INF/lib is a different context and its libraries won't be available for your app unless you are setting the context path of your app as shown in this question. If you wanna add it, try placing your JDBC driver on /webapps/<yourapp>/lib first. Tomcat lib should work as well (but it's not nice when you distribute your app, might conflict with other apps deployed there, using different versions of the driver, etc.)
Third: When asking here, try to reduce your verifiable example to something readable. There's a lot of code which is not relevant to your problem. Reducing makes it easier to read your question and provide help.

Groovy: RedHat: java.sql.SQLException: No suitable driver found for jdbc:mysql:

I tryed to execute groovy-script under RH shell
[localhost]# groovy /home/rualas4/script.groovy
but received exception
Caught: java.sql.SQLException: No suitable driver found for jdbc:mysql:/localhost:3306/
java.sql.SQLException: No suitable driver found for jdbc:mysql:/localhost:3306/
at script.run(script.groovy:13)
I had installed next packages:
unixODBC-2.2.14-12.el6_3.x86_64
mysql-connector-odbc-5.3.2-1.el6.x86_64
and my code:
#GrabConfig(systemClassLoader = true)
#Grab(group='mysql', module='mysql-connector-java', version='5.1.25')
import groovy.sql.Sql
import groovy.io.FileType
println "Initialize connection"
url="jdbc:mysql://localhost:3306/"
username = "test"
password = "test"
driver = "com.mysql.jdbc.Driver"
sql = Sql.newInstance(url, username, password, driver)
also I have mysql-connector-java-5.1.25-bin.jar in my groovy (/opt/groovy/lib) directory
Please, provide a solution for resolve error exception
You are missing a / character in your connection url, when com.mysql.jdbc.Driver parse your url is looking for jdbc:mysql://:
com.mysql.jdbc.Driver class:
package com.mysql.jdbc;
import java.sql.SQLException;
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
// ~ Static fields/initializers
// ---------------------------------------------
//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
// ~ Constructors
// -----------------------------------------------------------
/**
* Construct a new driver and register it with DriverManager
*
* #throws SQLException
* if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}
com.mysql.jdbc.NonRegisteringDriver class:
package com.mysql.jdbc;
import java.sql.SQLException;
public class NonRegisteringDriver implements java.sql.Driver {
...
private static final String URL_PREFIX = "jdbc:mysql://";
...
public Properties parseURL(String url, Properties defaults)
throws java.sql.SQLException {
Properties urlProps = (defaults != null) ? new Properties(defaults)
: new Properties();
if (url == null) {
return null;
}
if (!StringUtils.startsWithIgnoreCase(url, URL_PREFIX)
&& !StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)
&& !StringUtils.startsWithIgnoreCase(url,
LOADBALANCE_URL_PREFIX)
&& !StringUtils.startsWithIgnoreCase(url,
REPLICATION_URL_PREFIX)) {
return null;
}
...
}
therefore:
Change:
jdbc:mysql:/localhost:3306/
To:
jdbc:mysql://localhost:3306/
Hope this helps,

SSL Server Exception: javax.net.ssl.SSLException

I am creating a SSL Server and Client in Java. The point of the program is to mimic a movie theater program. I can establish the connection but when I attempt to "reserve" a seat the program crashes. I get the following error:
Server aborted: javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
This is my Server Code
// SSL Server
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
public class SSL_Server {
public static void main(String[] args) {
int port = 2018;
System.setProperty("javax.net.ssl.keyStore","mySrvKeystore");
System.setProperty("javax.net.ssl.keyStorePassword","123456");
ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
ServerSocket ssocket = null;
System.out.println("SSL_Server started");
final ExecutorService threadPool = Executors.newCachedThreadPool();
try {
ssocket = ssocketFactory.createServerSocket(port);
InetAddress myIP =InetAddress.getLocalHost();
System.out.println(myIP.getHostAddress());
while(true){
Socket aClient = ssocket.accept();
//create a new thread for every client
threadPool.submit(new SSL_ClientHandler(aClient));
}
}
catch(Exception e) {
System.err.println("Server aborted:" + e);
} finally {
try{
ssocket.close();
} catch (Exception e){
System.err.println("could not close connection properly" + e);
}
}
System.out.println("connection was closed successfully");
}
}
The following is my client code
//SSL Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
public class TCP_Client {
public static void main(String[] args) throws IOException{
// SSL_Client newClient = new SSL_Client();
// Lock lock = new ReentrantLock();
boolean validInput = false;
BufferedReader din;
PrintStream pout;
int port = 2018;
BufferedReader stdinp = new BufferedReader(new InputStreamReader(System.in));
String line = "done";
StringTokenizer st;
String hostname;
String task = "done";
if(args.length>0)
hostname = args[0];
else
hostname = "localhost";
SocketFactory socketFactory = SSLSocketFactory.getDefault();
//Socket socket = socketFactory.createSocket(hostname, port);
while(true)
{
try{
//read input
while(!validInput)
{
System.out.println("Please enter a valid command or 'done' to finish.");
line = stdinp.readLine();
st = new StringTokenizer(line);
task = st.nextToken();
if(task.equals("reserve") || task.equals("search") || task.equals("delete") || task.equals("getinfo") || task.equals("done"))
{
validInput =true;
break;
}
System.out.println("Invalid command. Please enter another command or 'done' to escape.");
}
if(task.equals("done"))
{
break;
}
validInput = false;//reset for next line read in
//create a new socket every time
//Socket socket = new Socket(hostname, port);
Socket socket = socketFactory.createSocket(hostname, port);
din = new BufferedReader (new InputStreamReader (socket.getInputStream()));
pout = new PrintStream (socket.getOutputStream());
pout.println(line);
pout.flush();
//print out response from server
System.out.println(din.readLine());
} catch (Exception e){
System.err.println("Server aborted: " + e);
}
}
}
}
"Unable to find valid certification path to requested target" means that your truststore doesn't trust the server certificate. Import it into your truststore, or have it signed by a recognized CA.