Wednesday, December 21, 2011

A Message Routing Groovy DSL

The other day I was discussing system integration with a friend and he mentioned something about creating a DSL (Domain Specific Language) for the many aspects of enterprise integration. I have limited experience with writing DSL's but I figured I would give it a shot. Inspired by this post on the Canoo blog and my friend's idea, I started hacking on GroovyConsole. Groovy is a great language for writing DSL's because of the language's features like closures and map based interface implementation. Plus, Groovy has the benefit of being fully compatible with Java and other Java based tools. What I want to do is create a DSL for writing rules for a hypothetical message routing engine. Here is my Message domain class and System enum:
import groovy.transform.TupleConstructor

enum System {
    bus, db2, iSeries, mySQL, oracle, postgre
}

@TupleConstructor
class Message {
    String payload
    System origination
    System destination
    
    String toString() {
        "${payload} from:${origination} to:${destination}"
    }
}

Here is what I think the DSL might look like:
route message to oracle, mySQL when origination eq db2

What I am saying is, route a message to oracle and mySQL systems when the message's origination is db2. I guess I really didn't need to explain that because the DSL is pretty self explanatory, right? Let's move on to see what else the DSL might look like:
route message to iSeries, oracle, mySQL when payload contains 'Hello'

Is there a need to explain what the previous statement is stating? If you have not caught on yet, it is saying route a message to the iSeries, oracle and mySQL systems when the message's payload contains the word 'Hello'. In each case, I would imagine creating a new Message for each system that will be put on a queue or sent to an endpoint to be processed. Here is the meat of the code that will implement the DSL I designed above:
import static System.*

messages = []

Above, we have the initialization of the list of messages that will be the result of our DSL statement. If the proper conditions are met, we are returned a list of new messages to send to other systems.
def payload = { Message message ->
    message.payload
}

def destination = { Message message ->
    message.destination
}

def origination = { Message message ->
    message.origination
}

The code above handles referencing each message property. The code below handles the keywords route, to, when, eq, neq and contains. It also handles each message instance and the array of System destinations, for example: iSeries, oracle, mySQL.
def route(Message message) {
    [to: { System[] destinations ->
        [when: { Closure clos ->
            [eq: { System system ->
                if(clos(message) == system)
                    destinations.each { messages << new Message(message.payload, message.origination, it) }
                messages
            },
            neq: { System system ->
                if(clos(message) != system)
                    destinations.each { messages << new Message(message.payload, message.origination, it) }
                messages
            },
            contains: { String string ->
                if(clos(message).contains(string))
                    destinations.each { messages << new Message(message.payload, message.origination, it) }
                messages
            }]
        }]
    }]
}

Below, is an example Message instance for testing the DSL.
message = new Message("Hello there!", db2, bus)

When I run my DSL statements from above, I see the list of messages created to be sent on to the other systems.
route message to oracle, mySQL when origination eq db2

Result: [Hello there! from:db2 to:oracle, Hello there! from:db2 to:mySQL]

The second example:
route message to iSeries, oracle, mySQL when payload contains 'Hello'

Result: [Hello there! from:db2 to:iSeries, Hello there! from:db2 to:oracle, Hello there! from:db2 to:mySQL]

I think this is very cool for my first attempt at a DSL with Groovy. I am sure I can clean up the code a bit (feedback is welcome) and this is really just scratching the surface of what we can do with Groovy and DSL's!

Tuesday, November 15, 2011

Issue with Dynamic Proxy in Java?

I created a simple Annotation, Report, the other day to handle some simple logging/reporting tasks. The intent is to create a simple way to annotate methods that should be logged or reported during invocation. Here is what the Annotation looks like:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Report {
    String menu();
    String name();
    Platform system();
}
I have an interface, Menu, which all Menu implementations will implement:
public interface Menu {
 
    public void doSomething(String session);
}
Here is an example implementation of Menu, MyMenu, with a Report Annotation on the doSomething(...) method. Platform is an enum that describes whether or not to log/report to Oracle, SQL Server or both systems as in the case below:
public class MyMenu implements Menu {

