Has Freemarker something similar to toolbox.xml-file of Velocity? - struts

I have a Struts 1 application which works with Velocity as a template language. I shall replace Velocity with Freemarker, and am looking for something similar to 'toolbox.xml'-File from VelocityViewServlet. (there you can map names to Java Classes and, using these names it is possible to access methods and variables of various Java class in the Velocity template).
Does someone know, what is possible with Freemarker instead? So far I have found only information about the form beans...would be glad if someone can help....

For the utility functions and macros that are View-related (not Model-related), the standard practice is to implement them in FreeMarker and put them into one or more templates and #import (or #include) them. It's also possible to pull in TemplateDirectiveModel-s and TemplateMethodModelEx-es (these are similar to macros and function, but they are implemented in Java) into the template that you will #import/#inlcude as <#assign foo = 'com.example.Foo'?new()>.
As of calling plain static Java methods, you may use the ObjectWrapper's getStaticModels() (assuming it's a BeansWrapper subclass) and then get the required methods as TemplateMethodModelEx-es with staticModels.get("com.example.MyStatics"). Now that you have them, you can put them into the data-model (Velocity context) in the Controller, or pick methods from them in an #import-ed template, etc. Of course, you can also put POJO objects into the data-model so you can call their non-static methods.
The third method, which is not much different from putting things into the data-model is using "shared variables", which are variables (possibly including TemplateMethodModelEx-es and TemplateDirectiveModel-s) defined on the Configuration level.

Related

Reusing Java classes with procedural-style code?

There's a solid chance I'm misusing classes here which is why I need your help.
I've started developing with Java EE and one of the problems I am facing is I have a process which I have organised in a class, call it: "SendEmail.java".
Now let's say I have two other classes called "Thunderalert.java" and "FloodAlert.java" which will use all the methods that SendEmails.java has within it.
So I want to know the best way of using the SendEmails methods from each of the other classes.
Should I be creating an instance of SendEmails and accessing each method individually and error checking along the way (what if an exception is thrown?).. It's methods are just procedural code, so it's not really an 'object' as such
Shall I just be using the one method that runs all the other internal ones from within SendMail
Should this SendMail be redesigned as a helper class-type design?
I'm still quite new at Java EE so I'm not sure if there are any options available which I am missing
I think you should have one public method inside SendEmail class.
Btw, I would consider changing its name. I think having method send() when class is called SendEmail is not the best way (not to mention about names like call(), invoke() etc).
This is great article about this problem (The Kingdom of Nouns) in java.
What about something like: new Email(recipient, body).send()?
Or if you want to do it in a service style, I'd call it for example MailService

How to organize Kotlin extension methods

Let's say I have a few extension methods for "MyClass".
My question is, what's the best practice to organize/store these methods?
Should they be simply put into a "MyClassExtensions" Kotlin file?
I have tried to encapsulate these methods within a class, but after importing the class I couldn't seem to figure out how to use/access the extension methods.
Edit:
For clarification, I was not asking for help what to call a file that contains extension methods. I was asking about best practices/approaches to store/organize such methods. Ie. should they be simply put into kotlin files, or should they be encapsulated in a class. I am coming from a Java background, so I'm used to store stuff in classes.
As far as I am concerned, you should put them into a utility file, as you did in Java code base before.
But mention, you no longer need to put them into a class. Top-level functions are the best choice.
You can refer to the kotlin standard library or some open source projects like anko, those would be good examples.
In my case, I put extensions of one class into a file which have the same name of the original file in another package, and use
#JvmMultifileClass
to reduce the number of generated class files.

Is CamelGroovyMethods used as a groovy category?

Apache Camel comes with some relatively nice Groovy extensions so that you, for instance, can use closures with the Java DSL for defining routes.
Most, if not all, of the additional methods providing these extensions seem to be located in the class CamelGroovyMethods with static methods like
public static ProcessorDefinition<?> process(ProcessorDefinition<?> self,
Closure<?> processorLogic){/* implementation */}
How is the actual extension of the Camel java classes realised? Is CamelGroovyMethods used as a category somewhere, and if so, where is use(CamelGroovyMethods) called?
Just a guess, but as they are called extension methods they have probably been defined as such. Look in the jar, you should find a file called org.codehaus.groovy.runtime.ExtensionModule in META-INF/services. Have a look at Creating an extension module. I've used this technique myself and it works great except if you want to provide custom constructors, that requires an alternate mechanism.
...
Yep, found it ExtensionModule file in GitHub. They even provided the dsld file to assist with code completion in Eclipse.

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.

Is it good practice to call module functions directly in VB.NET?

I have a Util module in my VB.NET program that has project-wide methods such as logging and property parsing. The general practice where I work seems to be to call these methods directly without prefixing them with Util. When I was new to VB, it took me a while to figure out where these methods/functions were coming from. As I use my own Util methods now, I can't help thinking that it's a lot clearer and more understandable to add Util. before each method call (you know immediately that it's user-defined but not within the current class, and where to find it), and is hardly even longer. What's the general practice when calling procedures/functions of VB modules? Should we prefix them with the module name or not?
Intellisense (and "Goto Definition") should make it trivial to find where things are located, but I always preface the calls with a better namespace, just for clarity of reading. Then it's clear that it's a custom function, and not something built in or local to the class you're working with.
Maybe there's a subtle difference I'm missing, but I tend to use shared classes instead of modules for any code that's common and self-contained - it just seems easier to keep track of for me, and it would also enforce your rule of prefacing it, since you can't just call it from everywhere without giving a namespace to call it from.
I usually put the complete namespace for a shared function, for readibility.
Call MyNameSpace.Utils.MySharedFunction()
Util is such a generic name.
Example from the .Net framework. You have System.Web.HttpUtility.UrlEncode(...). Usually you refer to this as HttpUtility.UrlEncode since you have an import statement at the top.
The name of the class which has the static utility methods should be readable and explainable. That is good practice. If you have good class names they might just as well reside in a Utils namespace, but the class name should not be Utils.
Put all your logging in a Logger class. All your string handing in a StringUtils class etc. And try to keep the class names as specific as possible, and I'd rather have more classes with fewer functions than the other way around.