using java annotations in rythm template engine - rythm

In the quest of getting JUnit tests to be part of how we use Ryhtm we came up with the code snippet below. All went well until we added
#Test
which obviously is a java annotation and uses the # marker as a syntax element that is also being used by Rythm. How can the desired effect be achieved to get the #annotation? To simply escape the ## does not work it gives a
Syntax error on token "#", delete this token
error. So How can a Java # annotation be used ?
I have also filed this as a bug report at https://github.com/greenlaw110/Rythm/issues/285
#// This is a rythm template
#import static org.junit.Assert.*
#import org.junit.Test.*
#def static {
class TestMe {
String name;
#Test
public void testMe() {
name="test";
assertEquals("test",name);
}
}
}
#{
TestMe testme=new TestMe();
testme.name="testme";
}
The TestMe has the name #(testme.name)

If you use a fully qualifying annotation it should work:
#org.junit.Test

#import org.junit.Test.* in your template code should be #import org.junit.Test, note that .* needs to be take off

Related

Getting error in eclipse for spock's #Shared annotation

As a try, I created a simple groovy class in eclipse and wrote a simple spock test method.
I created one object with #Shared annotation and eclipse is complaining like:
Multiple markers at this line
- Groovy:unable to resolve class Shared , unable to find class
for annotation
- Groovy:class Shared is not an annotation in #Shared
I googled a little but did not find the solution. Does anyone know why this error is occurring? Below is the sample code:
class SimpleSpockTestExampleSpec extends Specification {
#Shared
MyObject obj;
def "length of Spock's and his friends' names"()
{
expect:"Replaces when-then block"
name.size() == length
where:
name << ["zzzzz","xxx","yyy"]
length << [5,6,7]
}
}
Pease ignore the line numbers in the image.
It seems that you haven't imported appropriate package. Do you have the following statement in the code:
import spock.lang.Shared
?

Scala - unbound wildcard exception (Play Framework 2.3 Template)

I am using Play Framework 2.3 I am using the scala template engine to create my views and Java elsewhere.
My model extends an abstract parameterised object like so... (pseudo code)
Abstract object:
public abstract class MyObject<T> {
// various bits
public class MyInnerObject {
// more stuff
}
}
Model object (singleton)
public class SomeModel extends MyObject<SomeBean> {
public static SomeModel getInstance() {
if (instance == null)
instance = new SomeModel();
return instance;
}
// more bits
}
I then pass the model to the view from another view helper:
#MyHelper(SomeModel.getInstance())
MyHelper scala view template:
#*******************************************
* My helper
*******************************************#
#(myObj: some.namespace.MyObject[_])
#import some.namespace.MyObject
#doSomething(myInnerObj: MyObject[_]#MyInnerObject) = {
#* do some stuff *#
}
#for(myInnerObj <- myObj.getInnerObjects()) {
#doSomething(myInnerObj)
}
However I get an error on the line #doSomething(myInnerObj: MyObject[_]#MyInnerObject) stating
unbound wildcard exception
I am not sure the correct Scala syntax to avoid this error I had naively assumed that I could use the _ to specify arbitrary tyope but it won't let me do this.
What is the correct syntax?
UPDATE 1
Changing the method definition to:
#doSomething[T](myInnerObj: MyObject[T]#MyInnerObject)
gives further errors:
no type parameters for method doSomething: (myInnerObj:[T]#MyInnerObject)play.twirl.api.HtmlFormat.Appendable exist so that it can be applied to arguments (myObj.MyInnerObject)
--- because ---
argument expression's type is not compatible with formal parameter type;
found : myObj.MyInnerObject
required: MyObject[?T]#MyInnerObject
It would seem that the Twirl templating engine does not support this syntax currently, although I'm not 100% sure.
I can solve the problem by removing the doSomething method completely...
#*******************************************
* My helper
*******************************************#
#(myObj: some.namespace.MyObject[_])
#import some.namespace.MyObject
#for(myInnerObj <- myObj.getInnerObjects()) {
<div>#myInnerObj.getSomeProperty()</div>
}
But I am bout 10% happy with the solution... It works at least but it feels very restricting that I cannot delegate to methods to help keep my code maintainable. By the look of the comments the problem seems to be a limitation in Twirl, not allowing type arguments for functions in views.
Note: I have accepted this answer as it removes the original problem of the exception however this is only because the solution I want doesn't exist... yet.

