ClassNotFoundException OptionsStrategy - janusgraph

When i connect to remote server and try to modify a graph i get java.lang.ClassNotFoundException: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/OptionsStrategy
I try search information about this exception. I think it happens because something conflict with version of janusgraph-core, gremlin-server and gremlin-driver
//pom file dependencies
<dependencies>
<dependency>
<groupId>org.janusgraph</groupId>
<artifactId>janusgraph-core</artifactId>
<version>0.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-driver</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-server</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
//jgex-remote.properties file
gremlin.remote.remoteConnectionClass=org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection
gremlin.remote.driver.sourceName=g
gremlin.remote.driver.clusterFile=.../janus_connect_config.yaml
//janus_connect_config.yaml file
hosts: [xxx.xxx.xxx.xxx]
port: xxxx
serializer: {
className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0,
config: {
ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry]
}
}
// java code
public class App {
public static void main(String[] args) throws ConfigurationException {
if (args.length == 0) {
throw new IllegalArgumentException("Input args must contains path to file with configuration");
}
String configFilePath = args[0];
PropertiesConfiguration connectConfig = new PropertiesConfiguration(configFilePath);
Cluster cluster = null;
Client client = null;
try {
cluster = Cluster.open(connectConfig.getString("gremlin.remote.driver.clusterFile"));
client = cluster.connect();
Bindings b = Bindings.instance();
GraphTraversalSource graph = EmptyGraph.instance()
.traversal()
.withRemote(connectConfig);
Vertex evnyh = graph.addV(b.of("label", "man"))
.property("name", "Evnyh")
.property("family", "Evnyhovich")
.next();
Vertex lalka = graph.addV(b.of("label", "man"))
.property("name", "Lalka")
.property("family", "Lalkovich")
.next();
graph.V(b.of("outV", evnyh)).as("a")
.V(b.of("inV", lalka)).as("b")
.addE(b.of("label", "friend")).from("a")
.next();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
try {
client.close();
} catch (Exception e) {
// nothing to do, just close client
}
}
if (cluster != null) {
try {
cluster.close();
} catch (Exception e) {
// nothing to do, just close cluster
}
}
}
}
}
Can somebody help resolve this problem?

You have a version mismatch. Note that JanusGraph 0.3.1 is bound to the TinkerPop 3.3.x line of code:
https://github.com/JanusGraph/janusgraph/blob/v0.3.1/pom.xml#L72
and OptionStrategy (and related functionality) was not added in TinkerPop until the 3.4.x line of code. JanusGraph therefore cannot process requests which use that sort of functionality.

Related

How to fix mysql jdbc error: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test

I have been looking for solution for my problem, but I did not get anywhere. I am using visual studio code to connect java(JDK-19) to MySQLv8.0 and I installed mysql-connector-j v8.0.31 (I am using windows)
I am trying to connect my database to java and I keep get this error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
This is my code:
import java.sql.*;
import java.util.Properties;
public class App {
public static void main(String[] args) throws Exception {
Connection dbConnection = null;
try {
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "test");
dbConnection = DriverManager.getConnection(url, info);
if (dbConnection != null) {
System.out.println("Successfully connected to MySQL database test");
}
} catch(SQLException e) {
System.out.println("An error occurd while connecting MySQL database");
e.printStackTrace();
}
}
}
I also added mysql-connector-j-8.0.31 jar file to referenced libraries.
Also added:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
to pom.xml

flink elasticsearch connector

