I am stuck trying to connect to an embedded Apache Derby Database through my Play (2.3.9) application. Have the following configurations in application.conf:
DATABASE_URL_DB = "derby:MyDB"
db.default.driver = org.apache.derby.jdbc.EmbeddedDriver
db.default.url="jdbc:"${DATABASE_URL_DB}
(I have the MyDB DB directory inside the Derby installation directory - which is the default).
Following is the controller code (a fragment of the file) i am trying to execute:
package controllers
import play.api.db._
import play.api.mvc._
import play.api.Play.current
object Application extends Controller {
def test = Action {
var outString = "Number is "
val conn = DB.getConnection()
try {
val stmt = conn.createStatement
val rs = stmt.executeQuery("SELECT 9 as testkey ")
while (rs.next()) {
outString += rs.getString("testkey")
}
} finally {
conn.close()
}
Ok(outString)
}
}
The dependencies in place (alongside others):
libraryDependencies ++= Seq( jdbc , cache , ws)
libraryDependencies += "org.apache.derby" % "derby" % "10.12.1.1"
In Routes (alongside others):
GET /globalTest controllers.Application.test
I get the error: NoClassDefFoundError: Could not initialize class org.apache.derby.jdbc.EmbeddedDriver
Could someone point out the problem? Thanks in advance.
The issue was resolved by minimizing the number of dependencies in build.sbt. Certainly seems like one of the dependencies in my project was interfering with the Derby drivers.
Related
I was recently working on a MySQL database and wanted to use the database as my data source in KTOR. To use the database, I decided to use the org.jetbrains.exposed.sql.Database
and javax.sql.DataSource imports. I'm working in IntelliJ.
My test code looks like this:
import org.jetbrains.exposed.sql.Database
import javax.sql.DataSource
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
val databaseUrl = "jdbc:mysql://localhost:3307/databaseName"
val username = "root"
val password = " "
// Create a DataSource object
val dataSource: DataSource = Database.connect(
url = databaseUrl,
driver = "com.mysql.jdbc.Driver",
user = username,
password = password
)
Somehow, I can't import the org.jetbrains.exposed.sql.Database , even though I added the dependency in my build.gradle.kts file:
dependencies {
implementation("com.mysql.jdbc:mysql-connector-java:8.0.22")
implementation("org.jetbrains.exposed:exposed:0.18.7")
implementation("io.ktor:ktor-server-core:$ktor_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("io.ktor:ktor-server-content-negotiation:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
testImplementation("io.ktor:ktor-server-test-host:$ktor_version")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version")
implementation(kotlin("stdlib-jdk8"))
}
I tried syncing the gradle file, rebuilding the project and cleaning the project. Am I missing something? Thanks!
Ok so I solved it by using a different dependency in my build.gradle file:
implementation("org.jetbrains.exposed:exposed-core:0.41.1")
Instead of:
implementation("org.jetbrains.exposed:exposed:0.18.7")
I'm beginner with java and using console to compile and run my programs. I'm trying to read data from MS Access .accdb file with ucanaccess driver. As i have added 5 ucanaccess files to C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext, but still getting Exception java.lang.ClassNotFoundException:net.ucanaccess.jdbc.ucanaccessDriver.
Here is my code.
import java.sql.*;
public class jdbcTest
{
public static void main(String[] args)
{
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String url = "jdbc:ucanaccess://C:javawork/PersonInfoDB/PersonInfo.accdb";
Connection conctn = DriverManager.getConnection(url);
Statement statmnt = conctn.createStatement();
String sql = "SELECT * FROM person";
ResultSet rsltSet = statmnt.executeQuery(sql);
while(rsltSet.next())
{
String name = rsltSet.getString("name-");
String address = rsltSet.getString("address");
String phoneNum = rsltSet.getString("phoneNumber");
System.out.println(name + " " + address + " " + phoneNum);
}
conctn.close();
}
catch(Exception sqlExcptn)
{
System.out.println(sqlExcptn);
}
}
}
Please add JDBC driver jar to lib folder.
Download URL download jar
I tried the method mentioned by Gord in his post Manipulating an Access database from Java without ODBC and used eclipse instead of command line compile and run. Also to learn eclipse basics, i watched video tutorial https://www.youtube.com/watch?v=mMu-JlBrYXo.
Finally i was able to read my MS Access data base file from my java code.
I have the following problem.
When you try to create a connection can not find variables.
The test has the following set of actions
Download the local settings file (put in props)
Create a database connection (This happens all in different groups, i tried in the same)
Use next code for upload local property file(Bean Shell, Thread Group 1)
FileInputStream is = new FileInputStream(new File("d:/somefolder/somefile.properties"));
props.load(is);
is.close();
Before creating the connection I checked the availability of variables(Bean Shell, Thread Group 2)
System.out.println(props.get("db.url"));
System.out.println(${__P("db.url")});
${__setProperty("db.url", props.get("db.url"))};
System.out.println(${__P("db.url")});
OutPut
correct connection url
1(Because function __P return default value if variable undefined,
default value = 1)
correct connection url
Create Jdbc Connection with next parametrs(Thread Group 2)
url: ${__P("db.url")}
Test Failure because ${__P("db.url")} return 1
If i use ${__BeanShell(props.get(db.url))}
Test Failure because props.get(db.url) return nothing
If i use ${__javaScript(props.get(db.url))}
Test Failure because props.get(db.url) return nothing
"Component jdbc connection configuration" initialized before started first Thread Group, so component don't see variables because he don't initialize.
Create Script for connecting to db
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
ResultSet clientConfigs = null;
ResultSet gameIds = null;
Connection connect = null;
Statement statement = null;
try {
Class.forName(props.get("configdb.driverClassName"));
String connectionUrl = props.get("configdb.url") + "?user=" + props.get("configdb.username") + "&password=" + props.get("configdb.password");
connect = DriverManager.getConnection(connectionUrl);
statement = connect.createStatement();
clientConfigs = statement.executeQuery("Select keyname,valuestr from client_config WHERE valuestr Like '%/_ah/api/%'");
ResultSetMetaData ccMetaData = clientConfigs.getMetaData();
int clientConfigsColumns = ccMetaData.getColumnCount();
ArrayList clientConfigsList = new ArrayList(20);
while (clientConfigs.next()){
HashMap clientConfigsRow = new HashMap(clientConfigsColumns);
for(int i=1; i<=clientConfigsColumns; ++i){
clientConfigsRow.put(ccMetaData.getColumnName(i), clientConfigs.getObject(i));
}
clientConfigsList.add(clientConfigsRow);
}
vars.putObject("clientConfigs", clientConfigsList);
gameIds = statement.executeQuery("Select gameId from game_config");
ResultSetMetaData giMetaData = gameIds.getMetaData();
int gameIdsColumns = giMetaData.getColumnCount();
ArrayList gameIdsList = new ArrayList(50);
while (gameIds.next()){
HashMap gameIdsRow = new HashMap(gameIdsColumns);
for(int i=1; i<=gameIdsColumns; ++i){
gameIdsRow.put(giMetaData.getColumnName(i), gameIds.getObject(i));
}
gameIdsList.add(gameIdsRow);
}
vars.putObject("gameIds", gameIdsList);
}
catch (Exception e) {
throw e;
} finally {
try {
if (clientConfigs != null) {
clientConfigs.close();
}
if (gameIds != null) {
gameIds.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
Apparently JMeter loads JDBC configuration parameters at really early, likely at UI load. See discussion here
The JDBC Config element is only processed at test startup, so it is
not possible to change the values once a test has started - i.e. you
could not change the values for different loops of the test plan. The
test plan has to know the JDBC settings near the start.
Which means, if you change value of property in threadGroup-1 at runtime, the changes will not take effect in JDBC config.
One possible way around this is to set the property from the command line while starting JMeter.
Alternatively drop JDBC sampler entirely and use one of the custom samplers to interact with your JDBC data source.
I followed https://sqoop.apache.org/docs/1.99.4/RESTAPI.html for trying out sqoop2. But Iam getting error "Exception in thread "main" org.apache.sqoop.common.SqoopException: MODEL_011:Input do not exist - Input name: linkConfig.connectionString" on the line linkConfig.getStringInput("linkConfig.connectionString").setValue("jdbc:mysql://localhost/my");
i tested sqoop2, mysql, database etc from terminal and working fine. please help. thanks in advance.
here is the code i am trying
import org.apache.sqoop.client.SqoopClient;
import org.apache.sqoop.model.MLink;
import org.apache.sqoop.model.MLinkConfig;
import org.apache.sqoop.validation.Status;
public class Sqoop2 {
public static void main(String[] args) {
//Initialization SqoopClient
String url = "http://<myip>:12000/sqoop/";
SqoopClient client = new SqoopClient(url);
// create a placeholder for link
long connectorId = 1;
MLink link = client.createLink(connectorId);
link.setName("Vampire");
link.setCreationUser("Buffy");
MLinkConfig linkConfig = link.getConnectorLinkConfig();
// fill in the link config values
linkConfig.getStringInput("linkConfig.connectionString").setValue("jdbc:mysql://<myip>/<dbname>");
linkConfig.getStringInput("linkConfig.jdbcDriver").setValue("com.mysql.jdbc.Driver");
linkConfig.getStringInput("linkConfig.username").setValue("root");
linkConfig.getStringInput("linkConfig.password").setValue("root");
// save the link object that was filled
Status status = client.saveLink(link);
if(status.canProceed()) {
System.out.println("Created Link with Link Id : " + link.getPersistenceId());
} else {
System.out.println("Something went wrong creating the link");
}
}
}
I faced the same issue. As per the documentation generic-jdbc connector id =1 and hdfs-connector id =2. But after we upgraded to 5.3.2 the id's were swapped.
Don't hard code the connector Id's(as said in the documentation). Use client.getConnectors(); or show connector --all method to look for existing connectors and get the connector Id you need. There is currently an issue logged for this https://issues.apache.org/jira/browse/SQOOP-1965.
Looks like connector 1 is already exists. Can you try with another id ?
What is the equivalent of org.apache.catalina.ServerFactory.getServer() in Tomcat 7 or what would be the best way to retrieve org.apache.catalina.Session instances ?
Here is a sample code that used to work on Tomcat 6.0:
public List<org.apache.catalina.Session> findActiveSessions() throws ServiceException {
StandardEngine engine = (StandardEngine) ServerFactory.getServer().findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost())
.findChild(ServletActionContext.getServletContext().getContextPath());
List<org.apache.catalina.Session> list = new ArrayList<org.apache.catalina.Session>();
for (org.apache.catalina.Session session : context.getManager().findSessions()) {
list.add(session);
}
return list;
}
You can look it up via its management registration..
import javax.management.*;
import org.apache.catalina.Server;
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Catalina", "type", "Server");
Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
Obviously that code is devoid of error checking but is functional.