Dynamically change JDBC config in Jmeter - java

I need to make sure,whether table has data or not ,based on the environment,say for example i have two two database,one is development another one is production like given below.
Production
host1
dbuser1
dbpassword1
dburl
Tablename : studentinfo
Development
dbuser2
dbpassword2
dburl2
Tablename : studentinfo
FYI : studentinfo has same structure in both environment .
In Jmeter ,User Defined Variable( UDV), I have configured two set of database information. Using BeanShell Processor I have trying to change the database connectivity information, Is there any way to change the Db Config dynamically ?
Given below is my Jmeter UDV
env : prod
prod_db_url: dburl
prod_db_user:usr
prod_db_password:password
dev_db_url: dburl
dev_db_user:usr
dev_db_password:password
In My Beanshell Preprocessor
String env=vars.get("env");
if(env.equlas("prod")){
// Load the Prod db into vars
} else if (env.equals("dev")){
// Load the Dev db into vars
}
Here ,I am setting the values in vars, and trying to get the information from DB Configuration variables. but i am not able get values the in DB config.
Can anyone explain ? what went wrong or what is the approach to get connection?

JDBC Connection Configuration is initialized after User Defined Variables but before any PreProcessor, that's why you don't see values changes.
Consider using JMeter Properties instead of JMeter Variables, i.e. change ${dburl} in JDBC Connection Configuration to ${__P(dburl,)}. Do the same for credentials variables.
Depending on how you run your test you can set properties value:
Via -J command-line argument like:
jmeter -Jdburl=jdbc://somedb:port/etc -Juser=foo -Jpassword=bar
Put it into user.properties file (located in JMeter's "bin" folder) like
dburl=jdbc://somedb:port/etc
user=foo
password=bar
References:
__P() function user manual entry
Apache JMeter Properties Customization Guide

You do not need a Beanshell PreProcessor for this.
For the below UDV,
env : prod
prod_db_url: dburl
prod_db_user:usr
prod_db_password:password
dev_db_url: dburl
dev_db_user:usr
dev_db_password:password
Just by changing the value of env, you can access all the variables values by using
${__V(${env}_db_url)} // return prod or dev db url depends on the value of env.
Another nice solution:
Can you have the same variables and store them in 2 different property files?
prod.proeprties
db_url=dburl
db_user=usr
db_password=password
dev.properties
db_url=dburl
db_user=usr
db_password=password
You can use the JMeter - Property File Reader.
Property reader file path would be /path/to/${env}.properties
Access all the variables using ${__P(db_url)}, ${__P(db_user)}

Related

JMeter JSR233 result to dashboard

I have a JMeter test that insert an input via an HTTP call to an asynchronous java-service and then collects an exposed metric on another java-service via a groovy script.
The script then saves the collected metric as a JMeter variable to be reviewed as a performance metric.
I would like to publish this value inside the JMeter -generated dashboard but I can't find a way to save this variable as a JMeter output.
Is there a way? seems JMeter is primarily aimed to test HTTP synchronous services but it's capable of doing such collection of data.
You can use variable(s) in custom graph definitions:
You can graph any sample_variable in CSV over time, you can customize your graphs by settings their properties in the user.properties file.
They must use the id prefix custom_:
jmeter.reportgenerator.graph.custom_<your_graph_name_id>.property.<your_option_name>
To specify that this graph is a customized one :
jmeter.reportgenerator.graph.custom_<your_graph_name_id>.classname=org.apache.jmeter.report.processor.graph.impl.CustomGraphConsumer
Here is an example of a custom graph configuration that graphs the variable ts-hit:
jmeter.reportgenerator.graph.custom_testGraph.classname=org.apache.jmeter.report.processor.graph.impl.CustomGraphConsumer
jmeter.reportgenerator.graph.custom_testGraph.title=Chunk Hit
jmeter.reportgenerator.graph.custom_testGraph.property.set_Y_Axis=Number of Hits
jmeter.reportgenerator.graph.custom_testGraph.set_X_Axis=Over Time
jmeter.reportgenerator.graph.custom_testGraph.property.set_granularity=60000
jmeter.reportgenerator.graph.custom_testGraph.property.set_Sample_Variable_Name=ts-hit
jmeter.reportgenerator.graph.custom_testGraph.property.set_Content_Message=Number of Hits :
Declare the JMeter Variable you're saving in the JSR223 script as a Sample Variable, in order to do this add the next line to user.properties file:
sample_variables=foo
Then you can configure your custom chart like:
jmeter.reportgenerator.graph.custom_testGraph.classname=org.apache.jmeter.report.processor.graph.impl.CustomGraphConsumer
jmeter.reportgenerator.graph.custom_testGraph.title=Your custom chart title
jmeter.reportgenerator.graph.custom_testGraph.property.set_Y_Axis=Your Y axis name
jmeter.reportgenerator.graph.custom_testGraph.set_X_Axis=Over Time
jmeter.reportgenerator.graph.custom_testGraph.property.set_granularity=60000
jmeter.reportgenerator.graph.custom_testGraph.property.set_Sample_Variable_Name=foo
jmeter.reportgenerator.graph.custom_testGraph.property.set_Content_Message=Your custom content message
replace foo with the actual JMeter Variable name of your choice and next time you generate HTML reporting dashboard you should see your variable values plotted over time
More information:
Reporting configuration
Apache JMeter Properties Customization Guide

How to give connection details for cassandra in properties file using datastax java driver

Initializer myInitializer = ... // your implementation
Cluster cluster = Cluster.buildFrom(myInitializer);
Im trying to connect to Cassandracluster with several node details mentioning in addcontactpoints("192.1.1.1","192.2.2.2").build().
Now I want to connect to Cassandra cluster with out mentioning the in that method. I want to mention my node details in separate properties file and want to connect to my cluster using that properties file. I have got one method in Java driver called getcontactpoint().
I'm not getting how to use that and implement it. Please help me to improve my code
put all nodes ip like below
nodes=192.1.1.1,192.2.2.2
In java Resource interface is there by using that you can get your properties file
Like ResourceBundle resource=ResourceBundle.getBundle("cassandra")
then by getProperty method you can get nodes and split it by comma(,) so it will gives you Array of String mean all IP .
Like
nodes=resource.getString("nodes")
then in method addContactPoints() just give nodes variable .
Like addContactPoints(nodes)

how to create environmental variables for my program

I made a program in Java that uses two external databases. The paths to these databases are hard-coded inside my program code.
In order to make this program usable for other users on other computers (who should also install these two databases on their computers), I think that the path for these two databases should be added as environmental variables ? How could this be done ?
I am not a professional when it comes to environmental variables, so can you please advise what should be done in this case?
Thanks in advance
To get the value of an environment variable in Java, you write something like this:
String pathToDatabase = System.getenv().get("PATH_TO_DATABASE");
(where PATH_TO_DATABASE is the name of the environment variable). This uses System.getenv() to get a map of all environment variables.
To set the value of an environment variable in Linux, your users can write something like this:
export PATH_TO_DATABASE=/this/is/the/path/to/the/database
before running the program.
Environment vars are usually not be the best way to handle app config, but if you must, the specific OS docs are needed to learn how to set them and from Java use:
Map map = System.getenv();
Rather than environment variables, a properties file would be useful and more portable. For example, in your properties file you could have the following:
db.url = jdbc://foo/bar?whatever
db.user = username
db.password = password
Then your code could read that in using the follow:
Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
System.err.println( "Eeeek!" );
}
System.out.println( properties.getProperty( "db.url" ) );
Handily, properties objects allow you to specify defaults, so you could still have the hardcoded values if you want and then override them with the external file.

