Why Hikari construct a bad database url? - java

I have problem using HikariCP and Google App Engine for JEE.
When trying to access site, i have the logged error :
com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Cannot connect to MySQL server on localhost:3,306.
As you can see, it add a ',' in the port address.
I try to send full URL to it but nothing append.
Here is my Servlet INIT class :
public class InitialServlet extends HttpServlet {
public static final String SEANCE_MANAGER = "SEANCE_MANAGER";
public static final String CLOUD_SQL_CONNECTION_NAME="";
public static final String DB_USER="test_db";
public static final String DB_PASS="password";
public static final String DB_NAME="dbname";
#Override
public void init(ServletConfig config) throws ServletException {
HikariConfig configs = new HikariConfig();
configs.setJdbcUrl("jdbc:mysql://localhost:3306/dbname");
configs.setUsername(DB_USER);
configs.setPassword(DB_PASS);
configs.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
configs.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);
configs.addDataSourceProperty("useSSL", "false");
DataSource pool = new HikariDataSource(configs);
DataAccess dataAccess = new DataAccess(pool);
SeancesManager seancesManager = new SeancesManager(dataAccess);
config.getServletContext().setAttribute(SEANCE_MANAGER, seancesManager);
}
}
How i can do to fix this bug ?
Thanks

The only difference from the official connection specified in the documentation that you can follow in order to connect App Engine with Cloud SQL through Java that I see is the format of the setJdbcurl.
I know this might be far fetched but can you attempt to format the setJdbcUrl like this?
config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
Also please double check the connection variables in case something went through.
Let me know and if it doesn't work we will look more into it.
EDIT:
Are you using SQL Proxy?
If you are using SQL Proxy run the command again and make sure you specify the port correctly.
That is the first thing that I can think off where you can specify the port and maybe had a "," in the command you specified.
Another thing I wonder, are you overwriting or have you modified the port number in any place? I would recommend you checking that because the error "3,306" is because the port specified is "3,306". The normal failure error directly fails with 3306.

Related

dbms_java.grant_permission is required for every new session

i am trying to implement java RMI client server connection, i made my server in NetBeans IDE and client class made in oracle database as java store procedure and use this via oracle function in my PLSQL block, everything is working fine but I stuck in little issue below:
I made this java store procedure in SYSTEM user and give dbms_java.grant_permission('SYSTEM','java.net.SocketPermission','192.168.43.25:*','connect,resolve') to SYSTEM user via SYSDBA, "*" is used for all available ports. I get perfect response from my server but till specific session expiry.
Whenever I logout from SYSTEM user and login back again, its again throws me an exception the Permission ("java.net.SocketPermission" "192.168.43.25:56792" "connect,resolve") has not been granted please guide me how can I get rid from this repeated task? because in development environment I'll manage it but how can deploy it on production with this issue. My Environment is Oracle DB 18c XE, Thank You!
Following is my java store procedure:
create or replace and compile java source named rmi as
package rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.Naming;
import java.security.Policy;
public class RmiClient {
public RmiClient(){
}
public static String getRequestFromClient(){
Policy.setPolicy(new MyPolicy());
String result = "";
try {
IServer server = getServer();
result = server.getRequestFromClient();
} catch (Exception ex) {
result = ex.getMessage().toString();
}
return result;
}
private static IServer getServer() throws Exception {
Parameter configurationParameters = new Parameter();
IServer server = (IServer) Naming.lookup( configurationParameters.objectName);
return server;
}
}
Granting permissions with DBMS_JAVA is a little different than a typical Oracle grant. After granting a permission using DBMS_JAVA.GRANT_PERMISSION, you will need to COMMIT at some point after the grant as been executed for it to take affect permanently. Notice how there is a COMMIT after the DBMS_JAVA call in the Oracle documentation.

How can I connect from Cloud Run Java application to a Cloud SQL database?

I have a Java/Vert.x application deployed as a Cloud Run container. It's running fine. I've tried to access my Cloud SQL MySQL instance to it, but to no avail. My application hangs as soon as I try to connect to the DB instance create a DataSource.
My Cloud Run container is associated with a service account with the Cloud SQL Client role.
I've followed the canonical GCP tutorial here:
https://cloud.google.com/sql/docs/mysql/connect-run
Obviously swapping in my specifics. Below is the offending code:
private static final String PW = "mypassword";
private static final String CONN_NAME = "/cloudsql/mydatabase-111222:us-west1:my-project";
private DataSource pool;
#Override
public void init() throws Exception {
LOGGER.info("MysqlRepo-init starting...");
// The configuration object specifies behaviors for the connection pool.
HikariConfig config = new HikariConfig();
LOGGER.info("MysqlRepo-init 1");
// Configure which instance and what database user to connect with.
config.setJdbcUrl(String.format("jdbc:mysql:///%s", "mydb"));
config.setUsername("root"); // e.g. "root", "postgres"
config.setPassword(PW); // e.g. "my-password"
// For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", CONN_NAME);
config.addDataSourceProperty("useSSL", "false");
LOGGER.info("MysqlRepo-init 2");
// Initialize the connection pool using the configuration object.
pool = new HikariDataSource(config);
LOGGER.info("MysqlRepo-init 3");
ResultSet rs = pool.getConnection().createStatement().executeQuery("SELECT COUNT(*) col FROM dual WHERE 1=1");
LOGGER.info("MysqlRepo-init Results = " + rs.getFetchSize());
LOGGER.info("...MysqlRepo-init done");
}
My logs stop at "MysqlRepo-init 2" (beyond that, I get Vertx warnings that my main thread is blocked).
Any thoughts on what I might be missing?
The problem seems to have something to do with calling this code from a Vert.x verticle. When I called it directly from the application's main method, I was able to get useful log messages, which were complaining about the "/cloudsql/" portion of the connection name. That provided enough information to ultimately resolve ths issue.