Extending a class in another file

I have some TypeScript code that is being generated by a tool. I'd like to extend this class in another file. As of 0.9.1.1, what's the best way to go about this?
I thought maybe I could staple my additional functions onto the prototype, but this is giving various errors (which change depending what mood the compiler is in).
For example:
Foo.ts (generated by a tool)
module MyModule {
export class Dog { }
}
Bar.ts
module MyModule {
function bark(): string {return 'woof';}
Dog.prototype.bark = bark;
}
You cannot split a class definition between multiple files in TypeScript. However typescript understands how JavaScript works and will let you write idomatic JavaScript classes just fine:
module MyModule {
export function Dog(){};
}
module MyModule {
function bark(): string {return 'woof';}
Dog.prototype.bark = bark;
}
Try it online
One way around this is to use inheritance:
class BigDog extends Dog{
bark(){}
}
I have encountered your problem as well before, but I had some deeper problems. You can see from basarat's example, that simple functions can be added as an extension to the prototype, but when it comes to static functions, or other static values you might want to extend your (presumably third party) class, then the TSC will warn you, that there is no such method defined on the class statically.
My workaround was the following little hack:
module MyModule {
export function Dog(){};
}
// in the other file
if (typeof MyModule !== 'undefined'){
Cast<any>(MyModule.Dog).Create = ()=>{return new Dog();};
}
// where Cast is a hack, for TS to forcefully cast types :)
Cast<T>(element:any):T{ return element; }
This should cast MyModule.Dog, to an any object, therefore allowing attachment of any kinds of properties, functions.

Working with Java; HashMaps and ArrayLists not compiling in Eclipse or BlueJay

I am having trouble getting HashMaps and ArrayLists to work correctly on my computer. I have tried using my own code, and copying samples from textbooks and online to make sure my syntax is correct, but thus far neither Eclipse or BlueJay will let me "add" or "put" things into these data structures. Here are some examples of what I have done.
package issues;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;
public class StructureIssues {
/*
* HashMap Attempt
*/
HashMap<Integer, String> numberNames = new HashMap<Integer, String>();
numberNames.put(new Integer(1), "hi");// here, I have syntax errors asking me to
// delete the (), and I have misplaced
// constructs on the dot.
//When the above line didn't work, I tried creating the objects
//outside of the parameter list...
Integer one = new Integer(1);
String myString = "hi";
numberNames.put(one, myString); //here it just complains about the parenthesis
//similar results for <String,String> and generic
/*
* ArrayList Attempt
*/
ArrayList<String> tryStrings = new ArrayList<String>();
String tryOne = "one";
tryStrings.add(tryOne);//Syntax error on tryOne; variable declarator ID expected
//also, syntax error on the dot; misplaced constructs
ArrayList<Integer> tryInts = new ArrayList<Integer>();
tryInts.add(new Integer(4));//Syntax error on add; expected "=" after it.
//Below, I have copied two lines from Big Java by Horstmann.
//The results are the same as my first String ArrayList attempt.
ArrayList<String> friends = new ArrayList<String>();
friends.add("Cindy");
}
I did find one or two questions similar to mine, and I followed their advice, but so far I've had no luck. Here is what I have tried to far to figure this out:
-Reinstalled my JDK package several times, trying both 64 and 32-bit
-Reinstalled eclipse Indigo several times, trying both 64 and 32-bit
-In eclipse, gone to Project->Properties->Java Compiler. My java compliance is JavaSE-1.7
-In eclipse, gone to Window->Preferences->InstalledJREs. I have jre7 with Standard VM.
-I have tried right clicking on my jre System Library in my packages, and changing to JavaSE-1.6, 1.7, and checking the default workspace box for jre7.
-I have tried similar code in BlueJay because I wanted to try another IDE to see if it was eclipse or my computer. I received: "identifier" expected. It highlighted tryStrings.add("one");
Am I doing something silly here? Any advice you guys could offer would be greatly appreciated. Thank you for your time.
Your code is not in any method. You may declare and initialize fields in a class. But using these fields should be done in methods (or constructors).
Problem is that the code is not in any method. Where you are calling the put method is the area where you declare the variables. see this modified code. I made the variable static so that it can be called from the main method.
public class StructureIssues {
/*
* HashMap Attempt
*/
static HashMap<Integer, String> numberNames = new HashMap<Integer, String>();
public static void main(String args[]) {
numberNames.put(new Integer(1), "hi");// here, I have syntax errors
// asking me to
// delete the (), and I have
// misplaced
// constructs on the dot.
// When the above line didn't work, I tried creating the objects
// outside of the parameter list...
Integer one = new Integer(1);
String myString = "hi";
numberNames.put(one, myString); // here it just complains about the
// parenthesis
// similar results for <String,String>
// and generic
/*
* ArrayList Attempt
*/
ArrayList<String> tryStrings = new ArrayList<String>();
String tryOne = "one";
tryStrings.add(tryOne);// Syntax error on tryOne; variable declarator ID
// expected
// also, syntax error on the dot; misplaced
// constructs
ArrayList<Integer> tryInts = new ArrayList<Integer>();
tryInts.add(new Integer(4));// Syntax error on add; expected "=" after
// it.
// Below, I have copied two lines from Big Java by Horstmann.
// The results are the same as my first String ArrayList attempt.
ArrayList<String> friends = new ArrayList<String>();
friends.add("Cindy");
}
}

