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.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm very new to the coding space and was wondering if someone could help me start a .jar file. BTW This is using C#. My issue is this wont run the file. I got it to work with .txt files though, so I'm just a bit confused.
private void button1_Click(object sender, EventArgs e)
{
Process.Start("java" , "server.jar");
}
In short, for the answer, add -jar right before the JAR file name.
The accepted answer is not 100% correct for several reasons: it does not recognize whitespace-delimited and whitespace-containing arguments, and may mess up with quote characters that must be passed (therefore properly escaped) to the delegated Java app. In short, do not use Arguments if the string is not known to be a constant (having spaces will require manual escaping anyway), but merely prefer ArgumentList that handles each argument properly.
Here is an example Java application to deal with command line arguments:
public final class SayHello {
private SayHello() {}
public static void main(final String... names) {
for ( final String name : names ) {
System.out.printf("hello %s!\n", name);
}
}
}
The manifest for the JAR file:
Manifest-Version: 1.0
Main-Class: SayHello
Making a JAR file out of it is simple:
javac SayHello.java
jar cfm SayHello.jar MANIFEST.MF SayHello.class
Example of use:
java -jar SayHello.jar 'John Doe' Anonymous
that gives:
hello John Doe!
hello Anonymous!
Now, an example C# program that passes the -jar argument to the java process so that it recognizes the given file as a JAR file and demonstrates what can go wrong with Arguments if passed as a string.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
using System.Diagnostics;
public static class SayHello {
public static void Main() {
// interprets 3 names: John, Doe, Anonymous (wrong)
RunJavaJarBadly1("SayHello.jar", "John Doe Anonymous");
// interprets 1 name: John Doe Anonymous (wrong)
RunJavaJarBadly2("SayHello.jar", "John Doe Anonymous");
// interprets 2 names: John Doe, Anonymous (correct, but bad: requires the first name to be quoted at the call-site)
RunJavaJarBadly1("SayHello.jar", "\"John Doe\" Anonymous");
// interprets 1 name: "John Doe" Anonymous (wrong: interprets everything as a single name)
RunJavaJarBadly2("SayHello.jar", "\"John Doe\" Anonymous");
// interprets 2 names, no ambiguous call, each name is recognized properly, does not require quoting at the call site
RunJavaJar("SayHello.jar", "John Doe", "Anonymous");
}
private static void RunJavaJarBadly1(string jarPath, string argumentsFortheJarFile) {
var process = new Process();
process.StartInfo.FileName = "java";
process.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
process.Start();
process.WaitForExit();
}
private static void RunJavaJarBadly2(string jarPath, string jarArgs) {
var process = new Process();
process.StartInfo = new ProcessStartInfo("java") {
ArgumentList = { "-jar", jarPath, jarArgs }
};
process.Start();
process.WaitForExit();
}
private static void RunJavaJar(string jarPath, params string[] jarArgs) {
var process = new Process();
process.StartInfo = new ProcessStartInfo("java") {
ArgumentList = { "-jar", jarPath }
};
foreach ( var jarArg in jarArgs ) {
process.StartInfo.ArgumentList.Add(jarArg);
}
process.Start();
process.WaitForExit();
}
}
The code above produces (no legend in the output, but added for explanation):
hello John! \_ #1/1: incorrect, the space is ignored
hello Doe! /
hello Anonymous! -- #1/2: correct, no spaces in-between
hello John Doe Anonymous! -- #2/1|2: incorrect
hello John Doe! -- #3/1: correct, but requires the call site to escape the argument
hello Anonymous! -- #3/2: correct, no need to escape, thanks to no spaces
hello "John Doe" Anonymous! -- #4/1|2: incorrect, similar to #2/1|2
hello John Doe! -- #5/1: correct, let the framework do its job
hello Anonymous! -- #5/2: correct, let the framework do its job
In order to get it to work, the file name needs to be "java" and contain the file location in the arguments.
System.Diagnostics.Process clientProcess = new Process();
clientProcess.StartInfo.FileName = "java";
clientProcess.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;
Taken from similar question here
Optional way using ArgumentList:
System.Diagnostics.Process clientProcess = new Process();
var info = new System.Diagnostics.ProcessStartInfo("java.exe")
{
ArgumentList = {
"-jar",
jarPath,
jarArgs
}
};
info.FileName = "java";
clientProcess.StartInfo = info;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;
Here are some options for you to check out.
Also similar question with a working result: here
Paraphrasing from links:
In order to get it to work, the file name needs to be "java" and contain the file location in the arguments.
System.Diagnostics.Process clientProcess = new Process();
clientProcess.StartInfo.FileName = "java";
clientProcess.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;
i'm trying to make a plugin, it must block a specified commands setted by config. i've maked this but it doesn't block any command.
Code:
#EventHandler(priority = EventPriority.HIGHEST)
public void onPreprocess(PlayerCommandPreprocessEvent event)
{
Player player = event.getPlayer();
String command = event.getMessage();
List<String> bCmds = this.plugin.cfg.getStringList("blocked-commands");
for (String bCmd : bCmds)
{
if(command.equalsIgnoreCase(bCmd))
{
event.setCancelled(true);
}
}
}
Config:
blocked-commands:
- /pl
- /op
- /sp
- /gravityblock
PS: I've tried to use:
String command = event.getMessage().subString(1);
Thanks for Help... :)
Registered events? implemented listner?
Also your code will not work with additional arguments in the command.
If it contains spaces, split it with " " and get the first element to just get the command
if (cmd.contains(" ")) cmd = cmd.split(" ")[0];
As stated by Bukkit's wiiki, the priorities are called in the following order:
EventPriority.LOWEST
EventPriority.LOW
EventPriority.NORMAL
EventPriority.HIGH
EventPriority.HIGHEST
EventPriority.MONITOR
Maybe you could try to use the Lowest priority, so the event gets cancelled before the command is handled.
I also believe that the command might have arguments, so it might not be equal to the string provided, you should also try
String command = event.getMessage();
if (command.toLowerCase().startsWith("/command") ) {
//cancel
}
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.
I am writing a java program that runs a loop and keeps asking the user for input. The program then does a bunch of things with the string, and asks for another string and repeats.
The issue is that many strings are very similar, so i would like to populate the prompt with the input from the last time in the loop. For instance: If the user enters a value as follows:
Enter the SKU Number: APE-6603/A
... Then the next time it asks for an SKU, it will wait till the user presses enter as normal, but be ready with the last value before the user even types anything:
Enter the SKU Number: APE-6603/A
... And the user can make simple changes very fast like replace the /A with /B and press enter! If the string that holds the user input is called "lookFor", is there a way to populate the prompt with this value in Java? It would be VERY useful!
Thanks!
After discussing this idea with a few people, it seems that what i want is not possible. The way of input is too simple to allow something like this.
My only possible solutions involve not running this from my IDE. I can either elect to use my application, or change the application into a GUI based applet. Running from the console will open up the "Press up" option, as suggested by rchirino, and using a GUI would let the value entered sit there for editing later.
If anyone is looking to do what i posted above, the answer is "Java cant do it!". Sorry. :)
You might want to try something like this:
public String promptandgetWithShowDefault(String prompt, String supplied) {
String prmpt = prompt + " (press Enter for \"" + supplied + "\"):";
String tmpch = null;
System.out.print(prmpt);
tmpch = scanner.nextLine().trim();
if (tmpch == null || tmpch.equals("")) {
return supplied;
} else {
return tmpch;
}
}
If the goal is to get a simple binar answer from the user like:
Would you like to do that? ( y / n ) y
then the empty string returned by the user, in the answer from Dmv, will do the trick, except that when the user types "n" or attempts to delete the trailing "y", it won't disappear, so it would then be clearer to write the prompt like:
Would you like to do that? ( [ y ] / n )
But when the goal is to get a long string, like the original question or a file path for instance, that the user can edit to correct a typo or not to overwrite previous file .... then you definitely need something else which doesn't seem to be available in Java.
Well do it in C then!!! with the help of libreadline...
it's probably possible, easier and more portable to do the same trick in Python, but I have no idea how to code in Python.
Here is a simple Java MRE to illustrate it:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
public class Main
{
public static void main(String[] args)
{
String path = System.getProperty("user.home") + File.separatorChar + "Documents";
File file = null;
do {
path = askForString("Enter the filepath to open:", path );
if ( ( path == null) || ( path.isBlank())) break;
file = new File( path );
} while ( ! file.exists() );
System.out.println("Openning " + path + "....");
// ......
}
public static String askForString( String message, String defaultString)
{
String response = null;
System.out.println( message);
// any extra String in cmd[] will be added in readline history
String[] cmd = { "/path/to/executable/ask4stringWdefault", defaultString};
try
{
ProcessBuilder pb = new ProcessBuilder(cmd);
// Make sure the subprocess can print on console and capture keyboard events
pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
BufferedReader stderrBuffer = new BufferedReader(new InputStreamReader(p.getErrorStream()));
int retcode= p.waitFor();
if ( retcode != 0)
{
System.err.println("The process terminated with error code: " + retcode + "\n" + stderrBuffer.readLine());
return null;
}
response = stderrBuffer.readLine();
} catch( Exception e) {
e.printStackTrace();
}
return response;
}
}
To build the executable "ask4stringWdefault" you need first to get the GNU Readline Library utility and compile it, ideally cross-compile for any platform Java supports, to get a static library that you will link while compiling ( or cross-compiling ) the following C script:
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
const char *defstr;
int prefill(const char *txt, int i);
int main(int argc, const char * argv[])
{
if ( argc < 2)
{
fprintf(stderr, "You must provide a default value\n");
return -1;
} else if ( argc > 2) {
// * optional extra values can be passed to populate history * //
if ( argc > 255) argc = 255;
for ( unsigned char i=0; i < argc; i++)
{
add_history(argv[i]);
}
}
defstr = argv[1];
char *cbuffer;
rl_startup_hook = prefill;
if ((cbuffer = readline(NULL)) == NULL) /* if the user sends EOF, readline will return NULL */
return 1;
fprintf( stderr, "%s\n", cbuffer);
free(cbuffer);
return 0;
}
int prefill(const char *t, int i)
{
rl_insert_text(defstr);
return 0;
}
The result is printed on stderr as it is the only stream that Java can keep track of, stdout and stdin being under the control of the executable subprocess itself.
It works fine on a Mac with arm64 architecture, using Eclipse you can't actually edit the default provided, any character typed at the prompt will be append to default string, but just hitting return will send unchanged default value back, which can be enough for basic testing.
I think I understand what you want to do, but it's rather simple. If your program is a console application (command-line), which I'll assume, then you just need to press the UP key to populate the prompt with the last typed characters.
If you're working with GUI elements then you can check the API documentation for the particular class of object you're using and check out it's fields.
Hope this helps!
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);