Pages

Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Sunday, April 5, 2015

Grails 3 Released. Setting up -javaagent

Grails 3 was released just recently and with all the new stuff it looks really-really-really awesome release! (Really hope that Grails will find the new home now). The two key changes for me are 1) moving to Gradle instead of Gant, and 2) building on top of Spring Boot. NOw it looks like it's basically the Gradle project with custom conventions that are derived from Grails 2.x.

For the first time, it feels like Grails is not a toy framework any more :)

What's not that cool (my own very subjective opinion), is the introduction of application.yml. It's almost impossible to modify it without reading the documentation. Even XML version of it (yes!) would have been more practical.

There are many other nice things added - go look for yourself.

Setting up a -javaagent argument for Grails 3

My personal interest with any new framework or server is usually related to the projects I'm working with. Thus, the first thing I wanted to check is how could I set up a -javaagent for Grails 3 application. Turns out, it's not as simple as you would expect.

Thanks to @bsideup, here's the snippet that you'd have to add to build.gradle file to setup a -javaagent argument, given that the agent JAR is located somewhere in file system:

In the example above, xrebel.jar is the agent package that is located somewhere in my file system. One can use the absolute path just fine in there.

Here's the another snippet, with DSL-style:

With this, I can confirm, that XRebel works with Grails 3 :)

Monday, January 19, 2015

Groovy and Grails

The biggest today (19.01.2015) news in the community is probably the announcement regarding Pivotal pulling Groovy/Grails funding. And there are a lot of sad reactions on this in all channels that I have seen.

This might start a panic reaction around Groovy and Grails. IMO, there's nothing to panic about. Groovy and Grails communities are the healthiest and there's a lot of big companies that use Groovy and Grails and who would definitely be willing to sponsor the projects further. I'm pretty sure they all will be in line to get the both projects under their sponsorship just in a few weeks :)

All-in-all, it might even be very good for Groovy since Pivotal didn't seem to leverage Groovy in their ecosystem with the focus on Cloud Foundry offering. So we might even see an acceleration of Groovy/Grails development once the projects get a new sponsor.

Wednesday, August 11, 2010

Having fun with Grails and JRebel

Gails is a fun framework to work with. Recently, I had to figure out how "dynamic" the framework is.

BTW, IntelliJ IDEA Grails support just rocks!

One thing that is definitely useful - to tell Grails not to re-deploy the application after a new change has been introduced. You can do that by adding -Ddisable.auto.recompile=true to VM parameters of your application start script.


By default, controllers and service classes are initialized dynamically by Grails, but with the option above enabled it lets you to skip the re-deploy phase. Re-deploy of the application is required once you change Java classes, which may be included in your Grails application - this will be solved using JRebel as you will see below. Let's see a small example for that.

1) Create a new controller, called ActionController (grails create-controller action), which will delegate its calls to a service, HelloService (grails create-service hello), which will just return a string:



ActionController.groovy


class ActionController {
   def helloService

  def helloAction = {
    render(helloService.serviceMethod(params.name))
  }
}

HelloService.groovy

class HelloService {
  def String serviceMethod(String name) {
    return "hello ${name}!"
  }
}

HelloService is injected to the ActionController by convention. Run the Grails app with grails -Ddisable.auto.recompile=true run-app or from IDE as shown above. ActionController.helloAction is the entry point for our application: 


It tells now "hello Anton!"

Let's add another service to the application. Say, it will be GoodbyeService (grails create-service goodbye):

GoodbyeService.groovy

class GoodbyeService {
  def String serviceMethod(String name) {
    return "bye ${name}!"
  }
}

... and change the ActionController accordingly:

ActionController.groovy

class ActionController {
  def helloService
  def goodbyeService

  def helloAction = {
    render(helloService.serviceMethod(params.name))
  }

  def goodbyeAction = {
    render(goodbyeService.serviceMethod(params.name))
  }
}

So without any restart/redeploy phase, http://localhost:8080/jr-grails/action/goodbyeAction?name=Anton tells me "bye Anton!"

Perfect! I'm productive! :)

Now try another example, including some Java sources from within the application. For instance, we have a DummyController which delegates the calls to Util class instead of a Grails service.


DummyController.groovy


class DummyController {
  def index = {
    render(jr.util.Util.value())
  }
}

Util.java


public class Util {
  public static String value(){
    return "hello";
  }
}

http://localhost:8080/jr-grails/dummy now gives "hello" in response.

The problem is that if you make some changes in the Util class and recompile it, the change will not be visible in the application. To see the changes, you would need to redeploy the application which may require some time once you have a more sophisticated application.

JRebel to the rescue!

