I am writing a simple web upload script.
The goal is to upload a file using php, and then calling a java program to process this file.
I have done the work for uploading the file, but I cannot get a java program to be successfully run from within the php script.
I have tried exec(), shell_exec(), and system() with no results.
For the command, I have used "java Test", "java < directory >/Test", "/usr/bin/java < directory >/Test", I have even set up the application as a jar file with no results. The actual line of code I have used is:
echo shell_exec("java Test");
Usually there is no output. However, if I have just shell_exec("java"), then the last line of the help from java ("show splash screen with specified image") is displayed, which shows that the command has been executed. If I use, for example, shell_exec("whoami") I get "nobody" returned, which is correct. The only thing the java file does is create a file so that I can see that the application has been successfully run (the application runs successfully if I run it on the command line). I have set the permissions for the java file to 777 to rule out any possibility of permission errors. I have been struggling with this for a while trying all sorts of options with no results - the file is never created (the file is created with an absolute path so it's not being created and I just can't find the file). Does anyone have any ideas?
Thanks.
I have been struggling with this for a
while trying all sorts of options with
no results - the file is never created
(the file is created with an absolute
path so it's not being created and I
just can't find the file). Does anyone
have any ideas?
What I think the problem is. Apache runs as "nobody" group??(apache user??) which will execute the java script which will try to create a file on disc somewhere. I assume it does not have permission to write to that location. you should chown that folder so that apache user can write to that folder.
==
First off I would like to point out to you that calling exec() from a script could really blow up your server. I would advice you to use something like redis(see below) instead.
==
Second I think I know what the problem is. You should first try to run the simple example below which worked fine for me.
==
First be sure permission are set right. Because apache runs as nobody(most of the times).
I tried this simple test myself on ubuntu with php installed from repo.
test.java
class test {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
test.php
echo exec('java test');
Ran test.php
$ php test.php
Hello World!
==
Or you could try 1 of the following solutions(which would even be a better solution):
Write your java program as a webservice for example on top of atmosphere-spade-server(simple/embedded jar). This could be written insanely fast. But on high load this will not be best option I guess. Still I think this will be more than fast enough for you probably. Even this way it will be much faster as executing it, because you won't have the overhead running JVM. Could blow up your server, not as fast as exec()
Do a blocking pop/push from a redis(*nix) list structure. This will be pretty easy to write on *nux because there are client libraries for both java/php. The speed will best I guess because redis is written in C. I use redis myself.
Use a JMS like for example activemq. Also pretty easy to write because good library support. I have not used a JMS myself. I use redis solution. The speed I guess would be a little less then with redis solution.
I dont realy know, but i came a cross PHP-JAVA bridge maybe it can help
http://php-java-bridge.sourceforge.net/pjb/
Update:
I tested this with Jasper Reports, and it is working really nice. It will allow you to Extend Java classes with PHP or just use Java class lik it was PHP.
use java\lang\String as JString;
require_once("javabridge/java/Java.inc");
class String extends JString {
function toString () {
return "hello " . parent::toString();
}
}
$str = new String("Java");
echo $str->toString();
or
$temp = new Java('java.sql.Timestamp');
$javaObject = $temp->valueOf('2007-12-31 0:0:0');
$params = new Java("java.util.HashMap");
$params->put("text", "This is a test string");
$params->put("date",$javaObject);
More examples: http://php-java-bridge.sourceforge.net/pjb/FAQ.html
It's possible it has to do with the path that the exec is defaulting to. You may need to explicitly define your classpath with an absolute path to your .class or jar files when calling java.
<?php
$PATH="C:\Program Files\Java\jdk1.7.0_09\bin";
echo exec("javac theNameOfYourJavaProgram.java 2>&1");//shows # of errors
echo "<br />";
echo exec("java theNameOfYourJavaProgram 2>&1");//this line executes it
echo "<br />";
echo shell_exec("javac theNameOfYourJavaProgram.java 2>&1 ");//compiles it
?>
Related
I have been trying to solve this issue for 5 hours
when I try to execute the below code in the terminal it works fine. However, when I use the same code in flask application I am getting this error (sh: 1: java: not found)
import os
environ = os.environ.copy()
os.putenv("JAVA_HOME", "/usr/lib/jvm/java-14-oracle/bin/java")
os.environ["PATH"] += os.pathsep + ":/usr/lib/jvm/java-14-oracle/bin/java/bin"
os.system("java -jar /home/../myproject/application/graphseg1.jar /home/../myproject/application/entire_text /home/.../myproject/application/segmented_text 0.40 2")
the above code works fine within the terminal as shown below:
However, when I try to run the same code within flask application, I am getting the following error:
I am using Ubuntu 18.04, nginx,supervisor,gunicorn3
supervisor configration file:
[program:flask_app]
directory=/home/****/myproject
environment=PATH=/tmp/enter/envs/myenvi/bin
command=/tmp/enter/envs/myenvi/bin/gunicorn application:app --timeout 9223372036
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stderr_logfile=/var/log/flask_app/flask_app.err.log
stdout_logfile=/var/log/flask_app/flask_app.out.log
You should probably using Subprocess instead. It provides pipes for STDIN, STOUT, STDERR and the option for a full shell with some inherent security warnings.
See: https://docs.python.org/2/library/subprocess.html#module-subprocess
Seems like your path is not setup properly, like omajd said can you print it?
See also: Problems adding path and calling external program from Python
I'm just learning Java and Jsch, and I can get it to run other commands but not cd. The error code returned by the SSHManager sendCommand function is not null, but some unreadable string that is different every time (maybe that means it is null not that familiar with inner workings of Java).
Any idea why not? Similar question here JSch - Why doesn't CD work? but unanswered.
I won't copy and paste the whole SSHManager class here - useful answer with complete code here that I'm trying to follow. Run a command over SSH with JSch
Sample code below:
import SSH.SSHManager;
public class src
{
int ERROR = 0;
public static void main(String[] args)
{
String username = "debian";
String password = "temppwd";
String ipadd = "192.168.7.2";
SSHManager ssh = new SSHManager(username, password, ipadd, "");
ssh.connect();
String out = "";
//this doesn't work, printing output as bytes to show how weird it is
out = ssh.sendCommand("cd Desktop");
System.out.println(out.getBytes());
//some other test commands
out = ssh.sendCommand("mkdir test");
System.out.println(out);
out = ssh.sendCommand("ls");
System.out.println(out);
ssh.sendCommand("logout");
}
}
Output from the Eclipse Console (bin and Desktop are already there in root directory):
[B#b065c63
bin
Desktop
test
Each command executed over SSH "exec" channel (what is behind SSHManager.sendCommand) is executed in its own shell. So the commands have no effect on each other.
To execute multiple commands in the same shell, just use an appropriate syntax of your server shell. Most *nix shells use semicolon or double-ampersand (with a different semantics).
In your case, the double-ampersand would be more appropriate.
cd Desktop && mkdir test && ls
See also Multiple commands using JSch.
Though, if your want to read commands output, you will have problem distinguishing, where output of one commands ends and output of the following commands starts. Let alone if you wanted to check command exit code.
Then it's better to execute each command in its own "exec" channel in a way that does not require a context. In your case that means using full paths:
mkdir Desktop/test
ls Desktop
See also How to perform multiple operations with JSch.
Also as you were going to use file manipulation only, you actually should not execute shell commands at all. Use the standard SSH API for file manipulation, the SFTP.
The question has kind of an answer, in the comments. Every command in sendCommand uses it's own 'pipe', so it disconnects and starts over in each one.
A quick solution would be to send multiple commands in one one sendCommand, such as:
out = ssh.sendCommand("cd Desktop; mkdir test; ls; logout");
But the correct way is to use a session, such as https://stackoverflow.com/a/9269234/290036
I answered a similar question Using java jcabi SSH client (or other) to execute several commands in shell
My open-source API Maverick Synergy has a high-level API to execute multiple commands within a shell. Its currently designed for and works well with bash-type shells.
Sorry if this question has already been answered some where, I have not had any luck turning up a solution. This is my first SO post, if information is missing/unclear, or the formatting sucks, let me know, I will update the post.
I am using TestNG version 6.13.1 (also tested with 7.0.0-beta1). I am running this command (not the full command, the class path is massive, and there are multiple -D options)
java -cp <classpath stuff...> -DappiumPort=30000 org.testng.TestNG -usedefaultlisteners false /Users/.../adbservice/test-results/3567/test_config/Test_Suite_testT13googleMaps.xml
expecting that testNG will recognize the first argument as a switch, and turn the default listeners off. This is based on reading Turning off test-output in TestNG and http://testng.org/doc/documentation-main.html#testng-xml, and other less relevant documents.
What actually happens is testNG appears to treat all the arguments as if they are file paths, and I get a very helpful error message
ProcessResults(exitCode=0, output=java.io.FileNotFoundException: /Users/.../adbservice/-usedefaultlisteners false testng.xml (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:196)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:139)
at org.testng.xml.Parser.parse(Parser.java:148)
at org.testng.xml.Parser.parse(Parser.java:233)
at org.testng.TestNG.parseSuite(TestNG.java:290)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:334)
at org.testng.TestNG.initializeEverything(TestNG.java:974)
at org.testng.TestNG.run(TestNG.java:988)
at org.testng.TestNG.privateMain(TestNG.java:1330)
at org.testng.TestNG.main(TestNG.java:1299)
The command itself is issued from Java, using a wrapper around a ProcessExecutor. The code looks like
new ProcessExecutor()
.command(cmd)
.readOutput(true)
.timeout(waitForTimeMs, TimeUnit.MILLISECONDS)
.execute();
I can get the same error if I capture the command input and paste it into the shell, so it seems that it is not a problem with the java code itself, but I figured I would include that information for completeness.
My question is, how can I make this call to testNG work using the command line arguments? There seem to be few alternatives because I have packaged tests which are executed in a shell process.
Edit
Since this is such a common case, I am convinced there is something wrong on my side. I tested that theory out by creating a really simple java project with a smoke test, and then ran it with
java -cp .:testng-6.13.1.jar:jcommander-1.72.jar:build/libs/test-1.0-SNAPSHOT.jar org.testng.TestNG -usedefaultlisteners false testng.xml
which worked exactly as described in the documentation. Therefore I think there is something going on with the input to java and how it is being processed that is causing the error with testNG.
Edit 2
Did some further investigation on my side, eventually I tried the original generated java command with the parameters ( -usedefaultlisteners false) on the command line, and lo and behold it worked, or at least, it did some stuff before bombing out, instead of complaining about the parameters being invalid file paths, which was my original result when running on the command line. Maybe I had the wrong directory or some such the first time, but this suggests that it is a problem with handling the command with this ProcessExecutor.
Edit 3
Paydirt. It turns out the ProcessExecutor library does not handle command line input with spaces as one might expect, so for example,
Lists.newArrayList(
"java", "-cp", ".:", "org.testng.TestNG", "-enabledefaultlisteners false", "testng.xml"
)
will error, but
Lists.newArrayList(
"java", "-cp", ".:", "org.testng.TestNG", "-enabledefaultlisteners", "false", "testng.xml"
)
works. It seems like that should be documented in the ProcessExecutor library docs.
I use the following code in a views.py
def berkeleyParser(infile,outfile):
cmd="java -Xmx1024m -jar nlptools/BerkeleyParser/berkeleyParser-1.7.jar -gr nlptools/BerkeleyParser/chn_sm5.gr < "+infile+" > "+outfile
os.system(cmd)
and then call this function to use berkeley parser.
I think the file path is ok, because the jar can successfully create the output file.
Meanwhile, I use a independent .py code to run the code above (with path modified), and got correct result in output file.
So, I don't know what's wrong with it.
I have a vbs file which do some validation and I would like to run it from java. I have followed the standard code to run, but no results coming out , even the no exception is thrown by eclipse. When I run the vbs file alone, it runs perfectly fine. I don't know what I am missing if don't see any exception. My code is like that:
String strVBpath = "C:\\Users\\Nur\\Documents\\tr.vbs";
Runtime.getRuntime().exec("cscript " + strVBpath );
could you please let me know what possibly went wrong. by the way if I run another vbs file which contains only a msgbox "Hello World" ,, it runs good from java , but why my tr.vbs is not running.
No, its a straight forward code, the code read some file and write the results back to Excel. I was trying to run it from eclipse. No error no results.