How to connect to RedisJson with JReJSON package in java? - java

Recently, I started working with RedisJson with node, but I also have to work with Java version of it.
I'm trying to create a connection as it is mentioned in this github repo: https://github.com/RedisJSON/JRedisJSON
The repo shows connection with "localhost", but I want to connect to my remote Redis server instance which has the URL like redis://:password#host:port.
I'm trying to pass the host and port like the following:
JReJSON jsonClient = new JReJSON("redis://:password#host", port);
But I'm getting the following error saying 'Failed to create socket' and 'UnknownHostException':
But, I'm able to connect to the same host from command line.
Could someone point out what is the issue or what is the actual way to connect to remote instance with RedisJSON in java?
Note: I'm using Jedis - jedis-4.3.1.jar and Rejson - jrejson-1.4.0.jar

Part 1: About the library
Check what the JRedisJSON home page says:
As of Jedis 4.0.0 this library is deprecated.
Since Jedis 4.0.0, you won't need jrejson/JRedisJSON separately. As you're already using jedis-4.3.1, you're good to go only with Jedis.
Check their quick start.
Part 2: About the constructor
You want to create client object from host, post and password. Check following two constructors:
new JedisPooled("redis://:password#host:port")
new JedisPooled(host, port, user, password) -> new JedisPooled(host, port, null, password)

Related

Jedis Issue - "Failed to connect to any host resolved for DNS name."

Whenever I try to connect to my Redis server from my Java application using Jedis, I get JedisConnectionException: Failed to connect to any host resolved for DNS name. The Java application runs on the same machine as the Redis server.
When I check the Redis server's status using systemctl, it's online and running without problems. I also connected to the Redis client via terminal using command-line on the Linux machine it is running on, authenticated and performed PING in which PONG was returned to make sure the Redis was up running.
Redis configuration
I have bind and requirepass un-commented in the redis.conf and looks like following (not my entire config, of course):
bind 127.0.0.1
requirepass mypassword
port 6379
This is the code I am using:
private void setupRedis(RedisCredentials credentials) {
final GenericObjectPoolConfig<Jedis> poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(0);
Jedis jedis;
try (JedisPool pool = new JedisPool(poolConfig, credentials.getIp(), credentials.getPort())) {
jedis = pool.getResource();
}
jedis.auth(credentials.getPassword());
jedis.connect();
log.info("Redis connection was established.")
}
I am a bit new to working with Redis therefor I wasn't sure on how much information to include in my post. All and any help is very much appreciated!
Tried
I tried the following code provided above multiple times. I have also tried restarting the Redis server and running the code again, with no successful try.
Expected to happen
For the application to log "Redis connection was establish" and to receive no errors in the process.
Resulted
The console logs the redis.clients.jedis.exceptions.JedisConnectionException: Failed to connect to any host resolved for DNS name and the application therefore obviously does not managed to establish a connection to Redis.

Remote access to ArangoDB through Java Interface