I used the following code to connect Flink to ElasticSearch. But when running with Flink, a lot of errors are displayed.The program first enters the data from a port and then reads each line in the command line according to the program written. It then displays the number of words. The main problem is when connecting to a elasticsearch that unfortunately gives error when connecting. Are these errors? What classes do you need to connect Minimal Flink to Elastic Search?
public class Elastic {
public static void main(String[] args) throws Exception {
// the port to connect to
final int port;
try {
final ParameterTool params = ParameterTool.fromArgs(args);
port = params.getInt("port");
} catch (Exception e) {
System.err.println("No port specified. Please run 'SocketWindowWordCount --port <port>'");
return;
}
// get the execution environment
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// get input data by connecting to the socket
DataStream<String> text = env.socketTextStream("localhost", port, "\n");
// parse the data, group it, window it, and aggregate the counts
DataStream<WordWithCount> windowCounts = text
.flatMap(new FlatMapFunction<String, WordWithCount>() {
#Override
public void flatMap(String value, Collector<WordWithCount> out) {
for (String word : value.split("\\s")) {
out.collect(new WordWithCount(word, 1L));
}
}
})
.keyBy("word")
.timeWindow(Time.seconds(5), Time.seconds(1))
.reduce(new ReduceFunction<WordWithCount>() {
#Override
public WordWithCount reduce(WordWithCount a, WordWithCount b) {
return new WordWithCount(a.word, a.count + b.count);
}
});
// print the results with a single thread, rather than in parallel
windowCounts.print().setParallelism(1);
text.print().setParallelism(1);
env.execute("Socket Window WordCount");
List<HttpHost> httpHosts = new ArrayList<HttpHost>();
httpHosts.add(new HttpHost("127.0.0.1", 9200, "http"));
httpHosts.add(new HttpHost("10.2.3.1", 9200, "http"));
httpHosts.add(new HttpHost("my-ip",9200,"http"));
ElasticsearchSink.Builder<String> esSinkBuilder = new ElasticsearchSink.Builder<String>(
httpHosts,
new ElasticsearchSinkFunction<String>() {
public IndexRequest createIndexRequest(String element) {
Map<String, String> json = new HashMap<String, String>();
json.put("data", element);
return Requests.indexRequest()
.index("iran")
.type("int")
.source(json);
}
#Override
public void process(String element, RuntimeContext ctx, RequestIndexer indexer) {
indexer.add(createIndexRequest(element));
}
}
);
esSinkBuilder.setBulkFlushMaxActions(1);
final Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")};
esSinkBuilder.setRestClientFactory(new RestClientFactory() {
#Override
public void configureRestClientBuilder(RestClientBuilder restClientBuilder) {
restClientBuilder.setDefaultHeaders(defaultHeaders)
.setMaxRetryTimeoutMillis(10000)
.setPathPrefix("a")
.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
#Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
return builder.setSocketTimeout(10000);
}
});
}
});
text.addSink(esSinkBuilder.build());
}
// Data type for words with count
public static class WordWithCount {
public String word;
public long count;
public WordWithCount() {
}
public WordWithCount(String word, long count) {
this.word = word;
this.count = count;
}
#Override
public String toString() {
return word + " : " + count;
}
}
}
my elasticsearch version: 7.5.0
my flink version: 1.8.3
my error:
sudo /etc/flink-1.8.3/bin/flink run -c org.apache.flink.Elastic /root/FlinkElastic-1.0.jar --port 9000
------------------------------------------------------------
The program finished with the following exception:
java.lang.RuntimeException: Could not look up the main(String[]) method from the class
org.apache.flink.Elastic:
org/apache/flink/streaming/connectors/elasticsearch/ElasticsearchSinkFunction
at org.apache.flink.client.program.PackagedProgram.hasMainMethod(PackagedProgram.java:527)
at org.apache.flink.client.program.PackagedProgram.<init>(PackagedProgram.java:246)
... 7 more
Caused by: java.lang.NoClassDefFoundError:
org/apache/flink/streaming/connectors/elasticsearch/ElasticsearchSinkFunction
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at org.apache.flink.client.program.PackagedProgram.hasMainMethod(PackagedProgram.java:521)
... 7 more
Caused by: java.lang.ClassNotFoundException:
org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at org.apache.flink.runtime.execution.librarycache.FlinkUserCodeClassLoaders$ChildFirstClassLoader.loadClass(FlinkUserCodeClassLoaders.java:120)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
... 13 more
my pom:
<groupId>org.apache.flink</groupId>
<artifactId>FlinkElastic</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-elasticsearch6_2.11</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-java</artifactId>
<version>1.8.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_2.11</artifactId>
<version>1.8.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-clients_2.11</artifactId>
<version>1.8.3</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
Please find the Flink Elastic Connector code here. I have used the following dependencies and versions mentioned below.
Flink: 1.10.0
ElasticSearch: 7.6.2
flink-connector-elasticsearch7
Scala: 2.12.11
SBT: 1.2.8
Java: 11.0.4
Point to be noted here:
Since ElasticSearch 6.x onwards they started full support of the REST elastic client. And till Elastic5.x they were using Transport elastic client.
1. Flink DataStream
val inputStream: DataStream[(String, String)] = ...
ESSinkService.sinkToES(inputStream, index)
2. ElastiSearchSink Function
package demo.elastic
import org.apache.flink.streaming.api.scala._
import org.apache.log4j._
import org.apache.flink.api.common.functions.RuntimeContext
import org.apache.flink.streaming.connectors.elasticsearch7.{ElasticsearchSink, RestClientFactory}
import org.apache.flink.streaming.connectors.elasticsearch.{ActionRequestFailureHandler, ElasticsearchSinkFunction, RequestIndexer}
import org.apache.http.HttpHost
import org.elasticsearch.client.{Requests, RestClientBuilder}
import org.elasticsearch.common.xcontent.XContentType
import org.elasticsearch.action.ActionRequest
import org.apache.flink.streaming.api.datastream.DataStreamSink
class ESSinkService {
val logger = Logger.getLogger(getClass.getName)
val httpHosts = new java.util.ArrayList[HttpHost]
httpHosts.add(new HttpHost("localhost", 9200, "http"))
httpHosts.add(new HttpHost("localhost", 9200, "http"))
def sinkToES(counted: DataStream[(String, String)], index: String): DataStreamSink[(String, String)] = {
val esSinkBuilder = new ElasticsearchSink.Builder[(String, String)](
httpHosts, new ElasticsearchSinkFunction[(String, String)] {
def process(element: (String, String), ctx: RuntimeContext, indexer: RequestIndexer) {
indexer.add(Requests.indexRequest
.index(element._2 + "_" + index)
.source(element._1, XContentType.JSON))
}
}
)
esSinkBuilder.setBulkFlushMaxActions(2)
esSinkBuilder.setBulkFlushInterval(1000L)
esSinkBuilder.setFailureHandler(new ActionRequestFailureHandler {
override def onFailure(actionRequest: ActionRequest, throwable: Throwable, i: Int, requestIndexer: RequestIndexer): Unit = {
println("#######On failure from ElasticsearchSink:-->" + throwable.getMessage)
}
})
esSinkBuilder.setRestClientFactory(new RestClientFactory {
override def configureRestClientBuilder(restClientBuilder: RestClientBuilder): Unit = {
/*restClientBuilder.setDefaultHeaders(...)
restClientBuilder.setMaxRetryTimeoutMillis(...)
restClientBuilder.setPathPrefix(...)
restClientBuilder.setHttpClientConfigCallback(...)*/
}
})
counted.addSink(esSinkBuilder.build())
}
}
object ESSinkService extends ESSinkService
Note: For more details click here.
A couple of things:
Flink doesn't yet support Elasticsearch 7. An ES7 connector will be released along with Flink 1.10.
You must include the flink/elasticsearch dependency in your project -- this error suggests you haven't included it:
ClassNotFoundException:
org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction
See the elasticsearch docs for more info.
Your Flink application code runs in the task managers. Each task manager must be able to find all of your application's dependencies in its CLASSPATH. The connector classes are not included out-of-the-box, so you will need to either build an uber jar (i.e., a fat jar, or jar with dependencies), or copy the flink-connector-elasticsearch6_2.11 jar file into the lib directory of every machine in the cluster. See the docs on connector dependencies for more details.

