By using java i want to convert javascript template (i try to make ) to pure javascript
Here is example :
Input
<? function test()
{
return "Just a message";
}
if("a"=="b")
{
?>
<h1><?=test()?></h1>
<?
}
?>
<?=test()?>
</head></html>
output pure js example
out.print("<html><head>");
function test()
{
return "Just a message";
}
out.print("<h1>");
if("a"=="b")
{
out.print(test());
}
out.print("</h1>");
out.print("</head></html>");
I need a function to convert javascript template to pure javascript an eval it later .
p/s
a example using javascript function here http://ejohn.org/blog/javascript-micro-templating/
but i'm not sure it work perfectly when given conplex template
You can match every pair. And each pair is javascript and the rest is outputted using out.print(...). A simple regex can do the job.
Or you can look at template engines which are fully tested and supported, such as: http://mustache.github.io/
Related
I've been looking for a Javascript parser on Java that can capture and list all Javascript functions, for example
function beforeSave('Test', request, response) {
response.body = entity.foo;
if (request.query.isExist('Test', 'foo', entity.foo)) {
response.error();
} else {
response.success();
}
}
function afterSave('Test', request, response) {
response.body = 'done';
response.success();
}
Is there a Javascript parser library for Java that would be able to list all Functions from a given source text as well as get the function bodies as needed.
I believe java.util.regex is the right tool for the job.
With that you can search for keywords in strings. Example for getting the body of the function:
import java.util.regex.*;
Pattern p1 = Pattern.compile("function', \"([^\"]*)\"");
Matcher m1 = p1.matcher(String);
System.out.println(String.format("function=%s",m1.group(1)));
To see more about this go to the question here.
I´m not a Java-expert by any means so check out the other question and the documentation of the library for more information.
I have problems to write reusable code in scala.
If i have something like
#helper.form(action = routes.Guides.addComment(category,title)) {
Is there a way to replace it with a variable?
pseudo code
#(func : Function)
#helper.form(action = func) {
Edit:
Oh.... now it's kinda obvious. The function itself should return a string , so I guess i can just say something like this
#(func :String)
..
.
return ok (form.render(routes.Guides.test()))
Testing it now
May I suggest an alternative? Use Call directly.
#(route: Call)
#helper.form(action = route) {
...
}
In Scala, you could even pass only a part of the route and fill the rest from the controller (very useful when you're using pagination).
figured it out.
with
routes.Guides.test().url
you get the url and then you can use it as a parameter
for example
#guidesComment((routes.Guides.addComment(ug.category,ug.title)).url)
guidesComment looks like this
#(func: String)
Then use it like this
<form action="#func" method="POST">
guys! I need to create some sort of meta language which I could embed in XML and then parse with Java. For example:
<code>
[if value1>value2 then "Hello, Bob!" else "Hello, Jack"]
</code>
or
<code>
[if value1+2>value2 return true]
</code>
I need to implement conditional statements,arithmetics.
Any suggestions where should I start looking?
Java has a built-in JavaScript interpreter:
ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("JavaScript");
jsEngine.put("value1", 8);
jsEngine.put("value2", 9);
String script = "if(value1 + 2 > value2) {'Foo'} else {'Bar'}";
final Object result = jsEngine.eval(script);
System.out.println(result); //yields "Foo" String
Of course you are free to both load the script from anywhere you need and to provide it with any context (value and value2 in this example) you want.
See also Scripting for the Java Platform article.
A user here, Bart Kiers. Wrote a tutorial about creating a simple language in Java with ANTLR.
Java has a scripting API that you could use for this. Lookup the API documentation of the package javax.script.
You could include code in for example JavaScript in the code element, and execute that using the scripting API.
If you really want to develop your own language, start off with the interpreter pattern. If you just want to leverage somebody else's language in your Java code, look to integration ala JSP style embedded languages.
It is almost certain that a homemade language would suck, especially in the long run, so don't roll something on your own.
There are several jsp-like frameworks available, maybe one of those would do the trick:
JSTL/JSP EL (Expression Language) in a non JSP (standalone) context
This is very similar to this other SO question about arrays.
If I evaluate:
y = {a: 1, b: 2, "momomomo": function() { return "hi"; }, zz: "wham"}
in a Javascript script instantiated via JSR223 (ScriptingEngine), I get a NativeObject of some sort (I see this in Eclipse's debugger) and have no idea how to access its properties. Furthermore I don't even know which .jar file, if any, I need to add to my build path to be able to work with the class in question, and if I find an approach that works in Rhino Javascript, it is useless for Jython.
Seems like JSR223 should have included language-agnostic access methods to ScriptingEngine to provide the ability to wrap a returned object as a List<Object> for arrays or a Map<String, Object> for associative arrays.
Any suggestions?
I too am trying to embed different scripting languages with more features than jsr223 or bsf. For that i have had to define my own interfaces and implement thse around each different scripting engine.
One feature i wanted was the ability to pass a Function (java interface with a single method) to my scripting engine and have it just work when passed parameters. Each of my embedded scripting engines has a layer where i wrap/unwrap from/to java values from the scripting environment.
I would suggest the best way to solve the problem is for your wrapper around the scripting engine to provide a getValue( String name ) and have it fix up javascript arrays convertoing them to java Lists. Naturally the setValue(String, Object) would check if the value is a List and convert it back to a js array and so on. Its tedious :()
Convert it to a java object and return it. You can then work with the java object as you would normally.
The following is an example conversion function
function convertToJava(o) {
var rval;
if (Array.isArray(o)) {
rval = new java.util.ArrayList();
for (var key in o) {
rval.add(convertToJava(o[key]));
}
}
else if (typeof o === 'object') {
rval = new java.util.HashMap();
for (var key in o) {
rval.put(key, convertToJava(o[key]));
}
}
else if (typeof o === 'function') {
// skip
}
else if (typeof o === 'undefined') {
// skip
}
else {
rval = o;
}
return rval;
}
How do I use Rhino return a string from Java to Javascript, all I get is org.mozilla.javascript.JavaNativeObject when I use
var jsString = new java.lang.String("test");
inside my js file.
Is this the right way to do it?
var jsString = String(new java.lang.String("test"));
The goal is to have a Java method to return the String object instead of creating it on the fly like above.
In general, you would call Context.javaToJS which converts a Java object to its closest representation in Javascript. However, for String objects, that function returns the string itself without needing to wrap it. So if you're always returning a string, you don't need to do anything special.
Although in most cases the returned Java String type can be used just like the JS String type within the JS code, it does not have the same methods!
In particular I found it cannot be used in a JS object passed to 'stringify()' as it does not have the toJSON() method.
The only solution I found is to explicitly do the addition of "" in the JS, to convert the Java String to a JS String. I found no way to code the java method to return a good JS string directly... (as Context.javaToJS() doesn't convert a Java String)
Eg:
var jstr = MyJavaObj.methodReturningAString();
JSON.stringify({ "toto":jstr}); // Fails
JSON.stringify({ "toto": ""+jstr}); // OK
Turn off the wrapping of Primitives and then the value returned in your expression will be a JS string:
Context cx = Context.enter();
cx.getWrapFactory().setJavaPrimitiveWrap(false);
For me this is a Rhino bug. The s+"" trick inside JavaScript works, but here's a quick patch to fix it Java-side - after this line in NativeJavaMethod.call()
Object retval = meth.invoke(javaObject, args);
add this check to convert it to a native JavaScript string (ie typeof returns "string" not "object")
if (retval instanceof String) {
return NativeJavaObject.coerceTypeImpl(String.class, retval);
}
This is important otherwise s.replace() calls the Java version so is wrong for eg "h e l l o".replace(" ", "")
https://github.com/mozilla/rhino/issues/638