Execute Java code in Java [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert String to code in Java
Dynamic code execution on Java
I have a String containing : "for(int i=0 ; i<5 ; i++){System.out.println(\"*\");}"
Can I execute the code in this String in Java?

Since Java 6, you can compile and run a Java compilation unit defined as a String or a File using standard APIs in the SDK (a compilation unit is basically everything that goes inside a .java file - package, imports, classes/interfaces/enumerations), take a look at this example. You can't run an arbitrary Java snippet like the one in your question, though.
If at all possible, it'd be a better idea to embed a different scripting language that allows you to run snippets of code from a Java program - for example, JavaScript, Groovy, MVEL, BeanShell, etc.

If you turn it into a full-blown source file, you can feed it to the java compiler programmatically, but last time I checked that was only available if you had the java SDK installed on your machine; it was not available on machines with the client distribution of Java. Of course, this may have changed since then. Look at package com.sun.tools.javac and you will find the java compiler API there.

Maybe you can run this as Groovy:
http://groovy.codehaus.org/Embedding+Groovy

There isn't a Java Core API function for doing this, but you can call javac either by using Runtime.exec or using some "unsafe" classes from com.sun.tools.javac Here's an example:
http://juixe.com/techknow/index.php/2006/12/12/invoke-javac-at-runtime/

I don't think you can execute a String containing a java code.
But it is worth a try if you can save that as a java source file and try to use ProcessBuilder class to execute.
Never tried it and not sure if it is best way to do it. So use it with caution :)
Good Luck!
Also found a similar post: Runtime class in java

No, you can not execute this code in your program.

Related

Sanitize database Input [duplicate]

This question already has answers here:
How to prevent code injection attacks in PHP?
(8 answers)
Closed 6 years ago.
I have a form data which recieved java code from user and store it in the database.
So how do I sanitize the input to make sure that it is indeed java code?
what do you want to achiveve with that, you want to save java code to database?, well if you want to do something like that then you need regular expressions i think, thats the first thing it comes to my head
This sounds somewhat dangerous (not the storing of java text code in a DB), but why would such a use case come up. Nevertheless...
If you are not going to be expecting all aspects of the Java language, you may want to look into BeanShell. Beanshell can take java source code and evaluate it without compiling. You can likely "source" the code without executing it. If it passes, then it is java code, if not, then it is not java code. However, Beanshell does not accept all modern syntax and structures of newer Java editions.
One easy way to verify that it is indeed java code is to try to compile it (this of course gets messy if the code requires dependencies). If you do take this route, then make sure you are compiling in a DMZ computer/user (I am not aware of any risks of compiling untrusted code, but there might be).... just don't run the code after you compile it!

How do I embed a Java compiler&runner into a JVM-based program?

I want user to be able to input a snippet of code with a class or function implemented in Java and the program should run this code, without referring to external tools like javac or saving class files to fisk.
In Clojure it is clear, as there is read and eval. Can it be done for a plain Java code, possibly with some third party jar?
The code is expected to be some variables, some loops, some mathematical functions and maybe some calls to the framework that is running it.

LLVM: Cannot get vmjc to work