How to add jms queue programmatically in runtime for Wildfly 10/11?

This code below creates JMS queue at run time in Wildfly 9.0.1 with no problem. In Wildfly 10 and 11 hornetq-server was replaced with activemq. How properly migrate it to Wildfly 10/11?
Thank you.
private boolean createQueue(String operationName, String queueName) {
boolean result = false;
ModelControllerClient client = qService.getModelControllerClient();
if(client != null){
ModelNode operation = new ModelNode();
ModelNode address = operation.get(ClientConstants.OP_ADDR);
address.add("subsystem", "messaging");
address.add("hornetq-server", "default");
address.add("jms-queue", queueName);
ModelNode entries = operation.get("entries");
entries.add("jms/queue/" + queueName);
operation.get(ClientConstants.OP).set(operationName);
try {
ModelNode returnVal = client.execute(operation);
return returnVal.get("outcome").asString().equalsIgnoreCase("success");
} catch (Exception e) {
DLOG.error(ExceptionUtils.getStackTrace(e));
} finally {
try {
client.close();
} catch (IOException ex) {
DLOG.error(ExceptionUtils.getStackTrace(ex));
}
}
}
return result;
}
With Wildfly 10 the JMS-Implementation changed from HornetQ to Apache ActiveMQ Artemis.The following example is tested with Wildfly 10.
You could prepare the command to create a queue like this:
public void createQueue() throws Exception {
ModelControllerClient client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9990);
if (client != null) {
ModelNode op = new ModelNode();
op.get(ClientConstants.OP_ADDR).add(ClientConstants.SUBSYSTEM, "messaging-activemq");
op.get(ClientConstants.OP_ADDR).add(ClientConstants.SERVER, "default");
op.get(ClientConstants.OP_ADDR).add("jms-queue", "HelloWorldQueue");
op.get("entries").add("queue/HelloWorldQueue");
op.get("entries").add("java:jboss/exported/queue/HelloWorldQueue");
op.get(ClientConstants.OP).set("add");
applyUpdate(op, client);
}
}
And execute the operation with this method:
private static void applyUpdate(ModelNode update, final ModelControllerClient client) throws IOException {
LOG.info("Execute: " + update.toString());
ModelNode result = client.execute(new OperationBuilder(update).build());
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
if (result.hasDefined("result")) {
LOG.info(result.get("result").toString());
}
} else if (result.hasDefined("failure-description")) {
throw new RuntimeException(result.get("failure-description").toString());
} else {
throw new RuntimeException("Operation not successful; outcome = " + result.get("outcome"));
}
}
The code runs inside a WAR with the following maven dependency:
<dependency>
<groupId>org.wildfly.core</groupId>
<artifactId>wildfly-controller-client</artifactId>
<version>3.0.10.Final</version>
</dependency>
With Java EE 7 and JMS 2.0 there is as well the annotation #JMSDestinationDefinitions which allows automatic creation of JMS resources at deployment time. For some use cases this could already be good enough.

