Running a script from a folder on a Tomcat Server - java

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.

Related

Java Spring Boot failing to find Python Script in resources folder

I am trying to call python Scripts(in resources) from my Java class.
This is my code spinnet
String res = "/Scripts/Brokers/__init__.py";
URL pathUrl = this.getClass().getResource(res);
String path = "";
if(pathUrl != null)
path = pathUrl.toString();
ProcessBuilder pb = new ProcessBuilder("/usr/bin/python3.6", path);
ProcessBuilder is giving error No such file or directory.
P.S.
value of path = "file:/home/path-to-project/project-name/out/production/resources/Scripts/Brokers/\__init__.py"
Also how to include python scripts in jar file to run the project on linux server.
I am stuck with this issue since last 3 days. Please suggest.
From java doc:
https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
Starting a new process which uses the default working directory and
environment is easy:
Process p = new ProcessBuilder("myCommand", "myArg").start();
So basically, you going to fork a sub process that will
start a python interpreter
with the python script that you have provided as argument.
The path to your script should be a normal path that your OS can understand, therefore you should not give a URI? like path (protocol:address/path).
if (path.contains(":"))
path = (path.split(":"))[1];
Also the backslash \ before __init__.py looks suspicious.
You should be able to run ls /home/path-to-project/project-name/out/production/resources/Scripts/Brokers/__init__.py and see the file, the same goes for ls /usr/bin/python3.6.

Jboss is changing the file permission of a directory under the deployed war

I have code in my j2ee web applicaiton directory which deletes the contents of a sub directory under the deployed War and then replaces with the new ones.
The code works fine in Tomcat but fails in Jboss. This happens in Windows 7 but not in Ubuntu . In Ubuntu , I installed JBoss under user home directory.
I am using the ApacheIO's FileUtils.cleanDirectory method to clean the contents of the subdirectory.
In another test , I wrote a simple Test class with the following lines
File file = new File("D:\\appserver\\jboss-eap-
7.0\\standalone\\deployments\\MyWar.war\\common\\graphpane2");
File jsFile = new File(file, "js");
System.out.println("jsFile.isDirectory() = " + jsFile.isDirectory());
System.out.println("jsFile.isDirectory() = " + jsFile.exists());
System.out.println("file = " + file.exists());
//File file = new File("D:\\VMs\\tex.txt");
try {
FileUtils.cleanDirectory(file);
} catch (IOException e) {
e.printStackTrace();
}
When jboss is running , jsFile.exists() is returning false inspite of the fact that the directory exists. But when jboss is closed, code just works fine.
Another point - When I go the the directory manually through windows explorer and delete the subdirectory, I get a windows dialog saying that I need permission from the user.
I ran the Jboss through a command prompt opening the command prompt itself as an administrator. But no help.
Needless say any help in this regard will be highly appreciated. I am using JBoss 7.0 eap.

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")

Working directory of a Tomcat webapp

I have a Java web application that is deployed on an Apache Tomcat 6 Server. The application includes an info.properties file that is added to the classpath, and has several hard coded values, which are read during runtime.
I now need to remove a certain value from the info.properties file, and build the value (a String, that of path to the bin folder of the same Tomcat installation) instead.
How do I get the working directory of my application during runtime and then add a relative path (from the info.properties file ) to access the bin folder?
Thanks
Tomcat home directory or Catalina directory is stored at the Java System Property environment. If the Java web application is deployed into Tomcat web server, we can get the Tomcat directory with the following command:
System.getProperty("catalina.base");
Here you can move inside Tomcat folder and open bin easily
Try the following code to get the current working directory:
public static String getCWD() {
File file;
int index;
String pathSeparator;
String cwd = null;
file = new File(".");
pathSeparator = File.separator;
index = file.getAbsolutePath().lastIndexOf(pathSeparator);
try {
cwd = file.getAbsolutePath().substring(0, index);
} catch (StringIndexOutOfBoundsException e) {
System.err.println("Caught Exception: " + e.getMessage() + "\n");
}
return cwd;
}

Why can't I access a file within my jar unless I'm in the folder with the Jar when I run it?

I recently created an application and successfully jarred this to c:/my/folder/app.jar. It works like a charm in the following case [Startup #1]:
Open cmd
cd to c:/my/folder
java -jar app.jar
But when I do this, it doesn't work [Startup #2]:
Open cmd
cd to c:/my/
java -jar folder/app.jar
Because app.jar contains a .exe-file which I try to run in my application:
final Process p = Runtime.getRuntime().exec("rybka.exe");
It won't work in example 2 because it can't find the file rybka.exe.
Any suggestions?
Something like this is a better way forward. Copy the exe out of the jar to a temp location and run it from there. Your jar will then also be executable via webstart and so on:
InputStream src = MyClass.class.getResource("rybka.exe").openStream();
File exeTempFile = File.createTempFile("rybka", ".exe");
FileOutputStream out = new FileOutputStream(exeTempFile);
byte[] temp = new byte[32768];
int rc;
while((rc = src.read(temp)) > 0)
out.write(temp, 0, rc);
src.close();
out.close();
exeTempFile.deleteOnExit();
Runtime.getRuntime().exec(exeTempFile.toString());
If the jar will always be in that directory you can use a full path /my/folder/rybka.exe. If not, you can use getClass().getProtectionDomain().getCodeSource().getLocation() to find out the location of the jar and prepend that onto rybka.exe.
Try extracting the exe to
System.getProperty("java.io.tmpdir"));
then run it from this location too should work every time.
Paul

Categories

Resources