I have two file.
Hello.java
Index.php
Hello.java
class Hello
{
public static void main(String args[])
{
System.out.println("HelloWorld");
}
}
Index.php
$file="Hello.java";
exec('javac'.$file,$output,$resultCode);
if ($resultCode===0)
{
echo "Result: " . $resultCode . "\n";
}
else
{
echo "fail";
}
It give "Fail" output i want to get "HelloWorld" output on browser.
please help me.
You have not provided a space between your command and arguments.
exec('javac'.$file,$output,$resultCode);
should be
exec('javac '.$file,$output,$resultCode);
This part just completed the compiling then you need another exec statement to completed the execution of the program. As suggested by mthmulders
exec("java -cp . Hello", $output,$resultCode);
Related
I would like to get current app path in the app.
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current config file path is: " + s);
It seems working well, BUT when I use like below.
> pwd
> /usr/local/
> java -jar app/getapppath.jar // executed app inside app folder
> Current config file path is : /usr/local // I want /usr/local/app
I can executed my app after 'cd app', but I want to fix it fundamentally. Any idea of this?
You can use classloader to get that information. Here is a example, which you can adopt to your needs:
package test;
import java.net.URL;
public class a {
public static void main(String[] args) {
URL u = ClassLoader.getSystemResource("test/a.class");
System.out.println(u);
}
}
In my case it works as:
$ cd /tmp
$ java -cp /home/me a
file:/home/me/a.class
$
I have a java program which throws some exception,I tried executing it from shell script and printing 0 on failure and 1 on successful execution of java program.But It also printing the Exception onto console I just want to print exit code only.How to do this ?.Any suggestion are appreciated .
following are my Java program and script files
Test.Java
public class EchoTest {
public static void main (String args[]) {
System.out.println ("scuccess Prasad Bezavada "+(2/0));
}
}
Test.sh(script file)
java Test
if [ $? -eq 0 ]
then echo "1"
else echo "0"
fi
getting the following out put
$sh Test.sh
Exception in thread "main" java.lang.ArithmeticException: / by zero
at EchoTest.main(EchoTest.java:3)
0
$
Expecting output is like below(i.e just want to skip the exception message)
$sh Test.sh
0
$
Try this.
java Test 2> /dev/null
if [ $? -eq 0 ]
then echo "1"
else echo "0"
fi
you have to catch the exceptions. After that, you would be able to output exactly what you want. on your example:
public class EchoTest {
public static void main (String args[]) {
try{
System.out.println ("scuccess Prasad Bezavada "+(2/0));
} catch (Exception e){
// doing nothing is ok for your intended behaviour
}
}
}
First of all, you would like your Java program to return a value (either 1 or 0).
In our case we will consider that if an exception is thrown, 1 will be returned and 0 otherwise. Also, exception will be hid (which is a bad practice. You should always log exceptions at least if you are not willing to show it on screen)
public class EchoTest {
public static void main (String args[]) {
try {
System.out.println ("scuccess Prasad Bezavada "+(2/0));
System.exit(0);
}
catch (Exception e) {
// log your exception here
System.exit(1);
}
}
}
Once this is done then what you will need to work on is on getting java's output code.
java Test
output = $?
# do some logic here..
if [[ $output -eq 0 ]]; then
echo "executed"
else
echo "exception thrown"
fi
Finally, this will indeed return either 1 or 0 depending on execution ignoring exception case, which is what you actually requested.
Everyone of us is familiar with try it yourself online editor of w3schools.com.
We can execute html,css,php,javascript etc. programs in 'try it'.
I have implemented same feature in my project for java.
Program executes using php-javabridge.
When my code is
class generate
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Hi World");
}
}
In output,it displays only:
Hi World
Instead,it should display:
Hello World
Hi World
When my code is
class generate
{
public static void main(String args[])
{
System.out.print("Hello World");
System.out.print("Hi World");
}
}
In output,it displays everything:
Hello WorldHi World
What could be the possible problem behind this?Any guess?
Solution to problem is simple.
My php program is:
require_once("javabridge/java/Java.inc");
exec('javac '.$filename,$output,$resultCode);
echo exec('java -cp . generate');
You need to do following modifications to your program.
ob_start();//solution step-Turn on output buffering
require_once("javabridge/java/Java.inc");
exec('javac '.$filename,$output,$resultCode);//$filename is generate.java,classpath current directory
echo exec('java -cp . generate',$output);//call generate.class and store output in $output
ob_end_clean();//solution step-Clean (erase) the output buffer and turn off output buffering
echo implode(delimiter,$output);//convert $output array to string and display
And finally,you get the desired result.
i em trying to fetch some query from an url and then pass them to a java program for further execution. The problem i am facing is that my php code is calling my java program but is not passing the values.
till now i have worked on these codes,
PHP PROGRAM:
<?php
$phonecode= $_GET['phonecode'];
$keyword= $_GET['keyword'];
$location= $_GET['location'];
exec("C:\Users\Abc\Documents\NetBeansProjects\JavaApplication11\src\javaapplication11\main.java -jar jar/name.jar hello" . $phonecode . ' ' . $keyword . ' ' . $location, $output);
print_r($output);
?>
JAVA PROGRAM:
public class Main
{
public static void main(String args[])
{
try
{
String phonecode = args[];
System.out.println(args[]);
System.out.println(phonecode);// i have only tried to print phonecode for now
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Ok, a couple of issues with the Java code you've posted, here's a working version of what you posted:
class Main
{
public static void main(String[] args)//String[] args, not String args[]
{
if (args.length == 0)
{//check to see if we received arguments
System.out.println("No arguments");
return;
}
if ( args.length < 3)
{//and make sure that there are enough args to continue
System.out.println("To few arguments");
return;
}
try
{//this try-catch block can be left out
String phonecode = args[0];//first arg
String keyword = args[1];//second
String location = args[2];//third
//print out the values
System.out.print("Phonecode: ");
System.out.println(phonecode);
System.out.print("keyword: ");
System.out.println(keyword);
System.out.print("location: ");
System.out.println(location);
}
catch(Exception e)
{
System.out.println(e.getMessage());//get the exception MESSAGE
}
}
}
Now, save that as a .java file, and compile it, it should churn out a Main.class file. I compiled it from the command-line:
javac main.java
I don't have netbeans installed, but I suspect the .class file will be written to a different directory, something like:
C:\Users\Abc\Documents\NetBeansProjects\JavaApplication11\bin\javaapplication11\Main.class
// note the BIN
Then, to execute, you need to run the java command, and pass it the path to this Main.class file, leaving out the .class extension. Thus, we end up with:
java /path/to/Main 123 keywrd loc
Should result in the output:
Phonecode: 123
keyword: keywrd
location: loc
In your PHP code:
exec('java /path/to/Main '.escapeshellarg($phonecode). ' '.escapeshellarg($keyword).' '.escapeshellarg($location), $output, $status);
if ($status === 0)
{//always check exit code, 0 indicates success
var_dump($output);
}
else
exit('Error: java exec failed: '.$status);
There are a couple of other issues, too: like $phonecode = $_GET['phonecode']; doesn't check if that $_GET param exists. If it doesn't your code will emit notices. To fix:
$phonecode = isset($_GET['phonecode']) ? $_GET['phonecode'] : '';
Other niggles include: the backslash is a special char in strings, it is used in escape sequences: \n is a newline char. PHP can deal with the *NIX directory separator /, even on windows. Use that, or escape the backslashes (C:\\Users\\Abc\\ and so on).
A file that only contains PHP code doesn't require the closing ?> tag. In fact: it is recommended you leave it out.
your java code should look like
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
Note String[] args, not String args[]
Also on PHP side in exec you need space between string hello, and variable $phonecode if you want those to be looked as a 2 separate arguments.
I'm trying to control a game server and display it's output in real time. This is what I have so far:
#!/usr/bin/perl -w
use IO::Socket;
use Net::hostent; # for OO version of gethostbyaddr
$PORT = 9000; # pick something not in use
$server = IO::Socket::INET->new( Proto => 'tcp',
LocalPort => $PORT,
Listen => SOMAXCONN,
Reuse => 1);
die "can't setup server" unless $server;
print "[Server $0 accepting clients]\n";
while ($client = $server->accept()) {
$client->autoflush(1);
print $client "Welcome to $0; type help for command list.\n";
$hostinfo = gethostbyaddr($client->peeraddr);
printf "[Connect from %s]\n", $hostinfo->name || $client->peerhost;
print $client "Command? ";
while ( <$client>) {
next unless /\S/; # blank line
if (/quit|exit/i) {
last; }
elsif (/fail|omg/i) {
printf $client "%s\n", scalar localtime; }
elsif (/start/i ) {
if (my $ping_pid = open(JAVA, "screen java -jar craftbukkit-0.0.1-SNAPSHOT.jar |")) {
while (my $ping_output = <JAVA>) {
# Do something with the output, let's say print
print $client $ping_output;
# Kill the C program based on some arbitrary condition (in this case
# the output of the program itself).
}
}
printf $client "I think it started...\n Say status for output\n"; }
elsif (/stop/i ) {
print RSPS "stop";
close(RSPS);
print $client "Should be closed.\n"; }
elsif (/status/i ) {
$output = RSPS;
print $client $output; }
else {
print $client "FAIL\n";
}
} continue {
print $client "Command? ";
}
close $client;
}
It starts the process just fine, the only flaw is that it's not outputting the output of the Java process to the socket (It is displaying the output in the terminal window that Perl was initiated with) I've tried this with ping and it worked just fine, any ideas?
Thanks in advance!
It sounds like the Java code (or maybe it's screen) is printing some output to the standard error stream. Assuming that you don't want to capture it separately, some easy fixes are:
Suppress it:
open(JAVA, "screen java -jar craftbukkit-0.0.1-SNAPSHOT.jar 2>/dev/null |")
Capture it in the standard output stream:
open(JAVA, "screen java -jar craftbukkit-0.0.1-SNAPSHOT.jar 2>&1 |")
screen redirects the output to the "screen". Get rid of the screen in the command.