OpenShift 3: How To Access POSTGRESQL POD Environment Variables Using Java? - java

I have a Java webapp running successfully on Tomcat.
I have created three environment variables in my myapp deployment:
MY_ENV_VAR_1=dbuser
MY_ENV_VAR_2=dbpassword
MY_ENV_VAR_3=dbname
I can get these values using standard Java code:
myEnvVar1 = System.getenv("MY_ENV_VAR_1");
myEnvVar2 = System.getenv("MY_ENV_VAR_2");
myEnvVar3 = System.getenv("MY_ENV_VAR_3");
I used 'normal Java' code to connect to the database:
connection = DriverManager.getConnection("jdbc:postgresql://" + postgresqlServiceHost + ":" + postgresqlServicePort + "/" + myEnvVar3, myEnvVar1, myEnvVar2);
So, I can connect to the database successfully.
The problem is:
I can see (in web console) but cannot get the values from the three environment variables in the postgresql deployment:
POSTGRESQL_USER
POSTGRESQL_PASSWORD
POSTGRESQL_DATABASE
Using the 'normal' System.getenv("POSTGRESQL_USER"); does NOT work.
So, please can someone tell me how to access the values of these three postgresql pod environment variables using Java Code?

So, the simple answer is:
You manually add the following three environment variables to the deployment environment of the application that will be accessing the database.
POSTGRESQL_USER
POSTGRESQL_PASSWORD
POSTGRESQL_DATABASE
You must do it in exactly the same way as you see them in the postgresql deployment environment.
It really is that simple...
In Java app:
String postgresqlServiceHost = System.getenv("POSTGRESQL_SERVICE_HOST");
String postgresqlServicePort = System.getenv("POSTGRESQL_SERVICE_PORT");
String postgresqlDatabase = System.getenv("POSTGRESQL_DATABASE");
String postgresqlUser = System.getenv("POSTGRESQL_USER");
String postgresqlPassword = System.getenv("POSTGRESQL_PASSWORD");
Connection connection = DriverManager.getConnection("jdbc:postgresql://" + postgresqlServiceHost + ":" + postgresqlServicePort + "/" + postgresqlDatabase, postgresqlUser, postgresqlPassword);

Related

Jenkins SQLServer Choice Parameter - Retrieve data from database

I am trying to get data from SQL Server database table and show it as part of choice parameter as part of a Jenkins Job Build Parameters that I am trying to setup.
I am trying to figure out how to use Extensible Choice for this.
The Choice provider I used is "System Groovy Choice Parameter"
import groovy.sql.Sql
import com.microsoft.sqlserver.jdbc.SQLServerDriver
def output = []
def configuration = [
'dbInstance' : 'servername',
'dbPort' : 0000,
'dbName' : 'dbName',
'dbUser' : 'dbUser',
'dbPass' : 'dbPass'
]
def sql = Sql.newInstance("jdbc:sqlserver://${configuration.dbInstance}:${configuration.dbPort};"
+ "databaseName=" + configuration.dbName,
configuration.dbUser, configuration.dbPass,
'com.microsoft.sqlserver.jdbc.SQLServerDriver')
String sqlString = "SELECT * FROM dbTable"
sql.eachRow(sqlString){ row -> output.push(row[0])
}
return output.sort()
Below is the error I see. Which I understand I see because the jdbc driver is not present. I downloaded the driver from the link below:
https://www.microsoft.com/en-us/download/details.aspx?id=11774
I followed the instructions as to where it should be unzipped to as mentioned in the instructions.
I saw that the CLASSPATH variable is missing, so i went ahead and created the Environment variable with path: "C:\Program Files\sqljdbc_6.0\enu\sqljdbc.jar"
Error: unable to resolve class com.microsoft.sqlserver.jdbc.SQLServerDriver
How do i make sure that the script runs successfully and returns all the data to Extensible Choice. If there is anyother way to do this, I am open to suggestions.
Thank you very much
To resolve the issue I had to copy the "sqljdbc4.jar" file to the following location "C:\Java\jdk1.8.0_92\jre\lib\ext" since that is the path where the JAVA searches for the external jars. Use 4th version for the file which will have 4 in the file name as above as that is version Jenkins supports.

How can I override java -Xmx option in application?