Launch browser automatically after spring-boot webapp is ready

How do I launch a browser automatically after starting the spring boot application.Is there any listener method callback to check if the webapp has been deployed and is ready to serve the requests,so that when the browser is loaded , the user sees the index page and can start interacting with the webapp?
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// launch browser on localhost
}
Below code worked for me:
#EventListener({ApplicationReadyEvent.class})
void applicationReadyEvent() {
System.out.println("Application started ... launching browser now");
browse("www.google.com");
}
public static void browse(String url) {
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#SpringBootApplication
#ComponentScan(basePackageClasses = com.io.controller.HelloController.class)
public class HectorApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(HectorApplication.class, args);
openHomePage();
}
private static void openHomePage() throws IOException {
Runtime rt = Runtime.getRuntime();
rt.exec("rundll32 url.dll,FileProtocolHandler " + "http://localhost:8080");
}
}
You could do it by some java code. I am not sure if spring boot has something out of the box.
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I've recently been attempting to get this working myself, I know it's been a while since this question was asked but my working (and very basic/simple) solution is shown below. This is a starting point for anyone wanting to get this working, refactor as required in your app!
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
openHomePage();
}
private static void openHomePage() {
try {
URI homepage = new URI("http://localhost:8080/");
Desktop.getDesktop().browse(homepage);
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
}
If you package the application as a WAR file, configure an application server, like Tomcat, and restart the configured application server through your IDE, IDEs can automatically open a browser-tab.
If you want to package your application as a JAR file, your IDE will not be able to open a web browser, so you have to open a web browser and type the desired link(localhost:8080). But in the developing phase, taking these boring steps might be very tedious.
It is possible to open a browser with Java programming language after the spring-boot application gets ready. You can use the third-party library like Selenium or use the following code snippet.
The code snippet to open a browser
#EventListener({ApplicationReadyEvent.class})
private void applicationReadyEvent()
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e)
{
e.printStackTrace();
}
} else
{
Runtime runtime = Runtime.getRuntime();
String[] command;
String operatingSystemName = System.getProperty("os.name").toLowerCase();
if (operatingSystemName.indexOf("nix") >= 0 || operatingSystemName.indexOf("nux") >= 0)
{
String[] browsers = {"opera", "google-chrome", "epiphany", "firefox", "mozilla", "konqueror", "netscape", "links", "lynx"};
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
{
if (i == 0) stringBuffer.append(String.format("%s \"%s\"", browsers[i], url));
else stringBuffer.append(String.format(" || %s \"%s\"", browsers[i], url));
}
command = new String[]{"sh", "-c", stringBuffer.toString()};
} else if (operatingSystemName.indexOf("win") >= 0)
{
command = new String[]{"rundll32 url.dll,FileProtocolHandler " + url};
} else if (operatingSystemName.indexOf("mac") >= 0)
{
command = new String[]{"open " + url};
} else
{
System.out.println("an unknown operating system!!");
return;
}
try
{
if (command.length > 1) runtime.exec(command); // linux
else runtime.exec(command[0]); // windows or mac
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Using Selenium to open a browser
To use the selenium library add the following dependency to your pom.xml file.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
Then in your main class, add the following code snippet.
#EventListener({ApplicationReadyEvent.class})
private void applicationReadyEvent()
{
String url = "http://localhost:8080";
// pointing to the download driver
System.setProperty("webdriver.chrome.driver", "Downloaded-PATH/chromedriver");
ChromeDriver chromeDriver = new ChromeDriver();
chromeDriver.get(url);
}
Notice: It is possible to use most of the popular browsers like FirefoxDriver, OperaDriver, EdgeDriver, but it is necessary to download browsers' drivers beforehand.
Runtime rt = Runtime.getRuntime();
try {
rt.exec("cmd /c start chrome.exe https://localhost:8080");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The code above worked for me. Change chrome.exe to the browser of your choice and Url to to your choice.
Note: You must include the scheme - http or https, and the browser you choose must me installed, else your app will run without opening the browser automatically.
Works only for windows though.

How to get JDBC connection id?

I need to get the JDBC connection id(UUID) with Connection object. Is there is any way to get the connection id?
Well, if you meen "sql-connection to sql-server", then jdbc has no standard instruments for this. Here is handmade example for jdbc:mysql (beware - Reflection and restricted characters):
private long getJdbcConnectionId(Connection conn) {
long cid = 0;
try {
Field f_conn__conn = conn.getClass().getSuperclass().getDeclaredField("_conn");
f_conn__conn.setAccessible(true);
Object o_conn__conn = f_conn__conn.get(conn);
Field f_conn__conn__conn = o_conn__conn.getClass().getSuperclass().getDeclaredField("_conn");
f_conn__conn__conn.setAccessible(true);
Object o_conn__conn__conn = f_conn__conn__conn.get(o_conn__conn);
Field f_connectionId = o_conn__conn__conn.getClass().getSuperclass().getDeclaredField("connectionId");
f_connectionId.setAccessible(true);
cid = f_connectionId.getLong(o_conn__conn__conn);
f_connectionId.setAccessible(false);
f_conn__conn__conn.setAccessible(false);
f_conn__conn.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
return cid;
}
EDIT:
ok this way to avoid compile-time coupling, using reflection
import java.sql.Connection;
import java.sql.DriverManager;
...
public String getMysqlConnectionId()
{
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://host:3306/schema", "myuser", "mypassword");
Class<?> clazz = Class.forName("com.mysql.jdbc.MySQLConnection");
Object o = connection.unwrap(clazz);
return (String) clazz.getMethod("getId").invoke(o).toString();
} catch ( Exception e ) {
return e.getMessage();
}
}
By casting your java.sql.Connection object to com.mysql.jdbc.MySQLConnection and using getId()
import java.sql.Connection;
import java.sql.DriverManager;
import com.mysql.jdbc.MySQLConnection;
...
public long getMysqlConnectionId()
{
Connection connection = DriverManager.getConnection("jdbc:mysql://host:3306/schema", "myuser", "mypassword");
// would throw a ClassCastException in case this is not a mysql one, of course
return ((MySQLConnection) connection).getId();
}
But this is sort of terribly coupling your project to MySQL at compile time
note: I won't be offended when I get down-voted for this, it is sort of deserved ;-)
<!-- pom.xml -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>x.y.z</version>
</dependency>
Some other people apparently are using connection.unwrap(com.mysql.jdbc.MySQLConnection) which might feels a bit more appropriate, yet does not remove the compile-time coupling to com.mysql
https://github.com/prestodb/presto/issues/9425
Here is my example how to get Oracle SID:
public int getConnectionSid() {
try {
if (connection == null || connection.isClosed())
return -1;
if (connectionSid == -1) {
try {
Method method = connection.getClass().getDeclaredMethod("getSessionId", null);
method.setAccessible(true);
connectionSid = (Integer)method.invoke(nativeConnection, null);
method.setAccessible(false);
} catch (NoSuchMethodException e) {
return -1;
} catch (IllegalAccessException e) {
return -1;
} catch (InvocationTargetException e) {
return -1;
}
}
return connectionSid;
} catch (SQLException e) {
return -1;
}

Resources