Java PostgreSQL: Suppress error output when connection failed - postgresql

I am connecting to a postgreSQL database with java.
The user inputs a username and a password in the command line and then I test the connection. I have put a try-catch block around it, but it still prints an error message when the connection fails. I don't want the user to see this message, I just want to handle the error myself, as can usually be achieved by a try-catch construct. However, in this particular case the message gets printed anyway. How can I suppress the message here?
Relevant code:
import java.sql.*;
public class ChessDatabase {
private Connection chessDB;
private String username;
private String password;
ChessDatabase(String username, String password) {
this.username = username;
this.password = password;
}
public boolean isConnected() {
try {
chessDB = DriverManager.getConnection("jdbc:postgresql://[...]", username, password);
} catch (Exception e) {
return false;
}
return true;
}
}
Error message:
Jun 25, 2018 3:38:24 PM org.postgresql.core.v3.ConnectionFactoryImpl log
WARNING: SQLException occurred while connecting to [...]
org.postgresql.util.PSQLException: FATAL: PAM authentication failed for user "[...]"
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:473)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:205)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
at org.postgresql.Driver.makeConnection(Driver.java:452)
at org.postgresql.Driver.connect(Driver.java:254)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at ChessDatabase.isConnected(ChessDatabase.java:35)
[...]
Jun 25, 2018 3:38:24 PM org.postgresql.Driver connect
SEVERE: Connection error:
org.postgresql.util.PSQLException: FATAL: PAM authentication failed for user "[...]"
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:473)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:205)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
at org.postgresql.Driver.makeConnection(Driver.java:452)
at org.postgresql.Driver.connect(Driver.java:254)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at ChessDatabase.isConnected(ChessDatabase.java:35)
[...]
PS: Just for clarification, the connection works and no error message is printed if username and password are correct. So the issue is not getting rid of the error, just of the message.

Thanks to the link JB Nizet provided, I could find that I can append "?loggerLevel=OFF" to the first parameter in DriverManager.getConnection(). That way the message does not get printed.

Related

Cannot deploy the ktor server

What kind of problem is that? Does anybody face this? Or anyone knows the solution? I was trying to deploy ktor server using PostgreSQL.
Exception in thread "main" com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: FATAL: password authentication failed for user "myselfapp"
at com.zaxxer.hikari.pool.HikariPool.throwPoolInitializationException(HikariPool.java:596)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:582)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:100)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:81)
at com.codewitharfin.db.DatabaseFactory.hikari(DatabaseFactory.kt:25)
at com.codewitharfin.db.DatabaseFactory.init(DatabaseFactory.kt:11)
at com.codewitharfin.ApplicationKt$main$1.invoke(Application.kt:10)
at com.codewitharfin.ApplicationKt$main$1.invoke(Application.kt:9)
at io.ktor.server.engine.internal.CallableUtilsKt.executeModuleFunction(CallableUtils.kt:51)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$launchModuleByName$1.invoke(ApplicationEngineEnvironmentReloading.kt:332)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$launchModuleByName$1.invoke(ApplicationEngineEnvironmentReloading.kt:331)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartupFor(ApplicationEngineEnvironmentReloading.kt:356)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.launchModuleByName(ApplicationEngineEnvironmentReloading.kt:331)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.access$launchModuleByName(ApplicationEngineEnvironmentReloading.kt:30)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:319)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:310)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartup(ApplicationEngineEnvironmentReloading.kt:338)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:310)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:143)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:277)
at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:174)
at com.codewitharfin.ApplicationKt.main(Application.kt:12)
at com.codewitharfin.ApplicationKt.main(Application.kt)
Caused by: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "myselfapp"
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:646)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:180)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:235)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:223)
at org.postgresql.Driver.makeConnection(Driver.java:400)
at org.postgresql.Driver.connect(Driver.java:259)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:121)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:359)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:470)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561)
... 21 more
I could not find any solution to this, is this some kind of environment problem? But I am giving the password the right here.
I faced this error when I forgot to mention the password in the URL and also when the password was wrong.
private fun hikari(): HikariDataSource{
val config = HikariConfig()
config.driverClassName = "org.postgresql.Driver"
config.jdbcUrl = "jdbc:postgresql:<database_name_in_lowercase>?user=<username>&password=<password>"
config.maximumPoolSize = 3
config.isAutoCommit = false
config.transactionIsolation = "TRANSACTION_REPEATABLE_READ"
config.validate()
return HikariDataSource(config)
}

milo:Bad_SessionIdInvalid, The session id is not valid