I am running a script in PowerShell, that calls a java application, but this application fails due to Out.of.memory.error: Heap Size. I created environment variable, but it didn't work. From the dump txt file I found out, that the java_command_line contains -Xmx512m option:
IBM_JAVA_COMMAND_LINE=C:\Program Files\ (x86)\IBM\Java70\jre\bin\java.exe -Xmx512m -classpath C:\Users\IBM_ADMIN\Desktop\Nessus_Scripts\nessusconverter.exe;...
From what I learned, this overrides my created environment variable and lowers the max heap size for this application. I guess it is coded in the called application. My problem is, that I don't know the author of the application and need it for my work. I am also time-limited, so some deep debugging or improving of this app is off limits.
Is there a way to override the option set in the application (without interfering in the app)?
I have Windows 7 and IBM SDK Java version 7.0.
Script calling the java app:
Function CallNessusConverter ( [Array]$input_files
[String]$output_filename, [String]$exceptions_filename,
[String]$hosts_filename, [String]$output_directory ) {
[String]$output_XML_file = $output_directory + "\" + $output_filename + ".xml"
[String]$output_Issue_file = $output_directory + "\" + $output_filename + "-Issues.csv"
[String]$output_Missed_file = $output_directory + "\" + $output_filename + "-NotScanned.csv"
[String]$input_XML_files = ""
foreach ($file in $input_files){
$input_XML_files += " " + $file
}
Write-Host "**** Calling nessusconverter ****"
[string]$CLI_nessusconverter = ".\nessusconverter -inputXMLfiles $input_files -exceptions $exceptions_filename -hosts $hosts_filename -outputXML $output_XML_file -outputIssue $output_Issue_file -rmunknown -outputMissed $output_Missed_file"
iex $CLI_nessusconverter
...
CallNessusConverter $input_files $output_filename $exceptions_filename $hosts_filename $output_directory`
As some kind of workaround, if there no other solution, you could try to replace the java.exe with a file that calls the real java with the desired parameters... Of course this is not a good idea if other applications use this java.exe as well.

MySql Driver Not Loading In Java

When I use the following line,
Class.forName("com.mysql.jdbc.Driver");
//Sets up database connection
connect = DriverManager.getConnection("jdbc:mysql://www.papademas.net/tickets?"
+ "user=root&password=jamesp");
statement = connect.createStatement();
String sql = "INSERT INTO JReimTicketer (dateIssued, ticketName, issuerName,"
+ " issuerDepartment, ticketDescription, activity) "
+ "VALUES (SYSDATE(),'"+ticketName+"', '"+issuerName+"', "
+ "'"+issuerDepartment+"', '"+ticketDescription+"', "
+ " '"+activity+"')";
my program stops, and it doesn't seem like it loads the driver. I've downloaded it, so I'm not sure why it's not working. Any help would be appreciated.
Firstly if your are using jdbc 4.0, you don't require
Class.forName("com.mysql.jdbc.Driver");
to load driver as it it auto-loaded when you call
DriverManager.getConnection();
If you have specified mysql jar in your class path, the problem must be in your url. So kindly check your URL/Username/Password
Also, if you are getting exception,please post stacktrace
Your code seems to be correct. And I think you're right. Things aren't missing from Front-End but Back-End. So, before you compile your code, you need to put MySQL Connecter jar (mysql-connector-java-x.x.xxx-bin.jar) file in your Java Buildpath Path. Do it before you compile and run the code.

runtime.getruntime().exec("wscript.exe macro.vbs") doesn't work on windows server 2008

I have a web application on a server deployed in tomcat 7 on windows server 2008.
This web application is running these lines of code:
String path = req.getServletContext().getRealPath("/") + "WEB-INF/vbs/macro.vbs";
int range = 1;
int range1 = 1;
int status = Runtime.getRuntime().exec("wscript.exe" + path + "" + range + "" + range1 + "" + temp.getAbsolutePath() + "" + temp1.getAbsolutePath()).waitFor();
On the local computer, the execution succeeds perfectly. Deployed to the server, instead, the application stops on the exec runtime and the browser waits for a response.
What could be the cause?
I know this is a very old question but still worth replying in case that someone with a similar problem.
Executing external programs using Runtime.getRuntime().exec() is perfectly fine but in this case there were no spaces in between the parameters, meaning that the command to be executed was wscript.exe/WEB-INF/vbs/macro.vbs11... instead of wscript.exe /WEB-INF/vbs/macro.vbs 1 1 ....
The Runtime.getRuntime().exec(String) method automatically splits the string by spaces so another potential problem is that arguments in the command string might need to be wrapped in quotes to prevent them from being parsed incorrectly by the application.
The correct code would have been:
int status = Runtime.getRuntime().exec(
"wscript.exe \"" + path + "\" " + range + " " + range1 + "\" " +
temp.getAbsolutePath() + "\" " + temp1.getAbsolutePath() + "\"")
.waitFor();
The fact that it worked in some servers but not in others could very well be related to the paths where these files were deployed having or not having spaces in them (e.g. "C:\Program Files").

how to setup cassandra java driver with eclipse

I am new to cassandra and moven. I was trying to write a simple java program in eclipse that uses cassandra java driver to connect to a cassandra node I have setup.
I found this repository https://github.com/datastax/java-driver but I have no idea what I should do with it. Can anyone give me step by step instructions for getting the driver and creating a simple eclipse project that uses the driver.
Start Eclipse (make sure eclipse has maven, I used eclipse KEPLER)
Create a new eclipse project (Under the Maven folder select "Maven Project")
Give the project a name / group-id / artifact-id
Open pom.xml and then click on the actual pom.xml tab.
Add the dependency shown on github, my pom file ended up looking like this.
And finally write a class to do some stuff with the driver, the below creates a keyspace and a column family.
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
public class App
{
public static void main( String[] args )
{
Cluster cluster = Cluster.builder()
.addContactPoints("127.0.0.1")
.build();
Session session = cluster.connect();
String cqlStatement = "CREATE KEYSPACE myfirstcassandradb WITH " +
"replication = {'class':'SimpleStrategy','replication_factor':1}";
session.execute(cqlStatement);
String cqlStatement2 = "CREATE TABLE myfirstcassandradb.users (" +
" user_name varchar PRIMARY KEY," +
" password varchar " +
");";
session.execute(cqlStatement2);
System.out.println("Done");
System.exit(0);
}
}
Also check this answer out for CRUD operations with the driver.

Categories