Cannot connect multiple times to mysql - java

I am writing an own databse in scala. To verify my results are correct, I check with a MySQL inside of a specs2 specification. I get the right result and everything is just fine. But if I run the test again without any changes, I get a SQLException: No suitable driver found for jdbc:mysql://localhost:3306/DBNAME?user=DBUSER (null:-1). Why is the driver not loaded again?
Edit
import java.sql.{ Connection, DriverManager, ResultSet }
import org.specs2.mutable.Specification
// SDDB imports ...
class DBValidationSpec extends Specification {
"SDDB and MySQl" should {
// SDDB
// ...
// JDBC
val connectionString = "jdbc:mysql://localhost:3306/sddb_test?user=root"
val query = """SELECT content, SUM( duration ) duration
FROM test
WHERE times
BETWEEN '2011-12-08'
AND '2011-12-09'
GROUP BY content"""
classOf[com.mysql.jdbc.Driver]
"give the same result" in {
// ...
//sddbResult
lazy val conn = DriverManager.getConnection(connectionString)
try{
val rs = conn.createStatement().executeQuery(query)
var mysqlResult = Map[List[String], Int]()
while (rs.next) {
mysqlResult += (rs.getString("content") :: Nil) -> rs.getInt("duration")
}
sddbResult == mysqlResult && sddbResult.size == 478 must beTrue
} finally {
conn.close()
}
}
}
}
I left out some parts of my code because they don't belong to the question.
Edit #2
The problem became even weirder. I added a second testcase. The testcase uses the same connectionString. The Exception was only raised once. The second test succeeded. I added sequential to my test definition and saw that only the first executed test raises the Exception. Afterwards I traced the classLoader to check if it is the same one. It is.
I did the following workaround:
trait PreExecuting extends Before {
override def before {
var conn: Option[Connection] = None
try {
val connectionString = "jdbc:mysql://localhost:3306/sddb_test?user=root"
conn = Some(DriverManager.getConnection(connectionString))
} catch {
case _ =>
} finally {
conn map (_.close())
}
}
}
I don't get the Exception any more because I suppress it by using the PreExecution tait. But I still wonder what is going wrong here.

I cannot pin down the error, to the following, but at least better also close the result set and statement.
val stmt = conn.createStatement()
val rs = stmt.executeQuery(query)
var mysqlResult = Map[List[String], Int]()
while (rs.next) {
mysqlResult += (rs.getString("content") :: Nil) -> rs.getInt("duration")
}
sddbResult == mysqlResult && sddbResult.size == 478 must beTrue
rs.close()
stmt.close()

It's seems to be a problem with the Driver registration, the Driver has to be registered some like this...
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
or some like this...
DriverManager.registerDriver(new DriverWrapper((Driver) Class.forName(props.getProperty("dbg.driver"), true, gcloader).newInstance()));
before use getConnection. I hope this help.

The driver is only loaded once.
No suitable driver usually means that the connection URL syntax is incorrect.

Related

Reuse java connectionpool in scala

