Has someone embedd a simple script language in a JAVA application.
My purpose is todivide the application in 3 part
Part 1) Hardcoded in java the application read from 2 source(Db, file,scocket,..., mind) and store 2 object.
Part2) The application in conjuction with the embedded scripting language make a a decisionedit the object and at the end call an exposed function eg: if the 2 object has the same namecall the function do nthing, if the name of the second object the next step isto call the update function.
Part3) the java application do the job that has been called.
Now i'm doing this with an application that use a JAR file with a lot of interface. So if i wont to expose only the step 2 ican give the specification of interface. The idea is to copy JDBC. Anyway it's difficult for tecnichan to write and compile in pere JAVA and create a JAR. So i'm looking for a good replacement. But it has to simple but powerful as jar replacement. I'm not trying to compile evrything in a single JAR i need them well separated.
THANKS
There is the Java Scripting API for this purpose.
Groovy for example provides an implementation to load, compile, interface, and execute Groovy scripts from within your Java application.
You can also try MVEL http://mvel.codehaus.org/
MVEL is a powerful expression language for Java-based applications.
It is fast anf easy to use.
expression language = java as scripting language
Related
I want to create a function at run time in JAVA.
I want some thing like java Scripts equivalent of:
new Function([arg1[, arg2[, ...argN]],] functionBody)
So the user can specify function as a string, and thereafter can invoke it using the required parameters.
There are quite a few things in that direction in Java, but the closest would probably be the Java Scripting API which "is used to embed scripts in your Java applications".
NB if the code you want to execute is provided by the user, make sure you execute it in a sandboxed environment, otherwise you'll be hurt.
I am working on a project, which will introduce programmable computers to Minecraft, similar to ComputerCraft, except using Python as opposed to lua.
I am aware of Jython, so thought it would be suitable to check if I could use that for my project, however couldn't find enough information (on their website and with a few searches) to be certain.
I am aware of the topic discussing using Java from within Jython, however this is not how I want my project to work. Those that have used Computercraft, know that you have only the libraries that Computercraft provides you, whereas the topic linked above has full access to.. well everything. In my use case, everything isn't possible. I also don't want from pycomputers.api import Colors, I want the 'colors' api to be used like colors.red.
Hopefully the above is possible, within Jython, if not I would love to know another Python interpreter (that can be used from Java), to make my project with.
According to the docs if you want to embed the Jython into a java application then you have to invoke it with the PythonInterpreter class. It's pretty strait forward from there, just note that the overloads that provide a filename argument are for the name of the main executable file (this information is normally available through the sys module in regular old CPython).
Now in order to expose bindings in java to python (say to control the minecraft world), we need to add the jar files to sys.path as is described here, and if you want to control the sys.path value from within java then use
PythonInterpreter pi = new PythonInterpreter();
pi.getSystemState().path.append(new PyString("path/to/java/modules.jar"));
Note that the packages inside the jar files cannot be organized in the reverse url style. Instead, follow the instructions on package naming. Particularly make note of Naming Python Modules and Packages and if you follow the guidelines in Proper Python Naming then you will get the results you desire.
Finally we execute the code with
String source = ...;
pi.execute(pi.compile(source));
I'm a java programmer. I use bash scripts a lot for text processing.
Utilities like grep,sed,awk,tr,wc,find, along with piping between commands gives such a powerful combination.
However bash programming lacks portability, testability and the more elegant programming constructs that exist in Java. It also makes it harder to integrate into our other Java products.
I was wondering if anyone knows of any Java text processing libraries out there which might offer what I'm looking for.
It would be so cool to be able to write:
Text.createFromFile("blah.txt).grep("-v","ERROR.*").sed("s/ERROR/blah/g").awk("print $1").writeTo("output.txt")
This might be pie-in-in-the-sky stuff. But thought I'd put the question out there anyway.
Unix4j implements some basic unix commands, mainly focussing on text-processing (with support for piping between commands): http://www.unix4j.org
Example (Ben's example, but without awk as this is not currently supported):
Unix4j.fromStrings("1:here is no error", "2:ERRORS everywhere", "3:another ERROR", "4:nothing").toFile("blah.txt");
Unix4j.fromFile("blah.txt").grep(Grep.Options.v, "ERROR.*").sed("s/ERROR/blah/g").toFile("output.txt");
Unix4j.fromFile("output.txt").toStdOut();
>>>
1:here is no error
4:nothing
Note:
the author of the question is involved in the unix4j project
Believe it or not, but I used embedded Ant for many of those tasks.
Update
Ant has Java api's that allow it to be called from Java projects. This is embedded mode. This is a reference to And Api 1.6.1. Distribution should include docs as well.
To use it, you would create new task object, set appropriate parameters and execute it just as you would in build.xml but via Java Api. Than you can run your task.
Something like
ReplaceRegExp regexp = new ReplaceRegExp();
regexp.setMatch("bla");
regexp.setFile(new File("inputFile"));
regexp.execute();
You may need to set up some other stuff as well.
Not sure if it solves your problem, but Ant has a lot of code to do things. Just search through docs.
We want to design a simple domain specific language for writing test scripts to automatically test a XML-based interface of one of our applications. A sample test would be:
Get an input XML file from network shared folder or subversion repository
Import the XML file using the interface
Check if the import result message was successfull
Export the XML corresponding to the object that was just imported using the interface and check if it correct.
If the domain specific language can be declarative and its statements look as close as my sentences in the sample above as possible, it will be awesome because people won't necessarily have to be programmers to understand/write/maintain the tests. Something like:
newObject = GET FILE "http://svn/repos/template1.xml"
reponseMessage = IMPORT newObject
newObjectID = GET PROPERTY '/object/id/' FROM responseMessage
(..)
But then I'm not sure how to implement a simple parser for that languange in Java. Back in school, 10 years ago, I coded a language parser using Lex and Yacc for the C language. Maybe an approach would be to use some equivalent for Java?
Or, I could give up the idea of having a declarative language and choose an XML-based language instead, which would possibly be easier to create a parser for? What approach would you recommend?
You could try JavaCC or Antlr for creating a parser for your domain specific language. If the editors of that file are not programmers, I would prefer this approach over XML.
Take a look at Xtext - it will take a grammar definition and generate a parser as well as a fully-featured eclipse editor pluging with syntax highlighting and -checking.
ANTLR should suffice
ANTLR, ANother Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages. ANTLR provides excellent support for tree construction, tree walking, translation, error recovery, and error reporting.
Look at Antlr library. You'll have to use EBNF grammatic to describe your language and then use Antlr to make java classes from your grammatic.
Have a look at how Cucumber defines its test cases:
(source: cukes.info)
http://cukes.info/ - can run in JRuby.
Or, I could give up the idea of having a declarative language and
choose an XML-based language instead,
which would possibly be easier to
create a parser for? What approach
would you recommend?
This could be easily done using XML to describe your test scenarios.
< GETFILE object="newObject" file="http://svn/repos/template1.xml"/ >
Since your example of syntax is quite simple, it should also be possible to simply use StringTokenizer to tokenize and parse these kind of scripts.
If you want to introduce more complex expressions or control structures you probably better choose ANTLR
I realize this thread is 3 years old but still feel prompted to offer my take on it. The questioner asked if Java could be used for a DSL to look as closely as possible like
Get an input XML file from network shared folder or subversion repository
Import the XML file using the interface
Check if the import result message was successfull
Export the XML corresponding to the object that was just imported
using the interface and check if it correct.
The answer is yes it can be done, and has been done for similar needs. Many years ago I built a Java DSL framework that - with simple customization - could allow the following syntax to be used for compilable, runnable code:
file InputFile
message Message
get InputFile from http://<....>
import Message from InputFile
if validate Message export Message
else
begin
! Signal an error
end
In the above, the keywords file, message, get, import, validate and export are all custom keywords, each one requiring two simple classes of less than a page of code to implement their compiler and runtime functions. As each piece of functionality is completed it is dropped into the framework, where it is immediately available to do its job.
Note that this is just one possible form; the exact syntax can be freely chosen by the implementor. The system is effectively a DIY high-level assembly language, using pre-written Java classes to perform all the functional blocks, both for compiling and for the runtime. The framework defines where these bits of functionality have to be placed, and provides the necessary abstract classes and interfaces to be implemented.
The system meets the primary need of clarity, where non-programmers can easily see what's happening. Changes can be made quickly and run immediately as compilation is almost instantaneous.
Complete (open) source code is available on request. There's a generic Java version and also one for Android.
I wanted to use JET (Java Emitter Templates)
in my Netbeans projects, but had to find out that JET
heavily depends on Eclipse libraries.
Is there something similar to JET, but as a standalone project?
Something which is open source and well maintained?
Futhermore, is "code generation" the common term for such tools?
If you are using Maven, you can use JET templates with the maven-jet-plugin.
This seems to be the source code. And here the documentation.
It is not actively maintained but works pretty well and follows the JET spec.
I've used it with templates and skeletons.
It's self contained, doesn't depend on Eclipse, and doesn't introduce any transitive dependencies to your project.
Indeed JET is very tied with Eclipse.
If you want to generate code without Eclipse you should use another solution.
You can choose another template engine like Velocity (https://velocity.apache.org/) or FreeMarker (https://freemarker.apache.org/).
Or you can choose a code generator working by itself independently of any IDE.
For example "Telosys Command Line Interface" : http://www.telosys.org/
From what I know, JET is something like JSP, no?
Java Emitter Templates are very similar to Java Server Pages (JSPs). Both JETs and JSPs use the same syntax, and are compiled to Java behind the scenes. Both are used to separate the responsibility for rendering pages from the model and controller. Both accept objects passed into them as an input argument, both allow inserting string values within code ("expressions"), and allow direct use of Java code to perform loops, declare variable, or perform logical flows ("scriptlets"). Both are good ways of representing the structure of a generated object (web page, Java class, or file) while supporting customization of the details.
JETs differ from JSPs in a few key ways. In a JET, the structure of the markup may be changed to support generating code in different languages. Typically the input to a JET will be a configuration file and not user input (though there is nothing forbidding this). And also typically, JET processing will take place only once for a given workflow. These are not technical limitations, and you may find uses for JETs which are quite different...
ibm.com
Here are a few links to get you started on JSP, if that sounds like what you need:
sun.com
netbeans.org
Look for "template engine" for these types of tools.
A couple you might want to look at:
Apache Velocity (http://velocity.apache.org/)
StringTemplate (http://stringtemplate.org/)
I ended up using ERB (Ruby's template engine).
Works great in Netbeans!
I define custom ant task which generates source files by calling ERB (whose results are placed inside a non-versioned special directory).
The ant task is overriding Netbeans' "-pre-compile" task.