I am getting a "The session id is not valid." exception when reading the value of a node ,but just sometimes,I konw the session is not timeout,so why?
the exception :
java.util.concurrent.ExecutionException: UaServiceFaultException: status=Bad_SessionIdInvalid, message=The session id is not valid.
at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
at com.ggnykj.smartems.cloud.server.autocontrol.client.OpcClientServer.readNode(OpcClientServer.java:230)
at com.ggnykj.smartems.cloud.server.autocontrol.controller.OpcClientServerController.readNode(OpcClientServerController.java:115)
at com.ggnykj.smartems.cloud.server.autocontrol.server.SaveExOpcData.run(SaveExOpcData.java:59)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: UaServiceFaultException: status=Bad_SessionIdInvalid, message=The session id is not valid.
at org.eclipse.milo.opcua.stack.client.UaTcpStackClient.lambda$receiveResponse$16(UaTcpStackClient.java:367)
at org.eclipse.milo.opcua.stack.core.util.ExecutionQueue$PollAndExecute.run(ExecutionQueue.java:107)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
... 3 more
Exception in thread "pool-2-thread-2" java.lang.NullPointerException
at com.ggnykj.smartems.cloud.server.autocontrol.controller.OpcClientServerController.readNode(OpcClientServerController.java:116)
at com.ggnykj.smartems.cloud.server.autocontrol.server.SaveExOpcData.run(SaveExOpcData.java:59)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
there is my code:
MyX509IdentityProvider x509IdentityProvider = new MyX509IdentityProvider(clientOption.opcServer.getCertFilePath(),
clientOption.opcServer.getPrivateKeyPath());
X509Certificate cert = x509IdentityProvider.getCertificate();
KeyPair keyPair = new KeyPair(cert.getPublicKey(), x509IdentityProvider.getPrivateKey());
OpcUaClientConfig config = OpcUaClientConfig.builder()
.setApplicationName(LocalizedText.english(clientOption.opcServer.getOpcServerName()))
//.setApplicationUri("urn:eclipse:milo:examples:client")
.setApplicationUri("")
//.setCertificate(loader.getClientCertificate())
//.setKeyPair(loader.getClientKeyPair())
.setCertificate(cert)
.setKeyPair(keyPair)
.setEndpoint(endpoint)
.setIdentityProvider(clientOption.getIdentityProvider())
.setChannelLifetime(uint(600000000))
.setSessionTimeout(uint(600000000))
//.setRequestTimeout(uint(5000))
.build();
return new OpcUaClient(config);
there is the connect and read code:
private OpcUaClient getOpcClient(OpcServer opcServer){
OpcUaClient client = null;
if(null!=opcClientMap.get(opcServer.getOpcServerId())){
client = opcClientMap.get(opcServer.getOpcServerId());
}else{
try {
ClientOption clientOption = new ClientOption(opcServer);
client = new ClientOptionRunner(clientOption).createClient();
}catch (Throwable t){
logger.error("Error getting client: {}", t.getMessage(), t);
}
opcClientMap.put(opcServer.getOpcServerId(),client);
}
return client;
}
public DataValue readNode(OpcServer opcServer,NodeId nodeId){
OpcUaClient client = getOpcClient(opcServer);
DataValue value = null;
try {
client.connect().get();
value = client.readValue(0.0, TimestampsToReturn.Both, nodeId).get();
}catch (Exception e){
e.printStackTrace();
}
return value;
}
when I read the node,there is the problem:
value = client.readValue(0.0, TimestampsToReturn.Both, nodeId).get();
but I don't know why
This StatusCode comes from the server.
Maybe you can capture this behavior on Wireshark to ensure you're really using the same OpcUaClient instance you think you are and not one that has had its session timeout somehow. Or maybe the capture will show the server is at fault and returning this StatusCode when you read on a freshly created Session.

Making connection to Zookeeper from AuthenticationProvider in Zookeeper

