Connecting to local instance of PostgreSql with JDBC for tuffy - java

I can login into Postgres using "psql -h localhost -U myuser mydatabase"
But my tuffy config file is like this :
# JDBC connection string; must be PostgreSQL
db_url = jdbc:postgresql://localhost:5432/mydb
# Database username; must be a superuser
db_username = myuser
# The password for db_username
db_password = mypass
# The working directory; Tuffy may write sizable temporary data here
dir_working = /var/postgres/data
But when I run tuffy commands, it show error like this :
Connecting to RDBMS at jdbc:postgresql://localhost:5432/tuffydb Failed
to connect to PostgreSQL! FATAL: password authentication failed for
user "tuffer" Exception in thread "main"
java.lang.NullPointerException at tuffy.db.RDB.query(RDB.java:438) at
tuffy.db.RDB.schemaExists(RDB.java:676) at
tuffy.db.RDB.resetSchema(RDB.java:717) at
tuffy.main.Infer.setUp(Infer.java:77) at
tuffy.main.PartInfer.run(PartInfer.java:18) at
tuffy.main.Main.main(Main.java:29)

Related

PgBouncer throwing PSQLException: ERROR: unsupported pkt type: 80 when issuing query "SHOW POOLS" on "pgbouncer" database via JDBC

When trying to issue "SHOW POOLS" or any stats query command on pgbouncer database via JDBC, facing the below exception.
org.postgresql.util.PSQLException: ERROR: unsupported pkt type: 80
at
org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270)
at
org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998)
at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at
org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570)
at
org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:406)
at
org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:286)
JDBC code:
String connectionUrl = "jdbc:postgresql://"+ipaddress+":"+port+"/"+database;
con = DriverManager.getConnection(connectionUrl, userName, password);
statement = con.createStatement(); statement.executeQuery("SHOW POOLS");
JDBC Driver Version: 42.2.14 ;
PgBouncer Version: 1.14.0 ;
Postgres Version: 11.4;
PS:
Manually able to connect to pgbouncer database and issue all pgbouncer admin commands like SHOW POOLS or SHOW STATS. Just not able to execute the same from JDBC.
JDBC use extended query protocol by default, try simple protocol for such query
String connectionUrl = "jdbc:postgresql://"+ipaddress+":"+port+"/"+database+"?preferQueryMode=simple";
PGBouncer currently supports only the simple protocol - the packet type 80 is for 'Parse', which is the first step in the extended protocol. The message you see in the exception PSQLException actually comes from PGBouncer.

Mysql issue with dns resolution. Spring boot - Connect to mysql db using a read-only user

