Lonnie @ lharbour.net http://www.lharbour.net Ruminations on matters of greater or lesser import. Mostly lesser. Sun, 12 Aug 2018 15:48:05 +0000 en-US hourly 1 https://wordpress.org/?v=5.0.4 JMX Managed Bean Configuration in Grails http://www.lharbour.net/jmx-managed-bean-configuration-grails/ http://www.lharbour.net/jmx-managed-bean-configuration-grails/#respond Sat, 11 Aug 2018 20:01:40 +0000 http://www.lharbour.net/?p=282 I wrote this up at least 16 months ago and never posted it. I was working in Grails 2.x.x at the time, had moved to some other tech for a while and now find myself doing some Grails 3.0.x projects. I am still pretty captivated by the framework although it’s been much more heavily “springified” now. I’ll make some posts on these later experiences soon.

In the mean time…

There are cases that arise in any application where it might be useful to enable JMX to set or query certain properties “live” through the JMX protocol. A common case is the log level of an application. For Java applications, a JMX managed bean can be used with a boolean property to set the log level. We can do this with a Grails application as well.

There is a JMX plugin available in the open source community which automatically configures and exposes various objects as managed beans within the application. This plugin is located here. This plugin works great and is very useful, but by default exposes things including configuration information that you may not wish to expose.

As an alternative, it’s not too terribly hard to configure JMX managed beans as needed without using the plugin, rather by leveraging some mechanisms built into the underlying Spring container. The basic approach to this consists of the following tasks.

  • Create the class you want to expose via JMX and annotate the class with the appropriate Spring JMX support annotations.
  • Perform spring bean registration of the beans you want to expose via JMX.
  • Configure Spring Framework JMX support beans to enable JMX within the application.
  • Register the Spring beans as JMX managed beans within the bootstrap configuration.
  • At this point you will have a JMX managed bean that is accessible via a JMX client.

Below is a sample of a simple class, annotated with the appropriate Spring JMX support annotations.

Code blocks are all #groovylang. This has been tested to work with Grails version 2.2.4.


 package net.lharbour.sample    import org.springframework.jmx.export.annotation.ManagedAttribute  import org.springframework.jmx.export.annotation.ManagedOperation  import org.springframework.jmx.export.annotation.ManagedResource    /*   * This class contains the resource you will manage via a JMX console.   */  @ManagedResource  class JmxApplicationProperty {        private boolean logLevel = false        @ManagedOperation      void setLogLevel(boolean logLevel) {         this.logLevel = logLevel      }        @ManagedAttribute      boolean getLogLevel() {         logLevel      }  }  

Below is a sample of the code you will need to insert for the configuration and initialization of JMX support and your JMX managed bean(s).


 import net.lharbour.sample.JmxApplicationProperty  import org.springframework.jmx.export.MBeanExporter  import org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource  import org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler  import org.springframework.jmx.support.MBeanServerFactoryBean    // Place your Spring DSL code here  beans = {     jmxApplicationProperty(JmxApplicationProperty) {} //this is an example of a basic spring bean with a single property that will be exposed via JMX     //create/find the mbean server     mbeanServer(MBeanServerFactoryBean) {        locateExistingServerIfPossible=true     }       //use annotations for attributes/operations     jmxAttributeSource(AnnotationJmxAttributeSource) { }        assembler(MetadataMBeanInfoAssembler) {        attributeSource=jmxAttributeSource     }       //create an exporter that uses annotations     annotationExporter(MBeanExporter) {        server=mbeanServer        assembler=assembler        beans=[:]     }  }  