    @Report(menu="AIT_MM", name="MyMenu", system=Platform.BOTH)
    public void doSomething(String session) {
        System.out.println("Doing some work!");
    }
}
Here is a block of code that creates a MyMenu implementation of Menu and a Proxy instance of Menu, and gets the "doSomething" method and checks whether or not the Report Annotation is present on the Method, m:
    Menu menu = new MyMenu();
    Menu menuProxy = 
        (Menu) Proxy.newProxyInstance(menu.getClass().getClassLoader(), menu.getClass().getInterfaces(), new MyLogger(menu));
 
    try {
        Method m = menuProxy.getClass().getMethod("doSomething", String.class);
        if(m.isAnnotationPresent(Report.class))
            System.out.println("Annotation is here!");
    } catch (Exception e) {
        e.printStackTrace();
    }
  
    try {
        Method m = menu.getClass().getMethod("doSomething", String.class);
        if(m.isAnnotationPresent(Report.class))
            System.out.println("Annotation is here!");
    } catch (Exception e) {
        e.printStackTrace();
    }
The statement
if(m.isAnnotationPresent(Report.class))
evaluates to true in the second try/catch block with the normal instance of MyMenu, menu but it evaluates to false in the first try/catch block with the proxy instance of MyMenu, menuProxy. The above code also includes a reference to a class, MyLogger, that implements InvocationHandler. This is where the evaluation of
if(m.isAnnotationPresent(Report.class))
is imperative because it completes my implementation goal. Inside the MyLogger class, I have implemented the
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
method from InvocationHandler like so:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if(method.isAnnotationPresent(Report.class)) {
        Report r = method.getAnnotation(Report.class);
        this.logMyPrompt((String) args[0], r.menu(), r.name(), r.system());
    }
    return method.invoke(delegate, args);
}
Just some strange things that I noticed when trying to do something cool with Java Annotations. Everything works if I put a Report Annotation on the Menu interface's doSomething(...) method declaration, but that solution does not allow me to have individual data related to each implementations' doSomething(...) method.

Wednesday, October 26, 2011

Something Else I Need to Remember About Groovy

This is something else I need to remember when writing a Groovy script.
def c = "closure"
m = "method"

def myClosure = {
    println c
}

def myMethod() {
    println m
}

myClosure()
myMethod()

The above works as I expect it to. As soon as I change line 2 to this...
def m = "method"

...I get an error. Just something that I need to keep in my head on the Groovy Console.

Tuesday, October 25, 2011

A Quick Reminder About Using a Language

Let's say I decided to do all this work...
def boolean isNumber(String s) {
    try {
        int i = Integer.parseInt(s)
        return true
    } catch (Exception e) {
        return false
    }
}
In order to do this...
println isNumber("4")
println isNumber("-4")
println isNumber("t")

To get this result...
true
true
false

When all I needed to do is use the language features...
println "4".isNumber()
println "-4".isNumber()
println "t".isNumber()​​​​​​​​​​​​​​

To get the same result with a lot less coding...
true
true
false

Monday, October 17, 2011

Focusing on Business Continuity, Scalability and High Availability

Business is 24/7 and customers want access to your product at their convenience. As a developer and designer of many public facing applications, I find this is one of the most overlooked concepts when businesses are looking to improve their existing applications.

We are in a world where free, social networking applications perform above and beyond most "enterprise" level applications. Our business customers are experiencing this availability and performance and they are looking to internal IT staff and infrastructure teams to step things up. If you are part of a company's internal IT staff, you should understand how some of the top social sites are managing PetaBytes of data and millions of concurrent online users. The actual capacity numbers may not match up to your work environment but an important quality of scalability is being able to scale up as well as scale down.

Just some thoughts of what is on the horizon for professional IT staffers who are considering on being relevant as "enterprises" embrace the lessons learned by many of the top technology companies.

Sunday, September 25, 2011

HTML5 Game Programming

I just picked up Learning HTML5 Game Programming: Build Online Games with Canvas, SVG, and WebGL for my Kindle. Why am I going to read a book about game programming with HTML5? I think that investing a good portion of my free time on understanding the details and limits of HTML5 is crucial to my future. HTML5 is the future, for some of us, it is the present. I will post a review when I am done and hopefully I will post some of my findings.

http://amzn.com/B005OR9NH0

Sunday, August 21, 2011

A Quick Intro to Gradle