JRebel will help you with the issue above. Once you download and install the software, it is possible to start the application from your favorite IDE (via dedicated plug-in) or by adding special parameters to the application start script: -javaagent:"jrebel.jar"

Now if you run the example (see above), and after it is started, try making some changes to the Util class (for instance, change "hello" to "goodbye"). Hit F5 and the corresponding change will be visible now. The console will also display a message - JRebel: Reloading class 'jr.util.Util' - meaning that JRebel has noticed that the class has been altered and you want to use it in your application.

Unfortunately this trick doesn't work for all cases in Grails. For instance, for CRUD functionality in Grails application, if a change is made on a domain class, JRebel will reload the classes, but the change is not propagated further to the view because of some magic that Grails does behind the scenes.  The good news is that JRebel support for Grails is still in progress. Stay tuned! :)

Thursday, June 3, 2010

JAZOON 2010, Day 2

JAZOON 2010 started with the keynote "Total Cost of Ownership and Return on Investment" by Ken Schwaber, co-developer of the scrum process.




The overview of the keynote speech is available at JAZOON website.


For me the day started with Václav Pech's presentation about concurrency - Unleash Your Processor(s). Tremendous! It was so interesting!

Multithreaded programs today work mostly by accident!

Václav talked about jsr166y, asynchronous background tasks, parallel collections, fork/join strategy, friendly deadlocks and many more. He also mentioned a number of libraries that can help implement actors in Java (Jetlang, for instance). He also explained how do the persistent data structures work and why they are trees in nature. Also, Václav is a big contributor to gpars project for groovy, but he didn't talk about it much as there was a dedicated talk to this topic.

The next presentation I attended was about HTML5 WebSockets, which was also very interesting. I think websockets is the thing we were really missing for many cases and therefor had to build some nasty workarounds to make the things work. Peter Lubbers from Kaazing showed some interesting examples how the new technology compares to Comet, and he also used wireshark to make the evidence. Nice presentation overall.

GPars was next on the list of me. Dierk König from Canoo was giving a talk about parallel programming concepts for the JVM in Groovy. Actually it wasn't a presentation but rather one big demo. Unfortunately, Dierk has to give the demo in groovyconsole as the best IDE in the world crashed (probably because of some 3rd-party plug-in?).


After the references from Václav and Dierk groovy was actually blasted by Nikita Ivanov who was giving a talk cloud computing with Scala and GridGain. I absolutely agree with Nikita about the poor performance of current Groovy, but I'd definitely disagree with the claim that Scala is more concise compared to Groovy. Groovy is extendable the same was as Scala and you can hook into AST of Groovy to alter the syntax if you absolutely need it. Nikita was talking so much and so fast I started to worry about the demo he promised, but he managed to build the example live without any copy-pasteing. Unfortunately there were no time left for more advanced things.


Nikita also introduced Scalar which is an internal DSL for Scala to be used for GridGain. What is nice about it is that with one line of code once could describe the expected behavior of GridGain cluster, instead of writing 10 times more Scala code.


...... to be continued ........

Tuesday, July 31, 2007

A Case for Groovy Singleton

In my last post I've written about the new feature in Groovy API, the GroovySystem class. Now I would like to give it a try for the singleton pattern implementation inside the plug-in extension.

Why would I ever want to do that? The singleton class could be used for persisting the state between the same action calls. I wanted to try this solution just because it must be possible to implement the same thing in the different ways. Nothing else.

Here's an example:

def expando = new groovy.util.Expando()

class MySingleton {
String toString() { 'MySingleton: ' + hashCode()}
}

class MySingletonMetaClass extends MetaClassImpl {
private final static INSTANCE = new MySingleton()
MySingletonMetaClass() { super(MySingleton) }
def invokeConstructor(Object[] arguments) { return INSTANCE }
}

def registry = GroovySystem.metaClassRegistry
registry.setMetaClass(MySingleton, new MySingletonMetaClass())

expando.run = {action ->
expando.workbenchWindow.getActivePage().
showView("org.eclipse.soc.yummy.views.ScriptView")
println "hello groovy action: ${action}"
def single = new MySingleton()
println "${single}"
}

I just create a singleton using the GroovySystem and MetaClassImpl, so that when an action delegate gets called, I will have always the same instance of the singleton class.

Unfortunately, I didn't find a way to implement the same in case of different scripts, e.g. if I have two different scripting extensions. Perhaps I will have to provide a single class to the plug-in which could be used just for this purpose.

Monday, July 30, 2007

JSR 223 and Groovy 1.1 Beta 2

In Groovy version 1.1-beta-2 a new class groovy.lang.GroovySystem provides some nice features that I would like to use in my Google Summer of Code project. Namely, this is one way to implement a bundle activator for an eclipse plug-in. Not really an activator, actually, but sort of.

