Heroku properties file - java

I am using a properties file to hardcode a list of valid usernames in a Java webapp.
The file is placed in the same package as the class (which is a struts action) and is read as follows:
Properties prop = new Properties();
InputStream input = null;
input = getClass().getResourceAsStream("login.properties");
prop.load(input);
String[] aprovedUsers = prop.getProperty("approvedUsers").split(",");
It works ok when I test it locally (in an Apache server running as localhost), but when I deploy the webapp to heroku, it seems that it can't read the propoerties file as input is null.
Is there a special consideration that needs to be taken into account when using properties files in heroku?
EDIT: My Procfile is
web: java $JAVA_OPTS -jar target/dependency/jetty-runner.jar --port $PORT target/*.war
I am using Jetty as container.

Your local classpath and heroku classpath are different. Refer to ClassLoader.getSystemResource in order to find file.
FileInputStream stream = new FileInputStream(ClassLoader.getSystemResource("login.properties").getPath());

Related

How to externally provide mysql host to spring boot while executing JAR

I have a java Spring boot project which uses a MySQL database. I have the following application.properties file to specify the MySQL url, user and password:
spring.datasource.url=jdbc:mysql://${DB_HOST}:${DB_PORT}/${DB_NAME}
spring.datasource.username=${MYSQL_USER}
spring.datasource.password=${MYSQL_PASSWORD}
Using this property file, I can run the application from Eclipse if I edit the run configurations and set the values of DB_HOST, DB_PORT, DB_NAME, MYSQL_USER and MYSQL_PASSWORD in the Environment tab and run it.. everything works fine.
But now I want to run it on the server, by generating a JAR and passing these values from command line to the Jar during run time. So, I created a Jar file like this:
/gradlew clean build bootJar -DDB_HOST=mock -DDB_PORT=mock -DDB_NAME=mock \
-Dmysql_user=mock \
-Dmysql_password=mock
this successfully generates the executable Jar file.. then I try to run the generated jar file like this:
java -jar build/libs/MyApplication.jar -Ddb_host=localhost \
-Ddb_port=3306 \
-Ddb_name=my_db \
-Dmysql_user=root \
-Dmysql_password=root
but it gives the following error:
...
Failed to parse the host:port pair '${DB_HOST}:${DB_PORT}'
...
java.lang.NumberFormatException: For input string: "${DB_PORT}"
...
Which means that it is not actually replacing the values during runtime.
How do I fix this?
Edit: I also tried to open up the jar using archive utility and saw the application.properties file.. it contains the following line:
spring.datasource.url=jdbc:mysql://${DB_HOST}:${DB_PORT}/${DB_NAME}
which means that these values should have been updated during runtime. but it isn't
I was eventually able to get this to work by adding a DatasourceConfig class and setting the values programatically.
I removed all the spring.datasource.* values from my application.property file and then created a new class:
#Configuration
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class DatasourceConfig {
#Bean
#Primary
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(System.getProperty("MYSQL_URL"));
dataSource.setUsername(System.getProperty("MYSQL_USER"));
dataSource.setPassword(System.getProperty("MYSQL_PASSWORD"));
return dataSource;
}
}
This allows you to configure the datasource, username and password externally as VM arguments at runtime.
The values MYSQL_URL,MYSQL_USER,MYSQL_PASSWORD are passed onto the gradle command while building like this:
./gradlew clean build bootJar -DMYSQL_URL=mock -DMYSQL_USER=mock -DMYSQL_PASSWORD=mock
, and similarly to the java command while running the jar like this:
java -jar build/libs/MyApplication.jar -DMYSQL_URL=jdbc:mysql://localhost:3306/my_db -DMYSQL_USER=root -DMYSQL_PASSWORD=root
You just need to expose those Fields as Environment Variables before running the jar.
For Linux:
$ export DB_HOST=localhost
$ export DB_PORT=3306
$ export DB_NAME=my_db
$ export MYSQL_USER=root
$ export MYSQL_PASSWORD=root
$ java -jar build/libs/MyApplication.jar

server.port properties not working after buildin spring boot project

i'm working on spring boot project and all works fine , now i want to build and run the app.
in the application.properties file i set the property server.port = 8090
after building the project using maven i run the following command
java -jar jarfilename.jar but it says the port 8080 is already in use.
i try these commands:
java -jar -Dport=8090 jarfilename.jar
and
java -jar jarfilename.jar --port=8090
but also i got the same message the port 8080 is already in use.
I'm wondering why it takes the port number 8080 and ignore the port number 8090 that i set in the application.properties file.
Note : (I'm using tomcat embedded server) and when i check the folder target/classes.. application.properties i didn't find the property server.port=8090.
can anyone explain to me what' happen exacly?
thanks in advance.
Is the application.properties located at the right location?
Description from Spring.io:
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).
Use java -jar -Dserver.port=8090 jarfilename.jar to set the port from command line.
Hint, from Spring.io: If you want to use the short term -Dport=8090, you can use server.port=${port:8080} in your application property file.
I encountered the same problem, in my case, I didn't pass the args to SpringApplication.
public static void main(String[] args) {
SpringApplication.run(MySpringConfiguration.class);
}
should be
public static void main(String[] args) {
SpringApplication.run(MySpringConfiguration.class, args);
}
when you create spring boot application using 'spring initializer' select jar file
I know its an old post, but I might know the answer(maybe it will help others): There is a hierarchy with the configuration settings.
The applicaton.properties file is at the bottom(OS env. variables, Java System properties etc. are all above), on the other hand, terminal parameters are at the top.
So when the server initialized, it used the port from a property setting, that is higher in the hierarchy ladder.

Running a script from a folder on a Tomcat Server

I am trying to run a script on my tomcat webserver. To run the script before on my local machine, this is the code I used.
String absolutePath = new File(".").getAbsolutePath();
int last = absolutePath.length()-1;
absolutePath = absolutePath.substring(0, last);
String filePath = "";
if(osVersion.equalsIgnoreCase("Ubuntu"))
{
try (FileReader fr = new FileReader("template.txt");
FileWriter fw = new FileWriter("Ubuntu/ubuntu_file.json");) {
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
}
filePath = "Ubuntu";
String fi = absolutePath + filePath;
System.out.println(fi);//Get the full path.
// Create ProcessBuilder.
ProcessBuilder pb = new ProcessBuilder("bash", "-c",
"cd "+fi+" ; PACKER_LOG=1 /usr/local/bin/packer build ubuntu_file.json");
Process p = pb.start();
When I however try to run it on the tomcat webserver, I keep getting this error.
EclipseEE.app/Contents/MacOS/Ubuntu Failed to parse template: open
ubuntu_file.json: no such file or directory
I am fairly new to Tomcat, and I am just learning it's ins and outs. What tomcat directory should I place my Ubuntu folder (I am assuming it's the webapp directory) in order for tomcat to get the absolute path of the folder and then be able to run the script.
If you have a more or less conventional Tomcat installation then the $CATALINA_HOME environment variable will be set and point to your server installation which will contain at least the following directories:
$CATALINA_HOME/
bin/
conf/
lib/
webapps/
You can get the value of $CATALINA_HOME via:
String catalinaHomeDir = System.getenv("CATALINA_HOME");
I would be inclined to put your configuration in the conf subdirectory.
If you're running multiple Tomcat instances from the same base then be sure to read the RUNNING.txt file that comes with it because you may need to use $CATALINA_BASE instead.
You may need to set up CATALINA_HOME/BASE in your Eclipse Tomcat Runtime environment when running locally with an Eclipse controlled server.
BTW. This is not a portable solution. If you need to migrate to some other container (such as WildFly or Glassfish) then the absolute path config recommended by others is the way to go.

Open a file on Openshift using Java

I have a DIY cartridge. My project structure looks like
MY_PROJECT
-diy
-myProgram.jar
-resources
-file1, file2...
-.openshift
-action_hooks
-start
The myProgram.jar uses files from the folder 'resources'.
The code looks like
File imageFolder = new File("resources");
System.out.println("Image Folder read:"+imageFolder.canRead()); //canRead returns false
File[] listOfFiles = imageFolder.listFiles(); // here I get null
The program runs by action hook 'start':
nohup java -jar $OPENSHIFT_REPO_DIR/diy/*.jar --server.port=${OPENSHIFT_DIY_PORT} --server.address=${OPENSHIFT_DIY_IP} &
The problem is that I'm not able to work with files.
As described in code comments I get null on listFiles().
If I run the program on Openshift manually(ssh to server/$OPENSHIFT_REPO_DIR/diy/ and run java -jar ...) it works, but it doesn't work via action_hooks.
Thank you in advance!
I resolved the issue with Openshift env variable 'OPENSHIFT_REPO_DIR'.
Instead of using relative path
new File("resources");
I use absolute
String absolutePath = System.getenv("OPENSHIFT_REPO_DIR");
new File(absolutePath + "diy/resources")

how to connect jetty server with solr instance

I'm running Jetty as a service (followed these instructions) on an Ubuntu 14 server. It's been configured to run on port 9000, and it seems to this just fine.
On the same server, I have a solr instance folder (it's located outside of jetty, as part of a website).
What I would like, is to be able to browse to hostname:9000/solr and hostname:9000/solr/admin and then see/manage the data that's in my solr instance folder, but all I ever get from the Jetty service are 404-errors.
The instance itself works perfectly if I start it manually by running 'java -Djetty.port=9000 -jar start.jar' - however, this is not what I want.
What do I need to do?
Edit: Here is the output from service jetty check
root#ubuntu14:/opt/web/mybase/webapps# service jetty check
Checking arguments to Jetty:
START_INI = /opt/web/mybase/start.ini
JETTY_HOME = /opt/jetty/jetty-distribution-9.2.7.v20150116
JETTY_BASE = /opt/web/mybase
JETTY_CONF = /opt/jetty/jetty-distribution-9.2.7.v20150116/etc/jetty.conf
JETTY_PID = /var/run/jetty.pid
JETTY_START = /opt/jetty/jetty-distribution-9.2.7.v20150116/start.jar
JETTY_LOGS = /opt/web/mybase/logs
JETTY_STATE = /opt/web/mybase/jetty.state
CLASSPATH =
JAVA = /usr/bin/java
JAVA_OPTIONS = -Dsolr.solr.home=/var/www/mywebsite/private/my-solr-4.7 -Djetty.logs=/opt/web/mybase/logs -Djetty.home=/opt/jetty/jetty-distribution-9.2.7.v20150116 -Djetty.base=/opt/web/mybase -Djava.io.tmpdir=/opt/jetty/temp
JETTY_ARGS = jetty.state=/opt/web/mybase/jetty.state jetty-logging.xml jetty-started.xml
RUN_CMD = /usr/bin/java -Dsolr.solr.home=/var/www/mywebsite/private/my-solr-4.7 -Djetty.logs=/opt/web/mybase/logs -Djetty.home=/opt/jetty/jetty-distribution-9.2.7.v20150116 -Djetty.base=/opt/web/mybase -Djava.io.tmpdir=/opt/jetty/temp -jar /opt/jetty/jetty-distribution-9.2.7.v20150116/start.jar jetty.state=/opt/web/mybase/jetty.state jetty-logging.xml jetty-started.xml
Jetty running pid=4728
First make sure you have deployed the solr.war file correctly into Jetty as described here. Basically you have 2 options -
Copy the war file into the JETTY_HOME/webapps directory
Add the war file path into $JETTY_HOME/contexts/context.xml file
This will deploy Solr into jetty.
To run Solr, set the Dsolr.solr.home system property to point to your Solr root directory e.g. java -Dsolr.solr.home= -jar start.jar

Categories

Resources