I have been spending some time learning and working with Gradle. Gradle is a Groovy based build and dependency tool that supports declarative builds and build-by-convention. Gradle is an open source project and it is used by many companies and other open source Java and Groovy projects.

First, make sure you have Java 1.5+ installed and download Gradle from gradle.org. Create a GRADLE_HOME variable in your environment referencing where you have unpacked your download. Next, add GRADLE_HOME/bin to your PATH variable. To confirm Gradle is installed and working, enter gradle --version at a command prompt.

Once you know Gradle is installed properly, you can now setup your project. To put together a simple project, all you need is a /src/main/java directory with your packages and Java source and a build.gradle file. I highly recommend adding a /src/test/java directory with your test packages and Java unit testing source because everyone needs to write tests.

I have been using Gradle with a Java project that I have been working on. I mostly have been depending on Gradle to handle my dependency resolution, running tests and packaging my project. So, what kind of work goes into using Gradle for my needs? It is quite simple, it is a build file, build.gradle, with a few lines of Groovy.

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'commons-logging', name: 'commons-logging', version: '1.+'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}


The above entries let Gradle know to use the Java plugin, add Maven Central to the repositories and add commons-logging as a dependency for compilation and JUnit as a dependency of the test compilation. Within the project directory enter gradle build at a command prompt. The source will be compiled, the tests will be run with reports and you will have a packaged Jar file. It is ridiculously simple to get started. The Gradle team has done a great job. Have fun writing code.

Sunday, July 31, 2011

Integrating Spring and AVAYA Dialog Designer

For quite a while, I have been an advocate of using the Spring framework for most, if not all, of my recent Java projects. There are many advantages of using Spring for features such as dependency injection, transaction management, and integration (Web services, messaging) because Spring creates an abstraction from the underlying implementations allowing developers to focus less on the 'how-to' and more on the problem at hand.

When working with AVAYA Dialog Designer, an Eclipse based IDE for developing IVR applications, I have found that I rely heavily on shared Java libraries that have been already been tested and proven in our enterprise. With an increasing number of these shared libraries being written with Spring, I found that I needed to bring the Spring context into the AVAYA runtime environment.

Because, the AVAYA IVR environment is a Java Web environment, we can start by locating the web.xml file in the project under the WEB-INF directory. We can add a ContextLoaderListener to the application's web.xml file and we are on our way.
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/ivr-application-context.xml</param-value>
</context-param>

Next, we need to investigate how we are configuring our application context file to ensure that our application context loads our dependencies' beans into this application's context. In the xml above, I have set the contextConfigLocation parameter to point to the location of the IVR application's context file. In ivr-application-context.xml, I have configured a few beans that I have written in my Dialog Designer project.
...
<bean id="myBean" class="beans.MyBean"/>
...

If we have other application context files, we can import them in ivr-application-context.xml or add them to the contextConfigLocation.

One feature of the Dialog Designer environment is the capability of writing your own custom Java classes, like MyBean, and overriding some of the current application's classes represented by the graphical call flow nodes. Each node is backed by a Java source file. For example, we can override the requestBegin(SCESession mySession) method of the generated AVAYA framework classes and use the SCESession object to access the ServletContext in order to get access to Spring's WebApplicationContext.
...
public void requestBegin(SCESession mySession) {

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(
    mySession.getServlet().getServletContext());
    MyBean myBean = (MyBean) context.getBean("myBean");
}
...


Now we have access to an instance of MyBean from Spring's context. In the end, we can see how easy it is to bring Spring into an existing Java Web framework that really does not need to exist within the Spring container. The dependent libraries can be accessed and we can wire any other custom beans if needed. Of course, things would be much easier if the AVAYA framework integrated with Spring, but if you find yourself working with a similar contraint, I hope this post illustrates how easy Spring makes integrating with other technologies.

Thursday, May 12, 2011

The Simplicity of Spring MVC 3

The beauty of Spring MVC is the overall simplicity of getting things done. Here is a quick fictional example of the simplicity of a controller in Spring MVC:

@Controller
@RequestMapping("/")
public class WelcomeController {
   ...
}


Above we have the WelcomeController class. All we need to make this class a controller is the @Controller annotation. This controller is mapped to handle all application root requests through the @RequestMapping annotation. Below, we have a few methods that exist within the WelcomeController class that handle GET and POST actions to index.htm.