JDBC kinds of connection

I'm creating app for library management with Java and MySQL ( JDBC to connect with DB ) , and I have a problem , I checked a lot of topics, books, and websites but I didn't find good answer for me. Is it the good way to deal with connections ? I think that one connection for entire app is good option in this case. My idea is that in every function in every class when I need to use Connection object , these functions will need a connection parameter. In main class I'll call manager object 'Man' for example and to every constructor etc I'll pass Man.getMyConn() as this parameter and call Man.close() when Main frame will be closed . Is it bad idea ? Maybe I should use singleton pattern or connection pool ?
Sorry for my English , I'm still learning.
public class manager {
private Connection myConn;
public manager() throws Exception {
Properties props = new Properties();
props.load(new FileInputStream("app.properties"));
String user = props.getProperty("user");
String password = props.getProperty("password");
String dburl = props.getProperty("dburl");
myConn = DriverManager.getConnection(dburl, user, password);
System.out.println("DB connection successful to: " + dburl);
}
public Connection getMyConn() {
return myConn;
}
//close class etc.
}
Usually not. Further answer depends on type of the application. If you're making web application then you should definitely go with connection pool. If you're making e.g. desktop application (where only one user can access it at the time), then you can open and close connection upon each request.
I have working applications that do it your way. As #Branislav says, it's not adequate if you want to do multiple concurrent queries. There's also a danger that the connection to the database might be lost, and you would need to restart your application to get a new one, unless you write code to catch that and recreate the connection.
Using a singleton would be overcomplicated. Having a getConnection() method (as you have done) is very important as it means you can easily change your code to use a pool later if you find you need to.

Android xmpp error host-unknown

I'm trying to make a connection to xmpp server and this returning me this error.
W/AbstractXMPPConnection: Connection closed with error
org.jivesoftware.smack.XMPPException$StreamErrorException: host-unknown You can read more about the meaning of this stream error
at http://xmpp.org/rfcs/rfc6120.html#streams-error-conditions
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1003)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$300(XMPPTCPConnection.java:944)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:959)
at java.lang.Thread.run(Thread.java:818)
I tried to use this example in github and put this data.
private static final String DOMAIN = "10.20.0.125";
private static final String HOST = "10.20.0.125";
private static final int PORT = 5222;
private String userName ="admin2#localhost";
private String passWord = "asdfasdf";
The server is ok, we conducted another test pc to make a communication on android but this error persists.
I see mainly 2 errors:
in the demo configuration you have this lines of code:
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
First problem (main one):
DOMAIN variable SHOULD (but MUST) BE the server name you can read in server configuration, not just the IP; some functionality will broke outside the localhost.
Second problem:
while I suggest to split login from configuration (so just configure the connection and THEN login) what I don't get it's the username: localhost will be not resolved outside the server machine, so again has to be replaced with DOMAIN name (even if, in theory, the connection will give the user his domain, doesn't need to be so explicit).
so:
connection.connect();
login();
will be replaced with
connection.connect();
login(userName ,passWord,"Android" );
and you'll need to remove this 2 lines:
configBuilder.setResource("Android");
configBuilder.setUsernameAndPassword(userName, passWord);
about DOMAIN name: you'll find it in Server configuration, in Openfire it's the "Server Name" you can read in web interface in Server Information page.
I managed to find the solution.
I was using .jar files instead of the compile gradle dependencies:
compile 'org.igniterealtime.smack:smack-android:4.1.4'
compile 'org.igniterealtime.smack:smack-tcp:4.1.4'
compile 'org.igniterealtime.smack:smack-im:4.1.4'
compile 'org.igniterealtime.smack:smack-extensions:4.1.4'
Thus the error has been resolved. Thank you for your help.

Creating HBaseAdmin which connects to HBaseTestingUtility

I'm writing a code which manipulates data stored in HBase. I want to write also a test for this code. I want to use HBaseTestingUtility in my test, hence, in my #BeforeClass I create new instance of HBaseTestingUtility and I start the mini cluster:
#BeforeClass
public static void setUpClass() throws Exception {
utility = new HBaseTestingUtility();
utility.startMiniCluster();
}
It works good. However, I cannot connect to this embedded cluster in my code which is being tested. In the code I have:
Configuration config = HBaseConfiguration.create();
try (HBaseAdmin admin = new HBaseAdmin(config))
{
//code which manipulates the data
}
Unfortunately when new HBaseAdmin is created I'm getting a ConnectionError exception:
2013-11-21 11:20:35,778 WARN [main-SendThread(0:0:0:0:0:0:0:1:2181)] zookeeper.ClientCnxn (ClientCnxn.java:run(1089)) - Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect
java.net.ConnectException: Connection refused: no further information
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:692)
at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:350)
at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1068)
When I try another apporach to create HBaseAdmin:
try (HBaseAdmin admin = new HBaseAdmin(HBaseCacheTest.utility.getConfiguration()))
{
//code which manipulates the data
}
it works (note that here I'm accessing the instance of HBaseTestingUtility via HBaseCacheTest.utility).
Obviously this is not a good approach as I don't want to have a production code which depends on the testing code.
One approach I see to work here is to make it possible in my production class to set the Configuration and use this setter method in my tests.
However, I believe that there should be another way to connect to the embeded mini cluster created with HBaseTestingUtility.
Any ideas?
You should not create a new Configuration object, but use the one provided by HBaseTestingUtility:
HBaseAdmin admin = testingUtility.getHBaseAdmin();
Also, if you need configuration only you can use this one:
testingUtility.getConfiguration()
Just rechecked it in my UT. I'm using HBase 0.96-hadoop2
Hope this helps :)

Categories