In a scripted bundle, the activator can be just a singleton class, and GroovySystem can be used to create a fancy singleton pattern in Groovy, like it is described at Groovy's homepage.

The problem I faced when I tried to initialize the scripting engine using javax.sript API, was that the engine implementation still thinks that groovy.lang.MetaClass is a class, but it is an interface in the latest version of Groovy.

So the stack trace of this exception was:

Exception in thread "main"
java.lang.IncompatibleClassChangeError:
at com.sun.script.groovy.GroovyScriptEngine
.(GroovyScriptEngine.java:63)
at com.sun.script.groovy.GroovyScriptEngineFactory
.getScriptEngine(GroovyScriptEngineFactory.java:87)
at javax.script.ScriptEngineManager
.getEngineByName(ScriptEngineManager.java:225)

The quickest fix I could do, is to download the scripting engine sources from the website, and comment out the line in GroovyScriptEngine's static initializer. After the recompilation I didn't get the stack trace any more, but I think I have to investigate a bit more, what could be affected by this change.

Sunday, July 8, 2007

Eclipse plug-ins and JSR-223

Recently I was trying to bind the eclipse plug-in world with JSR-223 and Groovy via javax.script API for my GSoC project. Here's how it turned out.

First I need to have a class that deals with all that javax.script stuff: let there be ScriptingExecutor. Its functionality isn't very advanced - it just delegates the calls to the scripting API and maintains several fields for holding the state of the script. STOP! Why would I need to keep track of the state at all? The problem is that not all the scripting languages with the same semantics/features.

Let's see the example: an action facade and a script that implements this action. I'm using the Expando object to create a class with the same methods as for the action: run(IAction action), selectionChanged(IAction action, ISelection selection), dispose(). The reason why i would like to pass the new object back to the plug-in is that when a selection is changes I would like to save the reference for further processing in the run(IAction) method. The script below has a visibility problem and cannot use def selection to save the state.

def selection

def run(action){
println "selection = ${selection}" // this won't work!!!
}

def selection(action, selection){
this.selection = selection
}

The Groovy User Manual says:
Executing this code you get an exception talking about a missing property or field.
The only things the method has access to are:
* the binding,
* attributes defined by the base class, and
* the dynamic properties defined by the MetaClass (explanations for these will follow).
So I decided to use Expando as a base class for saving the state. Simple.

Next, there are 2 options of delegating the plug-in extension to the script object:

  1. Using the invokeMethod/invokeFunction methods of the javax.script.Invocable interfaces. These can be used just for simply calling the functions from the evaluated script. or...

  2. Using getInterface(Class clazz) to create an object that would implement the required interface, of instance IActionDelegate.

I'm not sure which option is really better so I'm using the first one for now.

Next, I should try to implement several facades and scripts for the extensions, so that I could see the common parts and unify them in one. Implementing a facade for every single extension does not seem to be very relevant, perhaps the getInterface(Class clazz) method will help to skip that... Or I will need some sort of Proxy solution to skip all the facades.

Also I'm referencing Eclipse Monkey project as an inspiration. The reason is that for smoothing the script development a set of predefined variables could be very handy, so the user could use them out of the box. And that is what Eclipse Monkey does: it exposes some internal object into the script context so that a script contributor could use them.

Monday, December 18, 2006

Groovy from SQL and templates

Groovy is a real fun! Get some data from database and put it to XML - must be quick-n-dirty :)
Let the table be:
-- Apache Derby ij script
connect 'jdbc:derby:../../myderby;create=true;user=test;password=test';
create table test(
name varchar(20),
age integer,
gender char(1)
);
insert into test values ('John Doe', 55, 'M');
insert into test values ('Diana Smith', 34, 'F');
insert into test values ('Foo Bar', 21, 'M');
disconnect;
exit;
... and the template.txt:
<person>
<name>${name}</name>
<age>${age}</age>
<gender>${gender}</gender>
</person>
.. and now, Groovy rocks! :)
import groovy.sql.Sql
import groovy.text.Template
import groovy.text.SimpleTemplateEngine
import java.io.File

class SQL2XML{
static void main(args) {
def file = new File("template.txt")
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(file)
def sql = Sql.newInstance("jdbc:derby:myderby",
"test", "test",
"org.apache.derby.jdbc.EmbeddedDriver")
sql.eachRow("SELECT * FROM TEST") {
def binding = ["name":"${it.name}",
"age":"${it.age}",
"gender":"${it.gender}"]
def result = template.make(binding)
println result
}
}
}

It seems to me that the dynamic features might be useful for adding customizations to the end-user application.

Disqus for Code Impossible