I'm making AuthenticationProvider that during authentication connects to Zookeeper (the same it is running on) and check in node if this user gave correct password.
Basically the flow looks smth like this:
#Override
public KeeperException.Code handleAuthentication(ServerCnxn cnxn, byte[] authData) {
final String usernameColonPassword = new String(authData);
String[] split = usernameColonPassword.split(":");
final String username = split[0];
final String password = split[1];
byte[] binary = curator.getData().forPath(ATUH_NODE); // here error is thrown
// check is password is correct
}
The problem is that all the time I'm getting KeeperErrorCode = ConnectionLoss at line when curator get data. What is the reason of this behavior? During an authentication I'm not allowed to do connection to Zookeeper that is authorizing client?
Below full stacktrace:
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for XXX
at org.apache.zookeeper.KeeperException.create(KeeperException.java:99)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1045)
at org.apache.curator.framework.imps.ExistsBuilderImpl$2.call(ExistsBuilderImpl.java:172)
at org.apache.curator.framework.imps.ExistsBuilderImpl$2.call(ExistsBuilderImpl.java:161)
at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:107)
at org.apache.curator.framework.imps.ExistsBuilderImpl.pathInForeground(ExistsBuilderImpl.java:157)
at org.apache.curator.framework.imps.ExistsBuilderImpl.forPath(ExistsBuilderImpl.java:148)
at org.apache.curator.framework.imps.ExistsBuilderImpl.forPath(ExistsBuilderImpl.java:36)
As I found it is impossible. At this point zookeeper is having some kind of lock/semaphore and he's not accepting new connections from this thread.

How do I connect to Hive on EMR through Eclipse?

I am trying to connect to Hive on EMR through Eclipse, but I get an error.
Exception in thread "main" java.sql.SQLException: Could not open client transport with JDBC Uri: jdbc:hive2://localhost:8158: java.net.ConnectException: Connection refused
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:215)
at org.apache.hive.jdbc.HiveConnection.<init>(HiveConnection.java:163)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.readypulse.sparkanalytics.HiveQLConnector.<init>(HiveQLConnector.java:31)
at com.readypulse.sparkanalytics.HiveQLConnector.main(HiveQLConnector.java:83)
Caused by: org.apache.thrift.transport.TTransportException: java.net.ConnectException: Connection refused
You would need a SSH Tunnel to poke a hole to EMR master. And then connect via JDBC.
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
private static String hiveConnectionString = "jdbc:hive2://localhost:8158";
//Need port forwarding
SparkPortForwarding.portForwardForSpark();
Class c = Class.forName(driverName);
Connection connection = DriverManager.getConnection(hiveConnectionString,
"user", "pwd");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
You can do port forwarding via shell as:
ssh -i ~/mykey.pem -N -L 8158:<maserhost>:10000 hadoop#<masterhost>
Or You can use the code using the library JSch
public static void portForwardForSpark() {
try {
if(session != null && session.isConnected()) {
return;
}
JSch jsch = new JSch();
jsch.addIdentity(PATH_TO_SSH_KEY_PEM);
String host = REMOTE_HOST;
session = jsch.getSession(USER, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.connect();
int assingedPort = session.setPortForwardingL(LPORT, RHOST, RPORT);
System.out.println("Port forwarding done for the post : " + assingedPort);
} catch (Exception e) {
System.out.println(e);
}
}

java.sql.SQLException: Network error IOException: Connection timed out: connect

I have installed SQL Server 2012 Express in my laptop and tried to run a sample java program as follows:
import java.sql.*;
public class Ex2 {
Connection con;
Statement st;
ResultSet rs;
public Ex2(String query){
System.out.println("IN Const1");
try{
System.out.println("IN try");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String dbName = "HOME";
String user = "sa";
String password = "JUL#2012";
//the name of my SQL SERVER 2005 instance
String SqlServerInstance = "SQLEXPRESS";
String url = "jdbc:jtds:sqlserver://localhost:1433";
url = url + "/" + dbName;
url = url + ";" + SqlServerInstance;
con = DriverManager.getConnection(url, user, password);
System.out.println("nach DriverManager");
st = con.createStatement();
st.executeQuery(query);
rs = st.getResultSet();
while ( rs.next() ){
System.out.println(rs.getString(0));
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
}
catch(Exception e){
e.printStackTrace();
System.out.println("Exception: " + e.getMessage());
}
}
public static void main(String[] argv){
System.out.println("IN MAIN");
Ex2 test = new Ex2("SELECT * FROM HOME.dbo.employee;");
}
}*
and getting the following error log in the console:
java.sql.SQLException: Network error IOException: Connection timed out: connect
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:410)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
at java.sql.DriverManager.getConnection(DriverManager.java:171)
at Ex2.<init>(Ex2.java:22)
at Ex2.main(Ex2.java:43)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:516)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:307)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:257)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:311)
Exception: Network error IOException: Connection timed out: connect
... 6 more
When I checked the sql server configuration manager the services SQL Server and SQL Server Browser are running.
I have been googling for the last two days and struggle to fix this issue and couldn't. So please help me.