Change Username and Password of Tomcat JDBC Pool at runtime - java

with HikariCP it is possible to change Username and Password of the whole pool at runtime. You only have to set a poolName and set registerMbeans to true during the creation of the pool.
At runtime you could then use MXBeanProxy to change Username and password at runtime. It looks like this:
public void changeUser(HikariDataSource ds, String newUser, String newPassword) {
HikariConfigMXBean configBean = ds.getHikariConfigMXBean();
configBean.setUsername(user);
configBean.setPassword(password);
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName poolName= new ObjectName("com.zaxxer.hikari:type=Pool (" + dbKey + ")");
HikariPoolMXBean poolProxy = JMX.newMXBeanProxy(mBeanServer, poolName,
HikariPoolMXBean.class);
poolProxy.softEvictConnections();
}
But now I search some similar code for the Tomcat Connection Pool. Or another method to change username and password of Tomcat Connection Pool at runtime.
I hope somebody have an idea.

Related

Get the referrer's domain of the visitor for a website behind a load balancer

I have a Spring (Java) website that uses Kemp Technologies' LoadMaster as the balancer, which sits before my web servers.
I am able to get the right IP address of a visitor at any page via:
request.getRemoteAddr()
However, I am not able to get the correct domain of the referrer. Here is what I did:
I have the following code in a HandlerInterceptorAdapter, which is called for each web request. The code is to check whether a particular session variable exists. If yes, no action. If no, record the referrer's domain in session.
HttpSession session = request.getSession();
String value = (String) session.getAttribute("referrer");
if (value == null) {
String scheme = request.getScheme();
String serverName = request.getServerName();
int portNumber = request.getServerPort();
String url = scheme +"://"+serverName+ (portNumber == 80? "": portNumber);
session.setAttribute("referrer", url);
}
In other pages when I need the referrer's domain, I have the following:
String value = (String) request.getSession().getAttribute("referrer");
The problem is that the value I got is always my own domain (ex. http://www.example.com).
Where have I gone wrong?

Java cast oracleconnection eclipse

please tell me if I have to provide more information/code, becasue I am a newbie in java and maybe don't know which informations you need.
I have to add a functionality to an existing Eclipse RCP application. In this I need to register an OracleDatabaseChangeListenet to my database connection.
The problem is, the connection already exists and is of the self-designed class Connection (is designed the way, that connections to other databases except Oracle are possible) that implements self-designed interface IConnection, but basically this connection is to an Oracle 11g database.
So I need to cast this connection to OracleConnection, but get an CastExceptionError. How can I manage to cast the connection?
public void openConnection( IConnection connection) throws JeffException {
URI conURI = connection.getUri();
String con_System = conURI.getPath().split( "/")[1]; //$NON-NLS-1$
String jdbcUrl = "jdbc:oracle:thin:#//" + conURI.getHost() + ":" + conURI.getPort() + "/" + con_System; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String Jeff_user = connection.getProperty( DatabaseConstants.JEFF_USERNAME);
String Jeff_password = connection.getProperty( DatabaseConstants.JEFF_PASSWORD);
//derby-embedded
// jdbcUrl="jdbc:derby:embeddedDB1;create=true";
String Jeff_proxy_password = connection.getProperty( DatabaseConstants.JEFF_PROXY_PASSWORD);
String Jeff_proxy_username = connection.getProperty( DatabaseConstants.JEFF_PROXY_USERNAME);
OracleConnection conn=(OracleConnection) connection;
The error I get is
java.lang.ClassCastException: mapackage.projectmanager.model.Connection cannot be cast to oracle.jdbc.OracleConnection
Thanks,
Jeff

"(User has exceeded the 'max_user_connections' resource (current value: 10))" error on heroku

This question is related to Resque Mysql2::Error: User has exceeded the 'max_user_connections' resource (current value: 10)
I'm receiving the error "(User has exceeded the 'max_user_connections' resource (current value: 10))" when trying to insert a table into a MySql database.
I'm using this code to connect to the database :
#Configuration
public class MainConfig {
#Bean
public BasicDataSource dataSource() throws URISyntaxException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setUrl(dbUrl);
basicDataSource.setUsername(username);
basicDataSource.setPassword(password);
return basicDataSource;
}
}
whch is based on :
https://devcenter.heroku.com/articles/connecting-to-relational-databases-on-heroku-with-java#using-the-database_url-in-plain-jdbc
To fix this issue can I re-use this connection ?
I've tried updating the code above to re-use the same BasicDataSource but I receive error.
When I check the client connections here is what I see :
The amount of client connection decreases over time, it seems there is max number of connection that can be made within a specified time span ?
I may be wrong but I believe it is the database its self telling you that you have reached the limit. You can change it in the database options.
For a project I was working we used a connection pool and had a limit of 110 connections. This was based on a small size of users though.

Bypass password authentication for a database once a user is logged in as user on Unix?

I have written applications in Java which connect to the database by taking the username and password for the database which is set in the environment variables. So the database username and password are stored as clear text in a file on the server.
Here is the code which creates the connection string:
if (dataBase.equals("oracle"))
{
url = "jdbc:oracle:thin:#";
url = url + getParameter("Database IP", "setup.ini"); // ip
url = url + ":" + getParameter("Database Port", "setup.ini"); //port
String envVarValue = System.getenv("DBNAME");
// Environment variable has value DBNAME =
String a[] = envVarValue.split("#");
url = url + ":" + getParameter("SID", "setup.ini");
String b[] = a[0].split("/");
userName = b[0]; //User name
password = b[1]; //Password
}
Now I want my application to be able to connect to the database by the Unix user who would be running this application on the server without the need to get the password for the database user in the code.
Please tell me if this is possible and how if yes?
Refer this link on how to configure a user account for OS authentication in Oracle: http://docs.oracle.com/cd/B28359_01/java.111/b31224/clntsec.htm#CIHCBCBC
You can read the current OS user running your java program by calling System.getProperty("user.name"). When creating connection through JDBC, you may have to append this value to the prefix OS_AUTHENT_PREFIX you created as shown in the link above.

Need to create tql queries

I need to create TQL queries to query out sets of data from the UCMDB.
I am having 2 problems:
1) How can I find relationships which exists between CIs ( i do not have administrative privileges so need to do it in code somehow)
I need this to get required data.
2) I have created the following query: But I keep getting the IP property value as null.
I checked that IP has an attribute called ip_address.
Code:
import com.hp.ucmdb.api.types.TopologyRelation;
public class Main {
public static void main(String[] args)throws Exception {
final String HOST_NAME = "192.168.159.132";
final int PORT = 8080;
UcmdbServiceProvider provider = UcmdbServiceFactory.getServiceProvider(HOST_NAME, PORT);
final String USERNAME = "username";
final String PASSWORD = "password";
Credentials credentials = provider.createCredentials(USERNAME, PASSWORD);
ClientContext clientContext = provider.createClientContext("Test");
UcmdbService ucmdbService = provider.connect(credentials, clientContext);
TopologyQueryService queryService = ucmdbService.getTopologyQueryService();
Topology topology = queryService.executeNamedQuery("Host IP");
Collection<TopologyCI> hosts = topology.getAllCIs();
for (TopologyCI host : hosts) {
for (TopologyRelation relation : host.getOutgoingRelations()) {
System.out.print("Host " + host.getPropertyValue("display_label"));
System.out.println (" has IP " + relation.getEnd2CI().getPropertyValue("ip_address"));
}
}
}
In the above query output: I get the host names with IP = null
I have a sample query in JYthon which I am unable to figure out: Its for the above code only.
Attaching it for anyone who can understand it.
import sys
UCMDB_API="c:/ucmdb/api/ucmdb-api.jar"
sys.path.append(UCMDB_API)
from com.hp.ucmdb.api import *
# 0) Connection settings
HOST_NAME="192.168.159.132"
PORT=8080
USERNAME="username"
PASSWORD="password"
# 1) Get a Service Provider from the UcmdbServiceFactory
provider = UcmdbServiceFactory.getServiceProvider(HOST_NAME, PORT)
# 2) Setup credentials to log in
credentials = provider.createCredentials(USERNAME, PASSWORD)
# 3) Create a client context
clientContext = provider.createClientContext("TESTING")
# 4) Connect and retrieve a UcmdbService object
ucmdbService = provider.connect(credentials, clientContext)
# 5) Get the TopologyQueryService from the UcmdbService
queryService = ucmdbService.getTopologyQueryService()
# ======= Everything After this is specific to the query =======
# 6) Execute a Named Query and get the Topology
topology = queryService.executeNamedQuery('Host IP')
# 7) Get the hosts
hosts = topology.getAllCIs()
# 8) Print the hosts and IPs
host_ip = {}
for host in hosts:
host_name = host.getPropertyValue("display_label")
if host_name in host_ip.keys():
ips = host_ip[host_name]
else:
ips = {}
host_ip[host_name] = ips
for relation in host.getOutgoingRelations():
ip_address = relation.getEnd2CI().getPropertyValue("display_label")
if ip_address in ips.keys():
pass
else:
ips[ip_address] = ''
print "%s , %s" % (host_name, ip_address)
Please help.
I am unable to understand how to go about this further.
Thank you.
The easiest fix would be use the display_label property from the IP address CI instead of the ip_address property. The Jython reference code uses display_label for its logic.
I'd be a little concerned about using display_label since the display_label formatting logic could be changed to no display the IP address for IP CIs. Getting data directly from the ip_address property is a better choice and should work if the TQL is defined to return that data. Check the Host IP TQL and ensure that it's configured to return ip_address for IP CIs.

Categories

Resources