I am currently attempting to connect mysql using calcite.
However, I had problems executing SQL statements
When I use this sql to excute,it works.
ResultSet resultSet = statement.executeQuery(
"select * from ex.depts");
But I would like to access a table named like this "primary_test",it failed.
Exception in thread "main" java.sql.SQLException: Error while executing SQL "select * from ex.primary_test": From line 1, column 15 to line 1, column 29: Object 'primary_test' not found within 'ex'
at org.apache.calcite.avatica.Helper.createException(Helper.java:56)
at org.apache.calcite.avatica.Helper.createException(Helper.java:41)
at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:163)
at org.apache.calcite.avatica.AvaticaStatement.executeQuery(AvaticaStatement.java:227)
at CalciteMysqlConnectionIns.main(CalciteMysqlConnectionIns.java:44)
Caused by: org.apache.calcite.runtime.CalciteContextException: From line 1, column 15 to line 1, column 29: Object 'primary_test' not found within 'ex'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.apache.calcite.runtime.Resources$ExInstWithCause.ex(Resources.java:463)
at org.apache.calcite.sql.SqlUtil.newContextException(SqlUtil.java:787)
at org.apache.calcite.sql.SqlUtil.newContextException(SqlUtil.java:772)
at org.apache.calcite.sql.validate.SqlValidatorImpl.newValidationError(SqlValidatorImpl.java:4788)
at org.apache.calcite.sql.validate.IdentifierNamespace.resolveImpl(IdentifierNamespace.java:166)
at org.apache.calcite.sql.validate.IdentifierNamespace.validateImpl(IdentifierNamespace.java:177)
at org.apache.calcite.sql.validate.AbstractNamespace.validate(AbstractNamespace.java:84)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateNamespace(SqlValidatorImpl.java:977)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateQuery(SqlValidatorImpl.java:953)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateFrom(SqlValidatorImpl.java:3050)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateFrom(SqlValidatorImpl.java:3032)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateSelect(SqlValidatorImpl.java:3302)
at org.apache.calcite.sql.validate.SelectNamespace.validateImpl(SelectNamespace.java:60)
at org.apache.calcite.sql.validate.AbstractNamespace.validate(AbstractNamespace.java:84)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateNamespace(SqlValidatorImpl.java:977)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateQuery(SqlValidatorImpl.java:953)
at org.apache.calcite.sql.SqlSelect.validate(SqlSelect.java:216)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateScopedExpression(SqlValidatorImpl.java:928)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validate(SqlValidatorImpl.java:632)
at org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(SqlToRelConverter.java:556)
at org.apache.calcite.prepare.Prepare.prepareSql(Prepare.java:265)
at org.apache.calcite.prepare.Prepare.prepareSql(Prepare.java:231)
at org.apache.calcite.prepare.CalcitePrepareImpl.prepare2_(CalcitePrepareImpl.java:772)
at org.apache.calcite.prepare.CalcitePrepareImpl.prepare_(CalcitePrepareImpl.java:636)
at org.apache.calcite.prepare.CalcitePrepareImpl.prepareSql(CalcitePrepareImpl.java:606)
at org.apache.calcite.jdbc.CalciteConnectionImpl.parseQuery(CalciteConnectionImpl.java:229)
at org.apache.calcite.jdbc.CalciteMetaImpl.prepareAndExecute(CalciteMetaImpl.java:550)
at org.apache.calcite.avatica.AvaticaConnection.prepareAndExecuteInternal(AvaticaConnection.java:675)
at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:156)
... 2 more
Caused by: org.apache.calcite.sql.validate.SqlValidatorException: Object 'primary_test' not found within 'ex'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.apache.calcite.runtime.Resources$ExInstWithCause.ex(Resources.java:463)
at org.apache.calcite.runtime.Resources$ExInst.ex(Resources.java:572)
... 30 more
I have used many different query like
ResultSet resultSet = statement.executeQuery(
"select * from ex.\"primary_test\"");
but it doesn't work.
Could someone help me with this question?
my code is like following:
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.apache.calcite.adapter.jdbc.JdbcSchema;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.commons.dbcp2.BasicDataSource;
public class CalciteMysqlConnectionIns {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.apache.calcite.jdbc.Driver");
Properties info = new Properties();
info.setProperty("lex", "JAVA");
Connection connection = DriverManager.getConnection("jdbc:calcite:", info);
CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
SchemaPlus rootSchema = calciteConnection.getRootSchema();
// 本地Schema.
// Schema schema = ReflectiveSchema.create(calciteConnection, rootSchema, "hr",
// new HrSchema());
Class.forName("com.mysql.jdbc.Driver");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:mysql://192.168.130.7/hr");
dataSource.setUsername("root");
dataSource.setPassword("123456");
Schema schema = JdbcSchema.create(rootSchema, "ex", dataSource, null, "sql_learn");
rootSchema.add("ex", schema);
// System.out.println(calciteConnection.getMetaData());
DatabaseMetaData databaseMetaData = calciteConnection.getMetaData();
// ResultSet rs = databaseMetaData.getTables(null, null, "%", new String[]{"TABLE"});
Statement statement = calciteConnection.createStatement();
ResultSet resultSet = statement.executeQuery(
"select * from ex.\"primary_test\"");
output(resultSet, System.out);
resultSet.close();
statement.close();
connection.close();
}
private static void output(ResultSet resultSet, PrintStream out) throws SQLException {
final ResultSetMetaData metaData = resultSet.getMetaData();
final int columnCount = metaData.getColumnCount();
// out.println(metaData.getColumnLabel(1) + " " + metaData.getColumnLabel(2));
// out.println(metaData.getColumnTypeName(1) + " " + metaData.getColumnTypeName(2));
while (resultSet.next()) {
for (int i = 1; ; i++) {
out.print(resultSet.getString(i));
if (i < columnCount) {
out.print(", ");
} else {
out.println();
break;
}
}
}
}
}
you can try this:
select * from ex.`primary_test`
Related
I have downloaded aws sdk and connected my account and the database. But now I do not know what I need to do next. How do insert, delete or create table through java on eclipse.
I know to do these in a local database. I tried changing the url in getConnection() function to the my endpoint on eclipse but I keep getting error stating
"Access denied for user 'aws'#'xxx.xxx.xxx.xxx' (using password: YES)" (real IP modified for security reasons).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private static final String url = "jdbc:mysql://aws.cyduxshnlizb.ap-south-1.rds.amazonaws.com:3306";
final private String user = "myusername";
final private String passwd = "mypassword";
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection(url,user,passwd);
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from feedback.comments");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into feedback.comments values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from feedback.comments");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from feedback.comments");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from feedback.comments where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from feedback.comments");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}
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.
I can get the metastore table information on my local mysql metastore setup with hive using the below program.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
public class MetaStoreTest {
public static void main(String[] args) throws Exception {
Connection conn = null;
try {
HiveConf conf = new HiveConf();
conf.addResource(new Path("/home/hadoop/hive-0.12.0/conf/hive-site.xml"));
Class.forName(conf.getVar(ConfVars.METASTORE_CONNECTION_DRIVER));
conn = DriverManager.getConnection(
conf.getVar(ConfVars.METASTORECONNECTURLKEY),
conf.getVar(ConfVars.METASTORE_CONNECTION_USER_NAME),
conf.getVar(ConfVars.METASTOREPWD));
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(
"select t.tbl_name, s.location from TBLS t " +
"join SDS s on t.sd_id = s.sd_id");
while (rs.next()) {
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}
}
finally {
if (conn != null) {
conn.close();
}
}
}
}
Currently am trying the above program to get the metastore tables from a remote metastore using thrift.In my current hive-site.xml i have these params,
hive.metastore.uris = thrift://host1:9083, thrift://host2:9083
hive.metastore.local = false
There is no params for :
javax.jdo.option.ConnectionDriverName, javax.jdo.option.ConnectionUserName, javax.jdo.option.ConnectionPassword
So, how can i fetch the metatable information over thrift protocol. I am running the above code on host2. Please suggest.
Also when i run the above code, it shows information on :
METASTORE_CONNECTION_DRIVER as derby connection embedded driver,
METASTORECONNECTURLKEY as jdbc:mysql://<host name>/<database name>?createDatabaseIfNotExist=true,
METASTORE_CONNECTION_USER_NAME as "APP" and
METASTOREPWD as "mine"
replace this section of your code :
conf.addResource(new Path("/home/hadoop/hive-0.12.0/conf/hive-site.xml"));
Class.forName(conf.getVar(ConfVars.METASTORE_CONNECTION_DRIVER));
conn = DriverManager.getConnection(
conf.getVar(ConfVars.METASTORECONNECTURLKEY),
conf.getVar(ConfVars.METASTORE_CONNECTION_USER_NAME),
conf.getVar(ConfVars.METASTOREPWD));
with the below :
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://host2:3306/metastore", "urusername", "urpassword");
[note :Change the metastore dbname, user and password accordingly as per your setup.]
now :
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("show tables");
while (rs.next()) {
System.out.println("Tables:" +rs.getString(1));
}
See are you getting the metastore table names or not.
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
I am trying to connect to oracle database 12c using java in eclipse.
This is the exception that keeps getting caught.
Exception in thread "main" java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:743)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:666)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:566)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBHelper.makeConnection(DBHelper.java:31)
at Main.main(Main.java:37)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:470)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:506)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:595)
at oracle.net.ns.NSProtocolStream.negotiateConnection(NSProtocolStream.java:246)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:264)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496)
... 7 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:161)
at oracle.net.nt.ConnOption.connect(ConnOption.java:159)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:428)
... 13 more
Below is what i've done
main.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] arg) throws SQLException{
DBHelper dbconn = new DBHelper("system", "reborn78");
Connection conn = dbconn.makeConnection();
ResultSet result = dbconn.runQuery(conn, "SELECT A,B FROM NEWS");
System.out.println(result);
}
}
DBHelper.java
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DBHelper {
private String userName;
private String passWord;
private final String url = "jdbc:oracle:thin:#localhost:1521/ORCL";
public DBHelper(String userName, String passWord) throws SQLException{
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
this.userName = userName;
this.passWord = passWord;
}
public Connection makeConnection() throws SQLException{
Properties props = new Properties();
props.setProperty("user", this.userName);
props.setProperty("password", this.passWord);
return DriverManager.getConnection(this.url,props);
}
public ResultSet runQuery(Connection conn, String sqlQuery) throws SQLException{
PreparedStatement preStatement;
ResultSet result;
Statement statement = conn.createStatement();
preStatement = conn.prepareStatement(sqlQuery);
statement.execute(sqlQuery);
result = preStatement.executeQuery();
return result;
}
}
below is my listener.ora file
# listener.ora Network Configuration File: E:\app\Usama\product\12.1.0\dbhome_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = CLRExtProc)
(ORACLE_HOME = E:\app\Usama\product\12.1.0\dbhome_1)
(PROGRAM = extproc)
(ENVS = "EXTPROC_DLLS=ONLY:E:\app\Usama\product\12.1.0\dbhome_1\bin\oraclr12.dll")
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
)
below is my tnsnames.ora file
# tnsnames.ora Network Configuration File: E:\app\Usama\product\12.1.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora
# Generated by Oracle configuration tools.
LISTENER_ORCL =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
ORACLR_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(CONNECT_DATA =
(SID = CLRExtProc)
(PRESENTATION = RO)
)
)
ORCL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
SQL is connected using sqlplus and the listener running and connected to sql developer as well!
Below is the link to pictures
https://www.dropbox.com/sh/vbv0gkfcz2g59t5/AACtIVR1-bIen99DNN4HDsWaa?dl=0
I have wasted three days getting this right, i was able to get it to work yesterday but today when i restarted my system, the same error is back. I have tried everything available but nothing seems to work today.
Thanks in advance
SOLVED.
I was able to get it to run by re-configuring the database using database configuration assistant and then configuring the net services by net configuration assistant.
Turns out, as I understand, it is the only way to start the services needed to connect via a listener. I have to do it manually and test the net connection in the net configuration assistant every time i restart the system.
Thank you for your support.