Eclipse getter/setter format

Does anyone know of an Eclipse plug-in or method to get Eclipse to generate getter/setters on one line like this:
public String getAbc() { return abc; }
Instead of
public String getAbc() {
return abc;
}
I'm on Eclipse v. 3.2.2.
Thanks.
I don't know how to make Eclipse generate them in the format you want, but you could do a search/replace using these regular expressions after the methods are generated:
Find:
(?m)((?:public |private |protected )?[\w$]+) (get|set|is)([\w$]+)\(([\w$]+(?:\[\])? [\w$]+)?\) \{\s+(return [\w$]+;|this.[\w$]+ = [\w$]+;)\s+\}
Replace by:
$1 $2$3($4) { $5 }
This expression will transform the generated getters and setters to be one line. Don't worry about running it with a mixture of transformed and newly generated methods; it will work just fine.
I think matching generics is important as well, so the correct regexp is:
(?m)((?:public |private |protected )?[\w\<\>$]+) (get|set|is)([\w$]+)\(([\w\<\>$]+ [\w$]+)?\) \{\s+(return [\w$]+;|this.[\w$]+ = [\w$]+;)\s+\}
As a variation of the regexp replacement approach, the following reformats the whitespace so that setters are followed by a blank line, but getters are not.
Find:
(\s(?:get|is|set)\w+\([^)]*\))\s*\{\s*(?:([^=;}]+;)\s*\}\s*(\R)|([^=;}]+=[^=;}]+;)\s*\}\s*(\R))
Replace by:
$1 { $2$4 } \R$5
Results in:
int getTotal() { return total; }
void setTotal(int total) { this.total = total; }
List<String> getList() { return list; }
void setList(List<String> list) { this.list = list; }
Map.Entry<String, Integer> getEntry() { return entry; }
void setEntry(Map.Entry<String, Integer> entry) { this.entry = entry; }
It's a minor aesthetic thing, but I figured that if you're looking for an answer to this question, then you're probably (almost) as anal as me ;-)
I know my regexp conditions are not as strict as those of #Hosam, but I haven't experienced any "false positive" replacements.
Java code formatting in Eclipse does not differentiate between getters/setters and any other methods in a class. So this cannot be done by built-in eclipse formatting.
You will need either to:
run a search/replace with the aforementioned regex
get en external plugin like PMD or CheckStyle and enforce a regex rule based on previous option
You can use fast code plug-in to generate this kind of getter setters. The details are given here : http://fast-code.sourceforge.net/documentation.htm#create-new-field.
I wanted to post as a comment to the designated answer, but I don't seem to be able to.
I modified Hosam Aly's answer to work with generic and inner types of the form:
List<X>
and
Map.Entry
The revised regular expression search string is:
(?m)((?:public |private |protected )?[\w\.\<\>$]+) (get|set|is)([\w$]+)\(([\w\.\<\>$]+ [\w$]+)?\) \{\s+(return [\w\.\<\>$]+;|this.[\w$]+ = [\w$]+;)\s+\}
This regular expression allows for angle brackets and a dot in the type.
For example:
public List<String> getStringList()
and
public void setStringList(List<String> list)
and
public Map.Entry getEntry ()
And the replace string is the same as before:
$1 $2$3($4) { $5 }