Java Play 2 - Function as a parameter in scala - java

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">

Related

Kotlin extension with parameters

On an Android project with both Kotlin and java, I want to use the Kotlin functions substringBeforeLast(delimiter) and substringAfterLast(delimiter) in some java files.
So i thought of using extensions. I did the following which works,
fun String.getStringAfterLast(): String{
return this.substringAfterLast(".")
}
however i was thinking of passing the delimiter as a parameter, but it gives me an error when trying to use in java "remove 2nd argument..."
fun String.getStringBeforeLast(delimiter: String): String{
return this.substringBeforeLast(delimiter)
}
Is the approach correct ? Can it be done ?
Your approach to this problem is correct and it should work. For example, with this Kotlin code:
fun String.getStringBeforeLast(delimiter: String): String{
return this.substringBeforeLast(delimiter)
}
You should be able to invoke the function from Java like this:
ExtensionKt.getStringBeforeLast(str, ",");
If it didn't work then I guess there had to be some small mistake, like for example: you added delimiter param to getStringBeforeLast() function, but mistakenely tried to invoke getStringAfterLast() function from Java.
Also, you can always invoke functions of Kotlin stdlib directly from Java. Just note that substringBeforeLast()/substringAfterLast() actually receive one additional, optional parameter and you need to provide it from Java, making the code a little more verbose:
StringsKt.substringBeforeLast(str, ",", str);

Play framework: is there a way to avoid strange form helper syntax?

I am trying to build a form with Play Framework 2, the usual syntax is:
#helper.form(action = routes.Application.submit, 'id -> "myForm") {
}
Note that the single quotation mark is before id is opened and never closed.
Is there another syntax that I can use to do the same thing?
The 'id is a Symbol.
You could use the Symbol("sym") syntax if you don't like this one, but it is not standard.
scala> 'symbol == Symbol("symbol")
res0: Boolean = true
You could work around it with an implicit conversion. This will require using a scala source file, though (seems like you're using java, but you can mix them).
app/libs/SymbolImplicits.scala
package example.libs
object SymbolImplicits {
implicit def string2Symbol[A](s: (String, A)): (Symbol, A) = (Symbol(s._1), s._2)
}
Then in your view you would #import example.libs.SymbolImplicits._, so you can then do:
#helper.form(action = routes.Application.submit, "id" -> "myForm") {
}
"id" -> "myForm" is then implicitly converted to 'id -> "myForm".
To avoid using that import in every view, you could also add this line to build.sbt (or in Build.scala project properties) instead:
TwirlKeys.templateImports += "example.libs.SymbolImplicits._"
No, that's required syntax for Scala's Symbol as pointed in other answer, anyway except that it looks weird for it's perfectly valid and there's no reason to fight with it.

Scala REST API call to a Java REST with FormParams

I wanted to know if you guys do know if it is possible in Scala to make a call to a Java REST client function which takes #FormParam params.
If my function in the Java client is this :
#Path("registerEmail")
#POST
public RegisterEmailResult doRegisterEmail(#FormParam("email") final String email, #FormParam("password") String password/* Some other params */) {
How can I pass some #FormParam params in Scala ? I tried this :
def registerEmail(registerEmail: RegisterEmail): Future[Boolean] =
post(
url("/theUrl/registerEmail"),
new Gson().toJson(registerEmail)
).map {
case data => true
}.recover {
case _ => false
}
The RegisterEmail model has all the field of the parameters of the Java function.
Did I miss something ? Otherwise I will have to do the Java function again with like #QueryParams, it seems to be maybe a better way.
It is simpler to understand your code if you include part of your imports as well. The url (which I assume is Play's play.api.libs.ws.WS.url(...)) can be utilised like this to pass form data:
WS.url("/theUrl/registerEmail")
.post(Map("email" -> Seq("someone#somewhere.com"),
"password" -> Seq("secretish")))
See https://www.playframework.com/documentation/2.3.x/ScalaWS for more details (specifically search for "Submitting form data")

Java Parser for JavaScript: List all Functions/Variables

I am planning to implement a JavaScript parser in java. I know that there are several ways to do it. There are view frameworks/engines/parsers which could help to do it right, like:
ANTLR 3/4:
it seems like there is only a js grammer for v3
Mozilla Rhino: atm i can parse variable names on initital (top-) namespace. but i am not able to parse nested scopes e.g. object members.. hm..
Nashorn: maybe i should give it a try..?
Maybe:
closure-compiler: IMHO this is very nice. but not for "non-google" js-code :) e.g. you have to apply several coding conventions to your javascript sources to get it working properly..
maybe it is possible to adapt Packer to do it? Is there a Java implementation of Packer???
There is EcmaScript 5.1 related to this article. it seems to be very comfortable. But this is not exactly what I´am looking for.. And still no java :)
My question is:
What could/would be the best way to parse JavaScript for:
(object-)function names
(object-)member names e.g. variables
Is it even possible to do it?
What would be your approach? For me it is not essential to parse ALL special markups of JavaScript.. The important factor would be to parse function/variables in a consistent context for the typical markups like this:
// Avoid `console` errors in browsers that lack a console.
function Object() {
var method;
var noop = function() {
};
var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
};
var obj = new Object();
var test = "Hello World";
The parse should be able to deliver this information:
Node: Object
Node: Object.method
Node: Object.noop
Node: Object.length
Node: Object.console
Node: Object
Node: obj
Node: test
There is no direct need of any determination if the node is a function/variable.

Convert javascript template to pure javascript

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/

Categories

Resources