I have a legacy Java application, and would like to reuse its database connection handling when extending the app with scala.
The existing application does this to use the database (with try/catch omitted):
Connection dbConn = NewConnectionPool.getRemotePool().getConnection();
PreparedStatement ps = dbConn.prepareStatement(someQuery);
in the scala code I tried:
class Rules {
val connHandle = NewConnectionPool.getRemotePool.getConnection
val session = connHandle.unwrap(classOf[java.sql.Connection])
def loadTagRulesFromDb(name: String = "rules"): tagRuleSet = {
//val tagRules = NamedDB('remotedb) readOnly { implicit session =>
val tagRules = DB readOnly { implicit session =>
sql"select * from databasename.messaging_routing_matchers".map(
rs => tagRule(
rs.long("id"),
rs.string("description"),
rs.long("ruleid"),
rs.string("operator"),
rs.string("target")
)
).list.apply
}
for (tr <- tagRules) {
println(tr)
}
tagRuleSet(name,DateTime.now(),tagRules)
}
}
and call it like:
Rules rr = new Rules();
rr.loadTagRulesFromDb("testing");
and I get this error (both with DB and the NamedDB version) "Connection pool is not yet initialized.(name:'" with name either default or remotedb):
java.lang.IllegalStateException: Connection pool is not yet initialized.(name:'default)
at scalikejdbc.ConnectionPool$$anonfun$get$1.apply(ConnectionPool.scala:76) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scalikejdbc.ConnectionPool$$anonfun$get$1.apply(ConnectionPool.scala:74) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scala.Option.getOrElse(Option.scala:121) ~[scala-library-2.11.8.jar:na]
at scalikejdbc.ConnectionPool$.get(ConnectionPool.scala:74) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scalikejdbc.ConnectionPool$.apply(ConnectionPool.scala:65) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scalikejdbc.DB$.connectionPool(DB.scala:151) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scalikejdbc.DB$.readOnly(DB.scala:172) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at dk.coolsms.smsc.Rules.loadTagRulesFromDb(Rules.scala:28) ~[smsc.jar:na]
at dk.coolsms.smsc.SendMessage.sendMessage(SendMessage.java:206) ~[smsc.jar:na]
I assume that I can get a scalikejdbc compatible connection from the BoneCP connectionHandle somehow?
EDIT: the solution is below, note that DB readOnly etc. should not be used since it relies on DBs.setupAll() and application.conf, which does not apply in this specific case
Accessing via a javax.sql.DataSource instance would be the best way to integrate ScalikeJDBC with existing database connections.
http://scalikejdbc.org/documentation/connection-pool.html
But you already have a raw java.sql.Connection, it's also possible to simply create a DBSession as below:
implicit val session = DBSession(conn)
sql"select * from databasename.messaging_routing_matchers".toMap.list.apply()

VSAM file locking when writing to it using Java JDBC

This is my first time trying to read and write to a VSAM file. What I did was:
Created a Map for the File using VSE Navigator
Added the Java beans VSE Connector library to my eclipse Java project
Use the code show below to Write and Read to the KSDS file.
Reading the file is not a problem but when I tried to write to the file it only works if I go on the mainframe and close the File before running my java program but it locks the file for like an hour. You cannot open the file on the mainframe or do anything to it.
Anybody can help with this problem. Is there a special setting that I need to set up for the file on the mainframe ? Why do you first need to close the file on CICS to be able to write to it ? And why does it locks the file after writing to it ?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.*;
public class testVSAM {
public static void main(String argv[]){
Integer test = Integer.valueOf(2893);
String vsamCatalog = "VSESP.USER.CATALOG";
String FlightCluster = "FLIGHT.ORDERING.FLIGHTS";
String FlightMapName = "FLIGHT.TEST2.MAP";
try{
String ipAddr = "10.1.1.1";
String userID = "USER1";
String password = "PASSWORD";
java.sql.Connection jdbcCon;
java.sql.Driver jdbcDriver = (java.sql.Driver) Class.forName(
"com.ibm.vse.jdbc.VsamJdbcDriver").newInstance();
// Build the URL to use to connect
String url = "jdbc:vsam:"+ipAddr;
// Assign properties for the driver
java.util.Properties prop = new java.util.Properties();
prop.put("port", test);
prop.put("user", userID);
prop.put("password", password);
// Connect to the driver
jdbcCon = DriverManager.getConnection(url,prop);
try {
java.sql.PreparedStatement pstmt = jdbcCon.prepareStatement(
"INSERT INTO "+vsamCatalog+"\\"+FlightCluster+"\\"+FlightMapName+
" (RS_SERIAL1,RS_SERIAL2,RS_QTY1,RS_QTY2,RS_UPDATE,RS_UPTIME,RS_EMPNO,RS_PRINTFLAG,"+
"RS_PART_S,RS_PART_IN_A_P,RS_FILLER)"+" VALUES(?,?,?,?,?,?,?,?,?,?,?)");
//pstmt.setString(1, "12345678901234567890123003");
pstmt.setString(1, "1234567890");
pstmt.setString(2,"1234567890123");
pstmt.setInt(3,00);
pstmt.setInt(4,003);
pstmt.setString(5,"151209");
pstmt.setString(6, "094435");
pstmt.setString(7,"09932");
pstmt.setString(8,"P");
pstmt.setString(9,"Y");
pstmt.setString(10,"Y");
pstmt.setString(11," ");
// Execute the query
int num = pstmt.executeUpdate();
System.out.println(num);
pstmt.close();
}
catch (SQLException t)
{
System.out.println(t.toString());
}
try
{
// Get a statement
java.sql.Statement stmt = jdbcCon.createStatement();
// Execute the query ...
java.sql.ResultSet rs = stmt.executeQuery(
"SELECT * FROM "+vsamCatalog+"\\"+FlightCluster+"\\"+FlightMapName);
while (rs.next())
{
System.out.println(rs.getString("RS_SERIAL1") + " " + rs.getString("RS_SERIAL2")+ " " + rs.getString("RS_UPTIME")+ " " + rs.getString("RS_UPDATE"));
}
rs.close();
stmt.close();
}
catch (SQLException t)
{
}
}
catch (Exception e)
{
// do something appropriate with the exception, *at least*:
e.printStackTrace();
}
}
}
Note: the OS is z/VSE
The short answer to your original question is that KSDS VSAM is not a DBMS.
As you have discovered, you can define the VSAM file such that you can update it both from batch and from CICS, but as #BillWoodger points out, you must serialize your updates yourself.
Another approach would be to do all updates from the CICS region, and have your Java application send a REST or SOAP or MQ message to CICS to request its updates. This does require there be a CICS program to catch the requests from the Java application and perform the updates.
The IBM Mainframe under z/VSE has different partitions that run different jobs. For example partition F7 CICS, partition F8 Batch Jobs, ETC.
When you define a new VSAM file you have to set the SHAREOPTIONS of the file. When I define the file I set the SHAREOPTIONS (2 3). 2 Means that only one partition can write to the file.
So when the batch program (in a different partition to the CICS partition) which is called from Java was trying to write to the file it was not able to write to the file unless I close the file in CICS first.
To fix it I REDEFINE the CICS file with SHAREOPTIONS (4 3). 4 Means that multiple partitions of the Mainframe can write to it. Fixing the problem
Below is a part of the definition code where you set the SHAREOPTION:
* $$ JOB JNM=DEFFI,CLASS=9,DISP=D,PRI=9
* $$ LST CLASS=X,DISP=H,PRI=2,REMOTE=0,USER=JAVI
// JOB DEFFI
// EXEC IDCAMS,SIZE=AUTO
DEFINE CLUSTER -
( -
NAME (FLIGHT.ORDERING.FLIGHTS) -
RECORDS (2000 1000) -
INDEXED -
KEYS (26 0) -
RECORDSIZE (128 128) -
SHAREOPTIONS (4 3) -
VOLUMES (SYSWKE) -
) -
.
.
.

Mongodb connection issue with java

i am having mongoDB connections issue in java , this is my connection class
public MongoDbUtil() {
try {
System.out.println("1");
String host = "127.0.0.1" ;
String dbName = "m_prod" ;
int port =27017 ;
System.out.println("2");
Mongo m = new Mongo();
System.out.println("3");
ds = new Morphia().createDatastore(m,dbName);
System.out.println("4");
ds.ensureIndexes();
System.out.println("5");
ds.ensureCaps();
System.out.println("1");
} catch(Exception e) {
System.out.println("catch");
}finally{
System.out.println("finally");
System.out.println(ds==null);
} }
only 1 and 2 is printing, after that 'finally' is printing also 'ds' is null, there is no any exception happen ('catch' is not printing)
Mongo server is up and running and i can access from command prompt (Linux) , the Other interesting thing is, its working fine when i call this method by unit test function, but for all other cases above issue happen , what can be the reason ?
Thanks
Mongo() is deprecated, you should use MongoClient() instead - see http://api.mongodb.org/java/2.11.0/com/mongodb/Mongo.html#Mongo()
Still it should find the deprecated constructor. Can you include the imports of your file, please?
If you're using the 3.0 driver, there's a driver-compat layer that will help you transition. You really should use the new API, though.

Pass connection from Java Application to Birt report

I'm new to Birt.
I'm trying to pass the connection to the report from my java application, but I get an error:
The following items have errors:
ReportDesign (id = 1):
+ There are errors evaluating script "importPackage(Packages.it.lfiammetta.birt); var conn = new
ReportRenderer();
reportContext.getAppContext().put("OdaJDBCDriverPassInConnection",
conn);": Fail to execute script in function __bm_beforeOpen(). Source:
" + importPackage(Packages.it.lfiammetta.birt); var conn = new
ReportRenderer();
reportContext.getAppContext().put("OdaJDBCDriverPassInConnection",
conn); + "
A BIRT exception occurred. See next exception for more information.
Error evaluating Javascript expression. Script engine error:
ReferenceError: "ReportRenderer" is not defined.
(/report/data-sources/oda-data-source[#id="43"]/method[#name="beforeOpen"]#2)
Script source:
/report/data-sources/oda-data-source[#id="43"]/method[#name="beforeOpen"],
line: 0, text:
__bm_beforeOpen(). (Element ID:1)
This is my java code that creates and launches report:
package it.lfiammetta.birt;
public class ReportRenderer {
public void executeReport() {
code...
Map<String, Object> appContext = task.getAppContext();
appContext.put("OdaJDBCDriverPassInConnection", myConnection);
appContext.put("OdaJDBCDriverPassInConnectionCloseAfterUse", false);
task.setAppContext(appContext);
task.run();
code...
}
}
This is the code I wrote in the script 'beforeOpen' the datasource:
importPackage(Packages.it.lfiammetta.birt);
var conn = new ReportRenderer();
reportContext.getAppContext().put("OdaJDBCDriverPassInConnection", conn);
I set the classpath.
Birt version I'm using is 4.2.1.
Thanks in advance for your help and I apologize for my English.
I'm doing that from Java code (IJDBCParameters - actually parameters for JDBC connections, I'm looking connection by name - OdaDataSourceHandle.getName()):
#SuppressWarnings("rawtypes")
private static void substituteJDBCConnections(IReportRunnable pReportRunnable) {
final Map<String, IJDBCParameters> jdbcConnections = reportParameters.getJdbcConnections();
if (jdbcConnections != null ){
for (Iterator iter = pReportRunnable.getDesignHandle().getModuleHandle().getDataSources().iterator(); iter.hasNext();){
// http://wiki.eclipse.org/Java_-_Execute_Modified_Report_(BIRT)
Object element = iter.next();
if (element instanceof OdaDataSourceHandle){
OdaDataSourceHandle dsHandle = (OdaDataSourceHandle) element;
String key = dsHandle.getName();
if (key == null){
continue;
}
IJDBCParameters jdbcParams = jdbcConnections.get(key);
if (jdbcParams == null){
continue;
}
try {
dsHandle.setProperty( "odaDriverClass", jdbcParams.getDriverName());
dsHandle.setProperty( "odaURL", jdbcParams.getConnectionString());
dsHandle.setProperty( "odaUser", jdbcParams.getUserName());
dsHandle.setProperty( "odaPassword", jdbcParams.getPassword());
} catch (SemanticException e) {
throw new UncheckedException(e);
}
}
}
}
Probably you fixed your issue already, but maybe someone will be looking for this in the future. First of all 4.2.x versions had problems with passed connections. I did not observed the same errors in 4.4.2.
Other thing, I do not get why you are trying to pass ReportRenderer as a connection in lines:
var conn = new ReportRenderer();
reportContext.getAppContext().put("OdaJDBCDriverPassInConnection", conn);
The passed object in here should be a java.sql.Connection object.
Therefore,
Map<String, Object> appContext = task.getAppContext();
appContext.put("OdaJDBCDriverPassInConnection", myConnection);
appContext.put("OdaJDBCDriverPassInConnectionCloseAfterUse", false);
task.setAppContext(appContext);
looks correct as long as myConnection is an implementation of java.sql.Connection

Getting response from servlet

I'm using the following code to get the response from a servlet. It will check whether the given name in the variable "get" is in a particular table, and print 1 if it exists.
Portion of servlet code:
get = request.getParameter("nam");// such as get="kannan"
try {
// Connection code
ResultSet rs = stmt
.executeQuery("select * from newfarmer where rname='" + get
+ "'");
while (rs.next()) {
username = rs.getString("rname");
if (get.equals(username)) {
out.println(1);
}
}
} catch (Exception e) {
out.println(e.toString());
}
In my android application, I check this response as follows:
response = CustomHttpClient.executeHttpPost(
"http://moberp.svsugar.com:8080/androidservlt/Modify",
postParameters);
String res = response.toString();
res = res.trim();
if (res.equals("1")) {
flag = 1;
Toast.makeText(getBaseContext(), "Correct", Toast.LENGTH_LONG)
.show();
} else {
flag = 2;
Toast.makeText(getBaseContext(), "please enter correct Ryot name",
Toast.LENGTH_LONG).show();
}
It works very well for single record. I mean, in the table "newfarmer", If "rname" consists of more than one same name only the else part is executed.
Example:
If "kannan" is presented 2 times in the table Servlet output is as
1 1
Now in android application, clearly the else part is executed because response is not 1.
This is only case of two same names. The table may contains more than 10 same names.
If 10 same names, then servlet output is as
1 1 1 1 1 1 1 1 1 1
So I need to check all.
So I need to make changes in my if condition, but I don't know what to do. Someone please give answer.
Thanks in advance
instead of while loop Use
if(rs.next())
Now it will print only one time.
No change in android
in servlet do this
if(rs.next())
{
username=rs.getString("rname");
if(get.equals(username))
{
out.println(1);
}
}
}
this loop will run only 1 time now if the record is present.
I don't understand why would get.equals(username) will evaluate to false when you are having a where clause in your SQL query?
So just try this.
if(rs.next())
{
// The above condition will make the code inside if executed
// only if any matching record is found and
//hence it will print `1` only once
//if any matching record is found.
username=rs.getString("rname");
if(get.equals(username))
{
out.println(1);
}
}
Also you are using stmt.executeQuery("select * from newfarmer where rname='"+get+"'");
which is susceptible to SQL injection.
So better use prepared statement instead.
try if(rs.next()),
this will surely help you

Categories