Next you will need to set up the Spring AnnotationExporter. This will parse and configure the beans within the spring container that have the Spring JMX annotations.


 import org.codehaus.groovy.grails.commons.ApplicationAttributes  import org.springframework.jmx.export.MBeanExporter    class BootStrap {     def grailsApplication     def init = { servletContext ->
       bootstrapAnnotationJmx(servletContext.getAttribute(ApplicationAttributes.APPLICATION_CONTEXT))     }       def destroy = {     }       private def bootstrapAnnotationJmx(ctx){        //pull out the app name to use as mbean domain       def appName = grailsApplication.metadata['app.name']         //find the beans to expose, currently just a single. There       //may be a way to do this other than by name and possibly as an array.         def exposed = ctx.getBean('jmxApplicationProperty')         //add bean(s) to the annotation exporter       MBeanExporter annotationExporter = ctx.getBean("annotationExporter")       annotationExporter.beans."${appName}:name=jmxApplicationProperty,type=services" = exposed       annotationExporter.unregisterBeans()       annotationExporter.registerBeans()     }  }  
http://www.lharbour.net/jmx-managed-bean-configuration-grails/feed/ 0
Inject Grails Service class into generic Spring Bean http://www.lharbour.net/inject-grails-service-class-generic-spring-bean/ http://www.lharbour.net/inject-grails-service-class-generic-spring-bean/#comments Fri, 24 Jan 2014 02:14:45 +0000 http://www.lharbour.net/?p=256 Having gained some measure of working experience with, and become an advocate of, the Grails framework of late, I thought I’d post some occasional tips that may help others along the way.

To help maintain a clean separation of concerns within your Grails application, you might find it desirable to maintain complex business logic outside of the context of Grails service and controller objects. Grails service objects can support transactions at a per-instance level and are maintained by the Grails application context in a way that make them great for a DAO-style pattern implementation. In fact, I prefer to keep all of my GORM-related interactions isolated to service objects rather than sprinkling them between controllers and services. Still, I believe you should avoid weighting service objects down with with complex business logic and calculations. Instead, traditional Spring Beans can be leveraged to aid comprehension and maintenance.

As within traditional Spring application, Spring Beans in Grails start life as simple POJOs or POGOs. They are added to the $app/src/groovy and $app/src/java folders.

 public MyPlainSpringBean {      def doComplexLogic() {      }  }  

Making a POJO or a POGO a Spring Bean is just a matter of initializing the class instances within the underlying Spring Application context. Do this by editing the beans closure in the $app/conf/spring/resources.groovy file.

 beans = {      myPlainSpringBean(MyPlainSpringBean) {}  }  

Now you can use dependency injection to get a handle to the Spring Bean with your complex logic. Usually, I add these dependencies to service classes but you can also add them to controllers.

 class MyController {        MyPlainSpringBean myPlainSpringBean        def index() {          myPlainSpringBean.doComplexLogic      }  }  

Great so far. But say you’d also like your Spring Bean to access the persistence layer to say, store the results of a calculation? In this case, it may make sense to leverage your Grails service object(s). Grails service objects are essentially just Spring Beans themselves with some additional management performed on behalf of the Grails application container. As we saw, traditional Spring Beans are instantiated in a Grails application by referencing their declarations within the conf/spring/resources.groovy class within the beans block. Now add a reference to the service object.

 class MyPlainSpringBean {      MyGrailsService myGrailsService          def doComplexLogic() {      }  }

Then tell Grails to inject an instance of the service object into your Spring Bean during initialization using the ref keyword. This works because the Grails container initializes the Grails services before instantiating your Spring Beans.

 beans = {      myPlainSpringBean(MyPlainSpringBean) {          myGrailsService = ref('myGrailsService')      }  }

You can now access your persistence layer while still maintaining all of your GORM interaction within the service object tier.

 public MyPlainSpringBean {        MyGrailsService myGrailsService        def doComplexLogic() {          def calculationResults = 1000.00f          myGrailsService.storeCalculations(results)      }  }  
http://www.lharbour.net/inject-grails-service-class-generic-spring-bean/feed/ 2
Moving on to new challenges! http://www.lharbour.net/moving-on-to-new-challenges/ http://www.lharbour.net/moving-on-to-new-challenges/#respond Tue, 11 Dec 2012 10:15:08 +0000 http://www.lharbour.net/?p=232 “The times they are a changin’.” – Bob Dylan

The last 5 years have been some of the most personally and professionally rewarding of my career. It was by no means an easy decision but I’ve decided to take the plunge and move on to the next phase of my professional life. It’s always a bittersweet experience to go through a transition of this type but as a colleague once told me “you know when it’s time.” What helps is knowing that in my new position, I’m going to get to experience some exciting and fun new challenges and meet lots of interesting new people. I’m really looking forward to it!

Many thanks to all the wonderful and talented people I’ve worked with over the past few years. I’ve learned a lot, had a LOT of fun, and got to participate in the delivery of some great and interesting products! I wish you the best in all of your future endeavors and perhaps our paths will cross again one day.

http://www.lharbour.net/moving-on-to-new-challenges/feed/ 0
Groovy/Grails as an application solution http://www.lharbour.net/groovygrails-as-an-application-solution/ http://www.lharbour.net/groovygrails-as-an-application-solution/#comments Mon, 29 Oct 2012 14:15:58 +0000 http://www.lharbour.net/?p=215 I’ve been having some interesting conversations with a colleague concerning the Groovy/Grails stack as a solution for web-based applications. Although I’ve become a Groovy believer, it doesn’t necessarily mean I’ve embraced Grails as a strategy for rapid application development. I certainly understand the attraction, but using one doesn’t necessarily mean you have to use both.

A word about dynamic languages. I know the controversy surrounding this debate but while I have some reservations, I’ve never been categorically opposed to dynamic languages.  I’ve used ActionScript in the past, have fooled around with PHP, am cool with Javascript and like I said, I’ve become a Groovy convert.  I would advocate using it in any JVM-based app.

As far as Grails, there are many positives. In addition to being great for quick prototypes, it’s also great for situations where plug ins already afford a great degree of desired functionality, or super fast development in scenarios without a lot of disparity in functionality between different facets of the application.

The opinions I’ve formed recently are related to my own admittedly somewhat limited experience with the framework and the discussions I’ve had with people and presenters I met at the recent SpringOne 2GX conference. Since Grails is a convention heavy framework, components need to be built within a pre-defined pattern to get the full benefit.  It infers things about what you’re doing based on that.  Some of the behavior is a bit mysterious and is not clearly documented. If you find you need to get outside of the pattern you have to do the work you’d have to do with a configuration-based framework anyway.

The impressions and general feedback I’ve received on Grails seems to follow this general pattern.

  • It can scale with effort and some sacrifices in terms of clarity and organization.
  • It lacks a way to clearly create a separation of concerns (see above).
  • It is convention heavy which can make for a bit steeper learning curve than some alternatives.
  • It can ultimately become unmanageable over time no matter how careful you are.
  • To mitigate some of these created your business components using the Grails-plugin architecture to modularize the application. Kenneth Liu gave a great presentation on how to approach this at the conference.

Anyway, since the conventions established with Grails is not one that is based on a knowledge of any particular business domain, components can get glommed together in the Grails pattern without regard for reuse or organization.  Controllers in particular can quickly become monolithic.  The business domain tends to reflect the physical implementation of the database because of the nature of GORM.  It can certainly work no matter the scenario but there are tradeoffs and I think if things get to that point it’s certainly worth considering a more traditional configuration-based framework.  By the way, when I talk “scale” here I mean in terms of complexity rather than performance.

To be fair, some people have had pretty good success using Grails for simple or medium complexity applications. Still, if I were to start a complex green field app right now, I’d most likely want to use Spring 3.x with a heavy dose of Groovy for the business logic and use Roo to help with the quick start goodness that is a Grails strength.  You’d get the benefit of Groovy within the context of a highly configurable, well understood, and widely used application framework.

http://www.lharbour.net/groovygrails-as-an-application-solution/feed/ 1
SpringOne 2GX is in the books http://www.lharbour.net/springone-2gx-is-in-the-books/ http://www.lharbour.net/springone-2gx-is-in-the-books/#respond Mon, 22 Oct 2012 18:22:11 +0000 http://www.lharbour.net/?p=205 I returned from SpringOne 2GX in DC last week. Lots of good exciting stuff being talked about.

Adrian Colyer, CTO of VMWare, did the intro. There was a great deal of emphasis being placed on the next generation of applications. Mobile applications (big surprise) and the increase of sophistication around clients (impact of tech like HTML5, web sockets (push notification), device agnostic applications, the cloud, high performance infrastructure, big data, and more) where hot topics. Had a couple of speakers get up next and talk about Spring and Groovy/Grails. Interesting to see a little thinly-veiled (but good natured) rivalry between the two camps.

I spent a lot of time talking to people and listening to presentations in the Groovy/Grails space. I admit that over the course of the last few weeks, I’ve gone from a Groovy language semi-skeptic (dynamic typing? Egads!) to a convert. AST transformations are way cool mysterious magic and deliver A LOT of power to POGOs at no or very low cost. Groovy is also great for ad-hoc scripting. Groovy and Java can be intermixed easily. Creation of new DSLs (Domain Specific Languages) is manageable although it seems like there’s a little bit of a learning curve associated with doing it “the right way”. Oh, did I mention closures!?!  And I haven’t even mentioned the syntactic sugar Groovy provides yet.

Some nice things.

  • Native support for lists, maps, regular expression
  • Everything’s an object, primative types and object types in Java are treated differently, in Groovy they’re all the same!
  • GStrings which in spite of their funny name, make working with Strings a bit easier.
  • Lambda-like expressions and Currying. (Oh, did I mention closures!?!)

AST Transformations.

One of the cool features in the Groovy toolbox is that you can add an annotation to your source code and get a lot of built in functionality woven in at compile-time. There are several different types of transformations. A common case is the idea of object immutability. Immutable objects are ones which don’t change after initial creation. The basic properties of such objects are:

  • No methods that modify the internal state of the object.
  • The class should be final.
  • Fields should not be visible.
  • Mutable embedded objects should be guarded (read only versions or defensive copies supplied)

Doing a simple class in Java might look like this…

 final class Person {      final String name;      final Integer age;      private person() { } //disallow private constructor        public Person(String name, Integer age) {          this.name = name;          this.age = age;      }        public getName() {          return name;      }        public getAge() {          return (age!=null ? new Integer(age) : null); //make a defensive copy      }  }  

Rather than writing Java code to implement this behavior, you can just use the @Immutable tag in groovy.

 import groovy.transform.Immutable    @Immutable final class Person {      String name      Integer age  }  

That’s it! Groovy gives you accessor methods and a contructor for free. Also, changes to Integer will be prevented and any requests for the Integer object will give you a defensive copy. Pretty nice for a single annotation.

 def p = new Person("Timmy", 12)  p.age = 12   // results in groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: age for class: Person    def p = new Person("Timmy", 12)  def i = p.age  i = 21  //is fine  


Grails is a convention based framework that rides on top of common Spring components. It feels like it solves some of the problems also solved by Spring Roo, although they do it considerably differently. The idea of getting a reasonably configured “kick start” on new apps are common to both. Grails is a whole ecosystem and Roo is more of a utility concept. I could be wrong, but I’d bet VMWare will eventually de-emphasize one over the other since they do solve a similar set of problems. Some folks I spoke to who are using Grails seems a little lukewarm about the framework. It’s still new enough that the adoption rate may pick up over time, but in my opinion developing applications with Spring with a good dose of Groovy sprinkled in would give the benefits of Groovy with a proven application framework like Spring.

http://www.lharbour.net/springone-2gx-is-in-the-books/feed/ 0
Unlock sequence for Coleman Horizon & Spectrum spas http://www.lharbour.net/unlock-sequence-for-coleman-horizon-spectrum-spas/ http://www.lharbour.net/unlock-sequence-for-coleman-horizon-spectrum-spas/#respond Sat, 06 Oct 2012 14:31:33 +0000 http://www.lharbour.net/?p=202 We have an older Coleman Horizon 208 spa which we hadn’t used in a while and recently got back into working condition. After inadvertently locking the panel, I realized I had forgotten how to unlock the darn thing and searching on google showed that apparently other people have run into this too. Anyway, I thought I’d share the solution here just in case it might be useful for someone.

This works for both the panel lock and temperature lock features.

To unlock either, press the following 3 buttons in rapid sequence. Program, then Mode, then Set Down. The manual says you have 2 seconds but the timing actually appears to be quicker which is the issue I was having.

http://www.lharbour.net/unlock-sequence-for-coleman-horizon-spectrum-spas/feed/ 0
Macbook Air http://www.lharbour.net/macbook-air/ http://www.lharbour.net/macbook-air/#respond Wed, 15 Aug 2012 11:13:07 +0000 http://www.lharbour.net/?p=191 I decided to take the plunge and turn in my windows desktop for a Macbook Air as my primary development machine. After reading some pros and cons, I figured I’d give it a try and so far so good. Mostly for development work, I run Eclipse (the STS variant) but also have been running XCode on a Macmini at work, so it seemed like a natural progression. I’m going to post some of my impressions here as I get more experience with it. So far, I’ve been pretty impressed. Mine has the sandy-bridge 2.0 GHz processor and 8 gigs of RAM. With the blue tooth keyboard, mouse and external monitor, it’s hard to tell I’m not working on the desktop. We’ll see if it can keep up as I start adding more projects to Eclipse and install some additional supporting tools.

http://www.lharbour.net/macbook-air/feed/ 0
HTML5 Localstorage http://www.lharbour.net/html5-localstorage/ http://www.lharbour.net/html5-localstorage/#respond Sat, 11 Feb 2012 14:03:17 +0000 http://www.lharbour.net/?p=140 I have been recently developing mobile applications using a combination of HTML5, CSS3, Phonegap, and jQuery mobile. This is an amazing stack for developing portable mobile apps without the need to write native applications for each platform. The HTML5 spec, although not finalized is gaining wider and wider adoption and looks to transform mobile application development as well as the traditional web experience.

One of the great features of HTML5 is the ability to store data in the local browswer cache that’s much more robust then that previously afforded by HTTP cookies. There used to be a couple of ways to accomplish this. One was by using the WebSQL concept allowing data storage accessible thorough an SQL type syntax and hierarchal data structures. This method has been deprecated by the W3C (at least for now).

The alternative is HTML5 localstorage which defines access to the local browser cache through a relatively simple API. Localstorage amounts to a map of key value pairs of type string. This is not as limiting as it might at first seem however. There is a very simple way to store javascript objects other than string in the local storage. It’s simply a matter of serializing those objects so that they can be reconstructed for use at a later time.

Here’s a trivial example…

var myObject = {};  myObject.name = 'Lonnie';  myObject.myFriends = [];  myObject.myFriends[0] = 'Alice';  myObject.myFriends[1] = 'Dave';  myObject.myFriends[2] = 'Mike';    //example of code to store a javascript object as json into local storage  localStorage.setItem(key, JSON.stringify(myObject));    //example of code to restore a javascript object from json out of local storage  var anObject = eval('(' + getLocal().getItem(key) + ')');

You can download a simple working example of this principle here.

In the past, HTTP cookies have been used (some people might say misused) for the purpose of storing more or less persistent browser data. HTML5 local storage provides access to a datastore with much more capacity then that afforded by cookies. Local data caching can allow applications to be much more responsive and even operate in some cases when “offline”, a great capability in the world of mobile applications.

http://www.lharbour.net/html5-localstorage/feed/ 0
Looking silly for a good cause http://www.lharbour.net/looking-silly-for-a-good-cause/ http://www.lharbour.net/looking-silly-for-a-good-cause/#respond Fri, 20 Jan 2012 11:07:44 +0000 http://www.lharbour.net/?p=128 I have a friend who recently decided to get a hair cut. This may not sound all that unusual, but in this case, it was the first venture under the stylist’s scissors in almost 3 years. Yet there was a very important reason he decided to do it. He decided to trade in his biker meets OpenGL developer style-sense after watching a television news report about the Locks of Love organization, which helps financially disadvantaged children who suffer from long-term medical hair loss. These children generally cannot wear artificial hair pieces due to the chemicals in the manufacturing process; it can create reactions for their sometimes compromised immune systems. The kids CAN wear natural hair pieces on the other hand, but the problem here is one of expense as natural wigs are very expensive.

Locks of Love takes donations of hair of sufficient length from people willing to donate, then works with manufacturers to create the natural hair pieces these kids need and provides them at little or no cost.

Recently, I decided to take the plunge and donate myself. The only problem is that, unlike my friend, my hair has (at least since my late high school days) never attained a length greater than about an inch. So starting last October, I abandoned my monthly trip to the barber and (as David Crosby once sang) “let my freak flag fly”. I expect to accumulate the requisite 16 inches or so over the course of the next two years.

In the meantime, in reply to the curious looks and comments that seem to be accumulating faster than the hair on top of my head, I’ve been jokingly replying “hey, I’m a software developer…I’m SUPPOSED to have a pony tail.”

They seem to understand.

http://www.lharbour.net/looking-silly-for-a-good-cause/feed/ 0
Subversion tip http://www.lharbour.net/subversion-tip/ http://www.lharbour.net/subversion-tip/#respond Thu, 29 Dec 2011 23:38:44 +0000 http://www.lharbour.net/?p=81 I use subversion for source control. There may well be better options out there (git anyone?) but it works fine for me 99% of the time. Someone I know was recently wondering how to retrieve a directory he’d deleted from his subversion repository, so thought I’d post this.

Since there is not a general “undo” in subversion, you have to copy the directory (or files, which this also applies to) from the revision before the commit which removed the directory or file to the “head”. This allows you to retain the original history. You can actually do this all in one step, however doing it as a multi-stop process using a local working copy allows you to review and validate that you’re doing the right thing in between steps.

The basic process is that you first copy the revision with your deleted directory or file down to a local working copy, then copy the directory or file up to the original location in the remote repository.

In case you don’t have a working copy, just check out the parent directory (the head revision) as a local working copy. For this example, parent is the original parent directory of the removed object, myObject is the object that was removed, and “4906” (arbitrary revision number) was the svn revision before the object was removed.

Checkout a local working copy if you don’t have one.

svn checkout http://myRepostoryServer/project/web/src/parent

Then copy from the deleted object from the remove repository / revision to the local working copy.

svn copy http://myRepostoryServer/project/web/src/parent/myObject@4906

Finally after you’ve checked out the locally recovered object, check it back in to the remote repository.

svn copy myObject http://myRepostoryServer/project/web/src/parent -m "Restore myObject to previous state"
http://www.lharbour.net/subversion-tip/feed/ 0