I'd like to compile Java to Javascript with LLVM like this:
*.java to *.class, via Oracle's javac
*.class to *.bc, via vmkit's vmjc
*.bc to *.html with JS, via emscripten's emcc
The created HTML/JS file (about 170KB large) prints ReferenceError: _StartJnjvmWithoutJIT is not defined in the browser console when opened. Trying to debug this I noticed that the *.bc file (LLVM IR) doesn't even seem to contain my code, i.e. the strings I'm printing are not inside.
What I did:
vmjc -disable-opt -main=MyTest MyTest.class
It prints out, no matter whether I use Java 6 or 7:
WARNING: Class file 'java/lang/VMString' requires Java version 1.7. This JVM only supports Java versions up to 1.6.
It creates a *.bc file anyway. When I convert that to non-binary (*.ll), I get a file where I would have expected my strings that I print to appear, but they don't. A string like MyTest_main does appear there, though:
llvm-dis MyTest.class.bc
So, is this approach viable at all? What does the warning about the Java version mean? Why doesn't my 'hello world' string appear in the *.ll code and is that a problem?
You could shorten the route by using GWT to compile Java directly to JavaScript.
Java and JavaScript are two different languages. Cross-compiling is tricky and mostly leads to clumsy code.
Personally I recommend a manual reimplementation of the core logic in Typescript, because it supports classical OO (object-oriented) development and type safety. Translating the code this way is time consuming, but relatively easy.
Alternatively, OO-style programming in native JavaScript is also possible. But since it lacks type savety, development this way is harder.
http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Compile another java file from java file

Just out of curiosity. Can we compile & run a java file from another java program?
If so, can you send a reference to that knowledge source?
Take a look at Java Compiler Api and this little example.
If you have the java source code already in a file, then you can just call the java compiler. The java compiler is built-in to the JVM libraries as of version 1.6.
The interface is documented here.
Didn't read it thoroughly, but maybe this helps.
If you're using Java 6, the best way to do this is through the javax.tools.JavaCompiler interface.
If you're using an older version of Java, you must call javac directly using Runtime.exec(), then load the class data by subclassing ClassLoader and overriding findClass.
Yes, you can, but you need java compiler and not only java runtime. First you generate your source, save it and then use Dynamic class loading(tutorial http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html)
You can use javac (JDK is needed):
http://www.javaworld.com/javatips/jw-javatip131.html
You can do it by calling the cmd prompt or use the Main class from the Java Code.
I don't know remember well how is it, but I did it a long time ago.

Is there any program like LINQPad for Java?

I've found LINQPad to be extremely useful when answering StackOverflow questions for C# or VB.NET. It allows me to write up some quick code, run it, and (if I want) see a nicely-formatted dump of the results. That way I can be sure that the code I post actually runs. Thus far I haven't seen anything that I can use to achieve the same result with Java. Is there anything like that out there?
I am not looking for something to query data sources; I just want a light-weight IDE. These are the features I'm particularly interested in:
The ability to write and run short snippets of code without establishing a whole project or file structure.
Reporting of compiler and runtime errors in the code when it is run.
The ability to add references to a particular editor instance.
Syntax highlighting and Autocomplete/Intellisense would be a plus.
JPad - A java scratchpad for running snippets
Since I also couldn't find one I've decided to write one. Currently it can:
Run java snippets (no class / imports / public blah... needed).
Contains drivers for MS/MySQL/Postgres.
Output results as HTML tables
It's very rough but I will add to it over time. Feedback is definitely welcome.
This may help : http://www.browxy.com:9000/codeRunner
EDIT: Url seems to have changed to http://www.browxy.com
You can use the Groovy web console ; it's possible to speak java in groovy land.
Java Snippet Runner:
Does something similar to Linqpad (jar file, not just for macs)
http://mac.softpedia.com/get/Development/Java/Java-Snippet-Runner.shtml
Code Runner (Commercial):
for Mac's only, it'll run code snippets in Java, and lots of other languages too (e.g. Objective C)
http://krillapps.com/coderunner/
http://ideone.com is an online service that has the features you want.
I've been using JEdit for a long time, which is a very powerful cross-platform editor, NOT an IDE. It does have plugins to execute Java code right in the editor, and even uses BSH for macros.
I was looking for a "Java LinqPad" also, and i came across :
this
I've been using IntelliJ IDEA and it works really well as a Groovy scratchpad. The Community Edition is free too.
You need to create a new project, but then can add Groovy scripts to it and run them on the fly. Not had any luck with the actual Scratch File functionality though.
Being a Jetbrains editor it's pretty slick too. (Unlike some of the other options)
Nothing beats LinqPad though.

Categories