I have a read-only user, when I try start my spring boot application I get a exception (using password yes).
User privileges:
mysql> show grants;
+---------------------------------------------------------------+
| Grants for myuser#% |
+---------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'mydb'#'%' IDENTIFIED BY PASSWORD 'xxx' |
| GRANT SELECT ON `mydb`.* TO 'myuser'#'%' |
+---------------------------------------------------------------+
2 rows in set (0,00 sec)
Class DatabaseConfig:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "mydbEntityManagerFactory",
basePackages = {"co.com.xxx.persistence.telemercadeo"}
)
public class DatabaseConfig {
/**
* Logger to register events.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseConfig.class);
/**
* Returns a data source for database connection (source).
*
* #return {#link DataSource}. Database connection representation.
*/
#Bean(name = "mydbDataSource")
#ConfigurationProperties(prefix = "mydb.jdbc")
public DataSource sourceDataSource() {
LOGGER.info("Loading data source for source");
return DataSourceBuilder.create().build();
}
#Bean(name = "mydbEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("mydbDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("co.com.xxx.model.telemercadeo")
.persistenceUnit("mydb")
.build();
}
#Bean(name = "mydbTransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("mydbEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
My application.properties:
mydb.jdbc.url=jdbc:mysql://192.168.200.5:3306/mydb
mydb.jdbc.username=myuser
mydb.jdbc.password=mypass
mydb.jdbc.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
When I start the app I get the next trace:
2017-03-09 08:34:34.635 [main] INFO c.c.n.c.e.c.DatabaseConfig - Loading data source for source
2017-03-09 08:34:34.678 [main] INFO o.s.o.j.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'mydb
2017-03-09 08:34:34.678 [main] INFO o.h.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [
name: mydb
...]
2017-03-09 08:34:34.740 [main] ERROR o.a.tomcat.jdbc.pool.ConnectionPool - Unable to create initial connections of pool.
java.sql.SQLException: Access denied for user 'myuser'#'SUBDOMAIN.MYDOMAIN.COM' (using password: YES)
2017-03-09 10:02:26.926 [main] WARN o.h.e.j.e.i.JdbcEnvironmentInitiator - HHH000342: Could not obtain connection to query metadata : Access denied for user 'myuser'#'SUBDOMAIN.MYDOMAIN.COM' (using password: YES)
My suspicions:
Can not connect to a db with a read-only user.
Access denied for user 'myuser'#'SUBDOMAIN.MYDOMAIN.COM'. Why appears the domain?
With a user with all the privileges there is no problem. But I need connect with a read-only user.
Mysql version: 5.1
EDIT
After restart mysql server with parameter --skip-name-resolve true (as #wangyuntao suggested), the exception change to:
java.sql.SQLException: Access denied for user 'myuser'#'192.168.200.1' (using password: YES)
If db's ip is 192.168.200.5, why exception is Access denied for user 'myuser'#'192.168.200.1' (using password: YES)?
You need to explicitly grant access from localhost
GRANT USAGE ON *.* TO 'mydb'#'localhost' IDENTIFIED BY PASSWORD 'xxx'
GRANT SELECT ON `mydb`.* TO 'my_user'#'localhost'
I'm not very sure, but if you like, you can try skip-name-resolve option.
As the document says:
server-system-variables
This variable is set from the value of the --skip-name-resolve option. If it is OFF, mysqld resolves host names when checking client connections. If it is ON, mysqld uses only IP numbers; in this case, all Host column values in the grant tables must be IP addresses or localhost. See Section 9.12.5.2, “DNS Lookup Optimization and the Host Cache”.
host-cache
To disable DNS host name lookups, start the server with the --skip-name-resolve option. In this case, the server uses only IP addresses and not host names to match connecting hosts to rows in the MySQL grant tables. Only accounts specified in those tables using IP addresses can be used. (Be sure that an account exists that specifies an IP address or you may not be able to connect.)
EDIT
According to MySQL document, here is my test and it works for me.
CREATE USER 'jeffrey' IDENTIFIED BY 'mypass';
GRANT SELECT ON mydb.* TO 'jeffrey';
Then you can connect to your db from other machines, e.g.
mysql -ujeffrey -pmypass -hYOUR_DB_IP

Jython script to create oracle datasource in Websphere

The below code creates the datasource sucessfully but there is an exception when test connection is called. But when i restart the server and use the Test connection in console it works.
How to avoid server restart and make the test connection work in the script.
I do have this error after the script is executed and before restart:
J2CA0130I: Data Source [nMINEDB] has Component-managed Authentication Alias [test/nMINEDBUser] but no corresponding J2C Authentication Data Entry is defined in security.xml. This may have undesirable effects.
Code:
#
# Jython Script to create MINE web data-source and JDBC provider.
#
#Import Statements
import os
import re
import sys
# Create JDBC provider for MINE oracle database.
def createMINEJDBCProvider():
server = '/Server:server1'
# Set the Node ID
serverID = AdminConfig.getid(server)
print 'Server ID:' + serverID
#Configuring J2c auth
userAlias='test/nMINEDBUser'
alias = ['alias', userAlias]
userid = ['userId', 'MINEDB']
password = ['password', 'MINEpass']
jaasAttrs = [alias, userid, password]
security = AdminConfig.getid('/Security:/')
print 'security:'+security
j2cUser=AdminConfig.create('JAASAuthData', security, jaasAttrs)
AdminConfig.save()
print 'Creating MINE User sucessfull'
# Test to see if the provider has already been created.
MINEJDBCprovider = AdminConfig.getid('/JDBCProvider:nOracle JDBC Driver/')
if len(MINEJDBCprovider) == 0:
providerName='nOracle JDBC Driver'
print 'creating Oracle JDBC provider on server:'+serverID
print 'JDBC provider Name:'+providerName
MINEJDBCprop1 = ['name', providerName]
MINEJDBCprop2 = ['description','Oracle JDBC Driver for MINE Application']
MINEJDBCprop3 = ['implementationClassName','oracle.jdbc.pool.OracleConnectionPoolDataSource']
MINEJDBCprop4 = ['classpath','C:/jars/ojdbc/ojdbc6.jar']
MINEJDBCprops=[MINEJDBCprop1,MINEJDBCprop2,MINEJDBCprop3,MINEJDBCprop4]
providerID = AdminConfig.create('JDBCProvider', serverID, MINEJDBCprops)
AdminConfig.save()
print 'Creating Oracle JDBC provider on server sucessfull with provider:'+providerID
createMINEDataSource()
else:
print 'oracle provider exists:'+MINEJDBCprovider
def createMINEDataSource():
providerName='nOracle JDBC Driver'
userAlias='test/nMINEDBUser'
MINEJDBCprovider = AdminConfig.getid('/JDBCProvider:nOracle JDBC Driver/')
MINEDataSource = AdminConfig.getid('/JDBCProvider:'+providerName+'/DataSource:MINEDB/')
if len(MINEDataSource) == 0:
# Set the datasource attributes
MINEDSprop1 = ['name', 'nMINEDB']
MINEDSprop2 = ['jndiName', 'jdbc/nMINEdb']
MINEDSprop3 = ['description', 'MINE database']
MINEDSprop4 = ['datasourceHelperClassname', 'com.ibm.websphere.rsadapter.Oracle11gDataStoreHelper']
MINEDSprop5 = ['authDataAlias' , userAlias]
mapConfigprop=["mappingConfigAlias", "DefaultPrincipalMapping"]
mapConfigs=[MINEDSprop5 , mapConfigprop]
mappingConfig=["mapping", mapConfigs]
MINEDSprops = [MINEDSprop1, MINEDSprop2, MINEDSprop3, MINEDSprop4, MINEDSprop5, mappingConfig]
MINEDataSource = AdminConfig.create('DataSource', MINEJDBCprovider, MINEDSprops)
#Set the DB URL
propSet = AdminConfig.create('J2EEResourcePropertySet', MINEDataSource, [])
AdminConfig.create('J2EEResourceProperty', propSet, [["name", "URL"], ["value", "jdbc:oracle:thin:#myserver:1523:MINED2"]])
AdminConfig.save()
print 'Creating MINE JDBC Datasource on server sucessfull with datasource:'+MINEDataSource
#Mapping module not trying right now
#AdminConfig.create('MappingModule', MINEDataSource, mappingConfig)
else:
print 'MINE Datasource already exists in the server:'+MINEDataSource
print 'Testing datasource connection'
print AdminControl.testConnection(MINEDataSource)
try:
print 'start'
createMINEJDBCProvider()
createMINEDataSource()
print 'end'
except:
print "***** Unexpected error while creating JDBC datasource:", sys.exc_info(), " *****"
raise
j2c authentication isn't initialized until the server is recycled.

Authentication with MS SQL Server from Mac OS X

Based on this question I've built the following function, which seems to connect to the SQL Server but is unable to authenticate:
connect <- function(server, database, user, password){
# Autoinstall if necessary
packages <- c("RJDBC")
new.packages <- packages[!(packages %in% installed.packages()[, "Package"])]
if(length(new.packages)){
install.packages(new.packages, dependencies = TRUE)
}
library(RJDBC)
sql.java <- paste(find.package(package = 'mypackage'), '/sqljdbc4.jar', sep = "")
drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver",
sql.java,
identifier.quote = "`")
con.string <- paste("jdbc:sqlserver://", server, ";databaseName=", database, ";integratedSecurity=true;", sep = "")
con <- dbConnect(drv, con.string, user, password)
}
# Feb 24, 2015 9:57:56 AM com.microsoft.sqlserver.jdbc.AuthenticationJNI <clinit>
# WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path
# Show Traceback
# Rerun with Debug
# Error in .jcall(drv#jdrv, "Ljava/sql/Connection;", "connect", as.character(url)[1], :
# com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication. ClientConnectionId:5ac4ed9c-a4a8-4318-ba77-7f3fb2ed01b0
# If I take ;integratedSecurity=true out of there:
# Error in .jcall(drv#jdrv, "Ljava/sql/Connection;", "connect", as.character(url)[1], :
# com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'domain\user'. ClientConnectionId:29035eb6-7b9f-4d9c-86b4-6d6760c61399
Does anyone know how I can handle authentication? It seems to work with RODBC on my Windows machine.