I have developed a Java application that uses ArangoDB as backend database (Used ArangoDB Java-Driver/Interface to access ArangoDB).
Everything is good until my ArangoDB and Application resides on same machine.
Once i moved ArangoDB to remote machine(Dedicated Server), my application is unable to access it :(
I have given my remote machine details(ArangoDB Server) in some properties file and feeding that file location to ArangoConfigure Constructor while creating ArangoDriver Object. But still i'm unable to access ArangoDB :(
Small snippet of my code is below:
protected static ArangoConfigure getConfiguration() {
//ArangoConfigure configure = new ArangoConfigure();
ArangoConfigure configure = new
ArangoConfigure("/Volumes/Official/ZLabs/arangodb.properties");
configure.init();
return configure; }
protected static ArangoDriver getArangoDriver(ArangoConfigure
configuration) { return new ArangoDriver(configuration); }
Please help me in this regard.
Awaiting your response.
Thanks & Best Regards,
- Mahi
First of all thank you #dothebart for all your help.
#dothebart, I have checked all the details that you have mentioned, before i posted here. Only thing is missed is HTTP connectivity thanks for pointing that.
Actually the below code change has fixed the problem for me.
Earlier code:
ArangoConfigure configure = new ArangoConfigure("/home/arango.properties");
configure.init();
ArangoDriver driver = new ArangoDriver(configuration);
Modified Code:
ArangoConfigure configure = new ArangoConfigure("/home/arango.properties");
ArangoHost hostObj = new ArangoHost(<IP-Address>, 8529);
configure.setArangoHost(hostObj);
configure.setUser(<user-name>);
configure.setPassword(<password>);
configure.init();
ArangoDriver driver = new ArangoDriver(configuration);
Setting up of host, username and password again is making it to work :(
File has all the details, then why should i provide them again.. I didn't understand that.
#dothebart i'm unable to find the log file, please let me know where can i find it.
If the Aranngodb Java driver fails to open or parse /Volumes/Official/ZLabs/arangodb.properties it issues a log message.
If arangodb properties looks like that:
port=8529
host=192.168.22.17
user=root
password=OpenSesame
enableCURLLogger=false
You start walking up the OSI model to debug TCP connection problems to evade possible connection issues due to firewals, routing etc.
One uses the commonly available telnet command to test the availability of the server:
telnet 192.168.22.17 8529
Trying 192.168.22.17...
If it sits there forever, you most probably have a firewall filtering you away, you finaly will get:
telnet: Unable to connect to remote host: Connection timed out
If it immediately exits with:
telnet: Unable to connect to remote host: Connection refused
It seems the server doesn't answer.
On the server side you then can check whether the service has bound the port (8529) you're trying to connect:
netstat -alpnt |grep 8529
tcp 0 0 0.0.0.0:8529 0.0.0.0:* LISTEN 19912/arangod
If you instead see it binding 127.0.0.1:8529 you won't be able to connect it remotely and need to change arangod.conf like this:
[server]
endpoint = tcp://0.0.0.0:8529
And then restart ArangoDB. Then, you should be able to see something like this:
telnet 192.168.22.17 8529
Trying 192.168.22.17...
Connected to 192.168.22.17.
Escape character is '^]'. <start to type now: >
GET / HTTP/1.0
<server should reply:>
HTTP/1.1 301 Moved Permanently
Location: /_db/_system/_admin/aardvark/index.html
Content-Type: text/html
Server: ArangoDB
Connection: Close
Content-Length: 197
<html><head><title>Moved</title></head><body><h1>Moved</h1>
<p>This page has moved to /_db/_system/_admin/aardvark/index.html.
</p></body></html>Connection closed by foreign host.
This looks like the properties-file isn't found in the classpath.
The path of the log-file should be configured in your log-configuration-file in your project.
Your project may use for example Logback (logback.xml) or another slf4j implementation.

io error:network adapter could not establish the connection

I am developing a mini project using Java and Oracle XE database.
I was able to connect to database, insert, update and run all other queries from my personal computer, but when I tried to run the same program on my college computer (which is networked) it did not run and gave me the following exception message:
io error:network adapter could not establish the connection
I tried researching the error message on the internet and found that it must be a firewall or port number problem, but I am unable to sort it. How can I fix this error?
Here is the connection code that I used:
public void connect()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","system","system");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
SimpleDateFormat sd=new SimpleDateFormat("dd-MM-yy");
DefaultTableModel table_allrec;
PreparedStatement pstmt,pstmt1;
Connection conn;
ResultSet rs,rs1;
This error is most likely caused by one of these factors:
You are using the wrong URL
The wrong port number or IP address (or DNS host name) was used
The listener is not configured properly
The listener process (service) is not running. You can re-start it with the "lsnrctl start" command or on Windows by starting the listener service.
Please make sure, you are entering correct username, password, hostname, PORT, SID while creating connection in SQL Developer
On the machine where DB is installed,
go to this folder C:\app{{Username_machine}}\product\11.2.0\dbhome_1\NETWORK\ADMIN
P.S. : {{Username_machine}} : This is will differ from machine to machine
Open 2 files inside this listener.ora AND tnsnames.ora
Check hostname, PORT, SID mentioned in the files MUST match with the one you are trying to use in STEP 1.
If any of the value doesn't match, Use the values present in the 2 Files for creating connection in SQL Developer
Try to connect with updated values in case mismatch of values were found
If you are still not able to connect
press windows + R, and type services.msc -- this is will open Services running on your machine
restart all the services that are starting with oracle
Try to reconnect again on SQL Developer
If it fails again,
Open CMD in administrative mode,
Check if Your TNS Listener is up by typing the following command
lsnrctl status
The above command will give error if the Listener is not up
Start the Listener, by typing the following command,
lsnrctl start
In case you are having problems in starting your listener then try starting “OracleOraDb11g_home1TNSListener” windows service. For that open your Run Command and write services.msc this will open your service panel. Here search for the same and right click to start it.
Doing the above steps, will resolve your Problem. Thanks !

App Engine Java Servlet does not connect to Cloud SQL

I have created a java web servlet using app engine, the servlet makes requests to a database. I have tested the servlet locally using a local database and it worked perfectly, i then proceeded to test the servlet locally but istead accessed the Cloud SQL database, this also worked perfectly.
My problem arises after i deploy the servlet. Once deployed all database requests return the following:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not
received any packets from the server.
I checked within the cloud console, and my app was properly added to the cloud SQL Authorized App Engine Applications under the Access Control tab.
Has anyone had similar problems with deployed app engine servlets? Any solutions or advice out there? I would appreciate any and all help!!!
UPDATE:
The above error was generated using the following code to access the db
Class.forName("com.mysql.jdbc.Driver");
Url = "jdbc:mysql://<ip-address-cloudsql>:3306/<dbname>";
Connection con = DriverManager.getConnection (Url,"root",<password>);
the same error was acheived using this code, note that it is very similar to the code shown in the example here https://developers.google.com/appengine/docs/java/cloud-sql/
Class.forName("com.mysql.jdbc.GoogleDriver");
Url = "jdbc:google:mysql://<appID:instanceID>/<dbname>?
user=root&password=<password>";
Connection con = DriverManager.getConnection (Url);
I followed the formatting tips show in this stackoverflow post when it came to setting the url using appid and instance id:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Using this code resulted in the following different error:
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
I'm assuming it says localhost because my cloudsql database is set to follow the app engine servlet. Also, know that both of these methods worked fine when running the servlet locally and accessing the cloud sql database.
any thoughts? i don't know what else to try:[
When connecting to Cloud SQL from an authorized App Engine application, the password is not required (actually it will fail if you try to connect with password).
Change your connection string to jdbc:google:mysql://<appID:instanceID>/<dbname>?
user=root omitting the &password=<password> part
If you have Authorized App Engine Applications you app engine on the access control settings you do not need a password since it is local so just make you password= ""; However if you are using something remote for example phpmyadmin that is run from another host, your command line or a GCE VM that runs through a TCP , SSH or HTML you will need to have a password ="something"; where something is set by you in your access control.
To everyone from Google who are looking as to why you might be getting "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure" on a connection.
Make sure your IP is allowed if you are calling from a test server.
I was testing at a friends house, and this unhelpful error kept showing up.
When connecting to Google Cloud Sql you should be careful:
-To close your opened connections
-To use Exponential backoff algorithm when trying to create new connection.
For more information see: https://cloud.google.com/sql/faq
If you're using application.properties in Spring Boot app, then just put the below line into application.properties:
spring.datasource.url: jdbc:mysql://google/<dbname>?cloudSqlInstance=<InstanceName>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****

Java PostgreSQL connection over VPN

I have a Java application that needs to connect to a remote PostgreSQL database over a VPN. Here is the relevant code:
Class.forName("org.postgresql.Driver");
Connection con = null;
con = DriverManager.getConnection("jdbc:postgresql://" + sqlHost + ":" + sqlPort + "/mydb", username, password);
This throws the error
org.postgresql.util.PSQLException: FATAL: pg_hba.conf rejects connection for host "172.16.7.5", user "xxxxx", database "xxxxx", SSL off
The Host IP address in sqlHost is actually 192.168.12.55, but if you notice the error message says that it is connecting to host 172.16.7.5 (which is the IP address assigned by the VPN).
I am able to connect to this PostgreSQL database using the exact same connection parameters on the exact same VPN using PGAdmin and using Python's psocopg2 module. Here is the equivalent Python code:
conn = psycopg2.connect("dbname=mydb user="+username+" password="+password+" host="+sqlHost+" port="+sqlPort)
Why in the world is only Java having problems with this? Since the connection works over PGAdmin and Python, I assume there is some setting in Java that I am using incorrectly, but I can't find anything.
EDIT: After reading into PostgreSQL docs a little more, I found that the issue with it listing the wrong hostname is not part of the issue but rather just the way PostgreSQL sees my computer over the VPN. Problem is still not solved, however.
Okay, I fixed this myself. The problem had nothing to do with the VPN but rather with the fact that Java by default does not try any sort of SSL connection by default whereas PGAdmin and psycopg2 do.
The solution was to add the following parameters to my connection url:
ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory
I'm not sure if this might be the problem, but I've experienced similar problems in the past trying to connect to a database with VPN turned on.
Try running your application with this JVM argument passed at application launch time:
-Djava.net.preferIPv4Stack=true
See also this answer for a more permanent solution.

Categories