...
@RequestMapping(value="index.htm", method = RequestMethod.GET)
protected ModelAndView indexGet() { ... }
...


Above we handle the /index.htm GET request and return a Spring ModelAndView object. In the indexGet() method we can add model objects to render in the view and set the view name as shown here:

...
ModelAndView mav = new ModelAndView();
mav.addObject("domainObject", new DomainObject());
mav.setViewName("welcome");
return mav;
...


Below we are handling a POST to /index.htm and here we are expecting our fictional DomainObject class from a form, and we denote that with the @ModelAttribute annotation.

...
@RequestMapping(value="index.htm", method = RequestMethod.POST)
protected ModelAndView indexPost(@ModelAttribute DomainObject instance) { ... }
...


In the indexPost(@ModelAttribute DomainObject instance) method we can handle the DomainObject instance.

...
validate(instance); // do some validation
myService.save(instance); // persist the DomainObject instance
ModelAndView mav = new ModelAndView();
mav.addObject("domainObject", instance);
mav.setViewName("welcome");
return mav;
...


Spring MVC is great for putting together Web applications and the controller infrastructure and configuration is quite fantastic and super simple. A developer can work directly with domain objects in a Web application while avoiding getting wrapped up in technology.

Tuesday, May 10, 2011

Discussing Technical Debt

There are a lot of software developers that discuss Technical Debt. Martin Fowler has a nice post on Technical Debt and I also encountered the term while checking out the Sonar project a little while ago. Technical Debt is something that I feel businesses and developers do not understand in its entirety and for good reasons. When a developer is tasked with making a decision about a functional implementation, options are sometimes available. One implementation can be done by a date d and a possible second implementation can be done by a date d + n. The ideal developer response is to propose all solutions and dates and let the business decide on a path to follow. It is key that the developer provides the pros and cons of all proposed solutions. Most of the time, developers can even eliminate a solution because of governing software development standards or by understanding the pitfalls of a solution which may impede maintenance or functionality in the future. In many cases, developers may not recognize the availability of other options or understand the pitfalls of a solution. In other cases, the business settles on the fastest solution. These scenarios may introduce Technical Debt.

In the enterprise environment, the introduction of Technical Debt may occur quite frequently, that really depends on quite a few environmental factors. So how do we understand and measure Technical Debt? Sonar is definitely a great tool that can help identify code in the red. Technical talent definitely has an incredible impact on Technical Debt. Having high quality developers with experience is very important when identifying and reducing Technical Debt. Managing an inventory or repository of software artifacts that are well documented can provide insight to relevant, proven and performing code. As developers, managers and IT executives we have to recognize and identify where we can alleviate debt by determining how to move forward with the relevant, performing code while leaving behind under-performing or costly code bases.

Technical Debt is not necessarily a platform or language, so moving to Ruby from Java or to Java from C# is not an answer to fix the debt problem. In some cases, changing languages or platforms is like a foreclosure or declaring bankruptcy. You get to put your past behind you, (well kind-of), but if you continue to make poor development decisions you will eventually end up over your head and in the red. Focusing on understanding Technical Debt and putting measures in place to reduce debt is really the way to move forward.

Sunday, April 17, 2011

Building an IVR Survey App with Grails 1

I have been exercising my Grails skills lately while working on an IVR based survey application. Grails is a pretty incredible platform for an IVR application because of Groovy's builder infrastructure. We can exploit Groovy's MarkupBuilder to create XML, specifically VXML, on the fly with minimal effort. I will post more about my progress of the Grails IVR survey application as things progress. I am considering open sourcing the code on github, but I think I need to prove it out a bit first. In Groovy/Grails we can do things like this:

render (contentType:"text/xml") {
    vxml(version:"2.1") {
        form ("", id:"survey") {
            block {
                audio (src: "/ivr-survey/prompt/fetch/${promptInstance.id}")
                prompt (promptInstance.text)
                "goto" (next: "/nextPrompt")
            }
        }
    }
}

Above we can utilize the render method in a Grails controller to respond with XML/VXML and the promptInstance (an instance of a Prompt class) in order to drive the application dynamically based on the current prompt in the call flow. There is quite a bit of stuff going on around the above snippet, so I will dig deeper into the application in the next post.