ORA-12505 :TNS listener does not currently know of SID given in connect descriptor

I am using Oracle database. I've written a small JDBC connection program in Java but I am facing an issue with the listener.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcConnection {
public static void main(String[] args) throws SQLException,ClassNotFoundException {
String url = "jdbc:oracle:thin:#localhost:1521:orcl";
String user = "system";
String password = "password";
Connection connection = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, password);
if(connection!=null){
System.out.println("Success in connnection");
} else {
System.out.println("failure in connection ");
}
}
}
I am getting the following exception:
C:\Users\Administrator\Desktop>java JdbcConnection
Exception in thread "main" java.sql.SQLException: Listener refused the connectio
n with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
The Connection descriptor used by the client was:
localhost:1521:orcl
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
:261)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:
441)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtensio
n.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at JdbcConnection.main(JdbcConnection.java:18)
This is the output of lsnrctl status
LSNRCTL for 64-bit Windows: Version 12.1.0.1.0 - Production on 16-JUN-2015 13:43
:41
Copyright (c) 1991, 2013, Oracle. All rights reserved.
Welcome to LSNRCTL, type "help" for information.
LSNRCTL> status
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for 64-bit Windows: Version 12.1.0.1.0 - Produ
ction
Start Date 16-JUN-2015 12:02:52
Uptime 0 days 1 hr. 40 min. 52 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File C:\app\orauser\product\12.1.0\dbhome_1\network\admin\l
istener.ora
Listener Log File C:\app\orauser\diag\tnslsnr\hydwemvm\listener\alert\lo
g.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1521ipc)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hydwemvm)(PORT=1521)))
Services Summary...
Service "CLRExtProc" has 1 instance(s).
Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully
If you know your oracle database SID, then use
jdbc:oracle:thin:#localhost:1521:orcl
otherwise use below in case you have service name
jdbc:oracle:thin:#localhost:1521/orcl
Also, make sure service name with the name ORCL should be up and running. If still doesn't work, then you need to restart your machine and try again above.
Still, not working ? Then, try following :
Login with SYSTEM user and register LOCAL_LISTENER by running below SQLs.
alter system set local_listener = '(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))' scope = both;
alter system register;
How to check oracle SID and service name :
SELECT sys_context('USERENV', 'SID') FROM DUAL; -- It will return your oracle database SID
SELECT sys_context('USERENV', 'SERVICE_NAME') FROM DUAL; -- It will return your oracle database service name
If you want to know the default SID of your database use this query in sqlplus:
SELECT sys_context('USERENV', 'SID') FROM DUAL;
Use this value in the JDBC URL instead of "orcl".
Can you use the below URL?
Note the difference, this is to use the SERVICENAME instead of a SID.
jdbc:oracle:thin:#localhost:1521/orclservice
I am facing the same problem.
Try removing the LAN cable or disconnect your net connectivity and
restart the services of Listener and run the code.
It worked for me.

Categories