Read a Environment Variable in Java with Websphere

I've a little problem with Websphere application server 7.0 (WAS7) and the reading of Environment Varaibles.
With TomCat, I've defined a variable as
<Environment name="myVar" type="java.lang.String" value="myVarOnServeur"
and I read it with a lookup on the initialContext :
Context ctx = new InitialContext();
String myVar = (String) ctx.lookup( "java:comp/env/myVar" );
and it works!
But with Websphere, I define a environment variable on the GUI but I can't read it in my java code. I've a NamingException.
(source: fullahead.org)
How can I do to fix my problem?
to define inside web.xml
<env-entry>
<env-entry-name>varName</env-entry-name>
<env-entry-value>56</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>
to see with java
Context envEntryContext = (Context) new InitialContext().lookup("java:comp/env");
String mydata = (String)envEntryContext.lookup("varName");
You are looking at the wrong place.
You should add the variable in Environment->Naming->Name space bindings->New.
If you choose Binding type String, "Binding identifier" and "Name in namespace..." myVar, you can get variable's value with:
Context ctx = new InitialContext();
String myVar = (String) ctx.lookup( "cell/persistent/myVar" );
On WAS follow the above setting where name is your key and value is your property value. in my example i used Name : Test Value : This is the test value. After setting this values restart your application server. on your Java code call System.getProperty("TEST") where test is the name for your property and the value will show
You can put something like the following in your web.xml file, which should be in your application's WEB-INF directory:
<env-entry>
<env-entry-name>myVar</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>myVarOnServeur</env-entry-value>
</env-entry>
By the way this is a standard syntax and should work across all the application servers. I'm using it with WebSphere, JBoss and WebLogic. It can be queried exactly as you do in your example.
If what you want is to define and manage your own variables, have a look at Environment->Naming->Name space bindings. You can bind jndi names to String constants there. see String binding settings
You should be able to resolve these via WebSphere's AdminOperations MBean:
//sample code from WAS 7 Infocenter
private String expandVariable(String s) throws
javax.management.JMException {
com.ibm.websphere.management.AdminService as =
com.ibm.websphere.management.AdminServiceFactory.getAdminService();
String server = as.getProcessName();
String mBeanName = "*:*,type=AdminOperations,process=" + server;
java.util.Set result = as.queryNames(
new javax.management.ObjectName(mBeanName) , null);
return (String) as.invoke((javax.management.ObjectName)
result.iterator().next(),
"expandVariable",
new Object[]{"${"+s+"}"},
new String[]{"java.lang.String"});
}
See Creating, editing and deleting WebSphere variables.
Websphere 7.0 - 8.5
Set Variable
Admin Console ---> Websphere Application servers -----> Your_sever_name ---> Java and process management ---> Process definition -->Java Virtual Machine --> Custom properties
Get Value in Java
System.getProperty("Your_Variable")
I would just like to elaborate on creating a variable in WebSphere that can be used by a Java app, to hopefully help others, as I had to do a bit of additional research to figure this out.
Let's say you want to create a variable in WebSphere named ENV which contains a value of dev (or int, or prod, or any other value).
In the left panel of the WebSphere admin console, select Servers >
Server Types > WebSphere application servers.
Select the application server that contains the app.
Expand Java and Process Management and select process definition.
Select Java Virtual Machines.
Select Custom properties.
Select New.
Create the name and value of the variable and select OK.
Select Save.
Restart the application server for this change to take effect.
In this example, a variable named ENV with a vaule of "dev" was created.
Next, the Java app will need to be configured to use the ENV variable in WebSphere. In the below markup, the Java app has a class named "Environment". This class creates a variable named env. System.getProperty("ENV") is the magic that gets the variable from WebSphere. It is noteworthy that this Java code should also work with other application servers, such as JBoss or Tomcat, so you don't need to customize the Java code to a particular platform.
While definitely not required, I also am returning env. I am just doing this for demonstration, so that we can get the variable in a JSP page, so that we can see the variables with our own eyes in a JSP page, for validation that this works as expected.
package com.example.main;
public class Environment {
public String env;
public Environment() {
env = System.getProperty("ENV");
}
public String getEnvironment(){
return env;
}
}
Inside of the tags of a JSP page, I add the following markup to get the env variable from the Environment class, which in turn gets the ENV variable from WebSphere.
<%#page import="com.sample.main.Environment"%>
<%
Environment foo = new Environment();
String env = foo.getEnvironment();
out.print("Environment : " + env;
%>
Now, once the app has been deployed to WebSphere, the environment should be displayed, which is how I know that I was able to successfully get the variable from the application server.
The thread is kind of old but just wanted to provide some info. This is with WebSphere 8.5.5
I tried getting WebSphere variables defined in the console via [Environment > WebSphere variables] using
System.getProperty("Variable");
It did not give the variable to me. I looked around a bit on the web and came across the following:
https://www.setgetweb.com/p/WAS855/ae/was2873.html
The following function listed there returns the variables
private static String expandVariable(String s) throws
javax.management.JMException
{
com.ibm.websphere.management.AdminService as = com.ibm.websphere.management.AdminServiceFactory.getAdminService();
String server = as.getProcessName();
java.util.Set result = as.queryNames(new javax.management.ObjectName("*:*,"
+ "type=AdminOperations,process=" + server), null);
return (String)as.invoke((javax.management.ObjectName) result.iterator().next(),"expandVariable",
new Object[] {"${"+s+"}"}, new String[] {"java.lang.String"});
}
Then call
expandVariable("Variable");
I don't see anything there that says that those entries can be read via ctx.lookup( "java:comp/env/..." );

h2 (embedded mode ) database files problem

There is a h2-database file in my src directory (Java, Eclipse): h2test.db
The problem:
starting the h2.jar from the command line (and thus the h2 browser interface on port 8082), I have created 2 tables, 'test1' and 'test2' in h2test.db and I have put some data in them;
when trying to access them from java code (JDBC), it throws me "table not found exception". A "show tables" from the java code shows a resultset with 0 rows.
Also, when creating a new table ('newtest') from the java code (CREATE TABLE ... etc), I cannot see it when starting the h2.jar browser interface afterwards; just the other two tables ('test1' and 'test2') are shown (but then the newly created table 'newtest' is accessible from the java code).
I'm inexperienced with embedded databases; I believe I'm doing something fundamentally wrong here. My assumption is, that I'm accessing the same file - once from the java app, and once from the h2 console-browser interface. I cannot seem to understand it, what am I doing wrong here?
EDIT: as requested, adding some code:
Java code:
Class.forName("org.h2.Driver");
String url = "jdbc:h2:" + "db/h2test.db";
String user = "aeter";
String password = "aeter";
Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement ps2 = conn.prepareStatement("Show tables;");
ResultSet rs = ps2.executeQuery();
This resultset has 0 rows (no tables), instead of showing me the 2 tables.
H2 Console-browser interface settings:
Settings: Generic h2(embedded)
driver class: org.h2.Driver
JDBC URL: jdbc:h2:../../workspace/project_name/src/db/h2test.db
user name: aeter
password: aeter
EDIT2: I copied the database to a new folder. Now the db file in the new folder is shown with the 'newtest' table (from the java code) and with the 'test1' and 'test2' tables (from the console-browser h2 interface) - exactly the same way the older db file was shown. So the problem persists with the copy of the db file.
For embedded mode, you'll need to check the path. For example, use a path relative to your home directory:
"jdbc:h2:file:~/db/h2test.db"
To be sure, use a full path:
"jdbc:h2:file:/users/aeter/db/h2test.db"
For convenience, append ;IFEXISTS=TRUE to avoid creating spurious database files.
See Connecting to a Database using JDBC for more.
H2 Server URLs are relative to the -baseDir specified as a parameter to main().
Also there can be a problem if you use some special parameters in your JDBC url, the database file name can differ for various cases.
In my case, I had two URLs:
jdbc:h2:~/XXX;MVCC=FALSE;MV_STORE=FALSE
jdbc:h2:~/XXX
This first case created XXX.h2.db file, the second one XXX.mv.db, beware.
Also you can like this
"jdbc:h2:file:db/h2test.db"
then java looks db folder from project folder
->projectName // project folder
-->src // src folder
-->db // here your database folder
-->....
If you are using Hibernate try this in hibernate.cfg.xml file:
<property name="connection.url">jdbc:h2:file:db/h2test</property>
without *.db extension at the end

Categories