Implement tryit feature of w3schools.com for java program - java

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.

Related

Why wont this .jar file run when I try to start it on C#? [closed]

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;

How to print only exit code ,when java program gives exception(running java program from shellscropt)?

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.

Passing query from php to java

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.

how can compile and execute java file in php?

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

Unable to call an instance method from Clojure.

I'm completely new to Java and clojure. But with previous experience in common lisp, I thought I would give clojure a try. I'm unable to figure out few very basic things.
This is the actual Java code.
import syntaxtree.*;
import visitor.*;
public class Main {
public static void main(String [] args) {
try {
Node root = new MicroJavaParser(System.in).Goal();
System.out.println("Program parsed successfully");
}
catch (ParseException e) {
System.out.println(e.toString());
}
}
}
When I run this code, the outcome is as expected.
└──╼ java Main < ../input/Factorial.java
Program parsed successfully
In Clojure I tried this :
(ns clj-assign2.core)
(defn -main
[]
(def root
(.Goal
(MicroJavaParser. (. System in))))
(println "Successfully parsed"))
But when this code is run, the following exception is raised :
└──╼ lein run < ../assign2/input/Factorial.java
Exception in thread "main" java.lang.IllegalArgumentException: No matching field found: Goal for class MicroJavaParser
at clojure.lang.Reflector.getInstanceField(Reflector.java:271)
at clojure.lang.Reflector.invokeNoArgInstanceMember(Reflector.java:300)
at clj_assign2.core$_main.invoke(core.clj:7)
< --- snipped --- >
What am I doing wrong here?
Maybe you are missing an import statement in your clojure program?

Categories