Monday, February 28, 2011

A Great Album from Deadmau5

I recently ordered Deadmau5, For Lack of a Better Name from Amazon. It is another great album from Deadmau5. I have listened to it a few times through and it is as good as other Deadmau5 albums 4 x 4 = 12 and Random Album Title. I really dig the sound-scape that is created. I definitely enjoy listening to any three of these albums while writing code or on a run. I listened to For Lack of a Better Name during the Gasparilla Distance Classic 5K I did this past weekend. The music definitely kept me pumped up and it kept out all the crappy top 40 "hits" music from bringing me down.

Saturday, February 26, 2011

Getting Started with Spring.NET

I have been a big fan of the Spring Framework for quite some time. As a matter of fact, I count on the many benefits and features of Spring for most of my Java projects. I have found Spring to be a gateway to productivity and better practice development for a number of solutions in the enterprise.

Recently, I have been investigating the .NET platform and C#. We have a mixed Java/C# environment at work and I would like to be a more flexible resource in order to help out on more projects. As I started looking into C#, I thought it was only appropriate to look into the Spring.NET project. It is quite similar to its Java counterpart and here is how I got things started with a very simple C# project:

First, I downloaded Visual C# 2010 Express. It is not quite as fancy as the variety of Visual Studio 2010 offerings, but it is a great IDE to get started with learning C#. Next, I downloaded the latest Spring.NET release, which happens to be version 1.3.1. In Visual C# 2010 Express, I then created a new blank project, 'SpringNET1'. Next, I added the Spring.Core.dll and Common.Logging.dll as references in my new project.

I created a new Class, MyApp.cs. This is the entry point of my application. I will go over the details of the Main(string[] args) function shortly, but basically it grabs the application context, gets an instance of the MyService class, calls MyService's GetName() function and writes the output to the console.

using System;
using Spring.Context;
using Spring.Context.Support;

namespace App.Core
{
    class MyApp
    {
        static void Main(string[] args)
        {
            IApplicationContext ctx = ContextRegistry.GetContext();
            ServiceInterface myService = (MyService) ctx.GetObject("MyService");
            Console.WriteLine(myService.GetName());
            Console.ReadLine();
        }
    }
}

Then I created an interface named ServiceInterface.cs with one function, GetName(), which returns a type of String.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace App.Core
{
    interface ServiceInterface
    {
        String GetName();
    }
}


Below is an implementation of the ServiceInterface, MyService.cs, which implements the GetName() function by returning my name, "RJ Salicco".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace App.Core
{
    class MyService : ServiceInterface
    {
        public String GetName()
        {
            return "RJ Salicco";
        }
    }
}

Lastly we need to create an Application Config file and let the runtime know about Spring and our Spring objects. The important thing to note here is the way that objects are configured. Using the <object> tag, we define the 'id' of the object and the 'type' of the object which is denoted by the fully qualified class name (namespace and class name) and the Assembly name separated by a comma. The 'id' is what I used to lookup the MyService instance in our context used in the MyApp class.

<configuration>
    <configSections>
        <sectionGroup name="spring">
        <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
        <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
    </sectionGroup>
    </configSections>
    <spring>
        <context>
            <resource uri="config://spring/objects"/>
        </context>
        <objects xmlns="http://www.springframework.net">
            <description>Simple bean setup.</description>
            <object id="MyService" type="App.Core.MyService, App.Core"></object>
        </objects>
    </spring>
</configuration>


I knowing this example is really, really simple, but I just wanted to document a starting point. We can all imagine a real world example implementation, wiring in some more objects, referencing objects as constructor arguments or properties and possibly utilizing the features of Spring AOP. As I dig deeper into C# and the .NET platform I plan on sharing what I learn and if Spring.NET delivers just some of the features its Java counterpart delivers, I will feel confident delivering C# solutions along with my Java solutions.

Wednesday, January 05, 2011

Availability != Scalability != Performance

Availability - the degree to which a system is responsive or in a state in which it is expected to be in

Scalability - property of a system to manage increased load as expected or the capability to be expanded to handle increased load

Performance - the speed or measure of the completion of a unit of work

Just some thoughts I had today about computer systems and what is important to end users. Redundancy should also be in place, but maybe it's not a concern for end users.