Showing posts with label Software Development. Show all posts
Showing posts with label Software Development. Show all posts

Tuesday, November 29, 2016

Building a Successful API Strategy

As we embark into a new era of integration and connectivity, it is key to effectively communicate an API strategy. An API strategy needs to be clearconcise and executable.

An API strategy should simply answer these questions:
  • Why are we building API's?
  • How are we building API's?
  • What are we building API's to expose?

These answers should be concise and to the point. The answers should not be overly detailed. The detailed answers to these questions may differ slightly from different viewpoints like organizational boundaries or specific functions within an organization.

An API strategy should align with our industry and the principles of our company. The ability to execute is the most important aspect of our API strategy.

Tuesday, February 02, 2016

Programmer Revival

A few weeks back I went out to the Tampa Java (JVM) User Group meeting to watch Venkat Subramaniam speak about Lambdas and functional programming with Java 8. I have already read his book, Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions, on the topic but I could not pass up on the opportunity to see him speak in person. I make every attempt to see speakers/authors/programmers, such as Venkat, in person because for me it is like a spiritual experience for my (programmer) soul. Many people attend places of worship to hear a community leader speak about known truths, to hear the truth from someone who believes passionately in these truths of life. People are there to reaffirm their beliefs and walk away from a positive experience with a sense of improved strength. It is invigorating and it revives their personal life to help them with their days ahead. The same thing happens when I attend events like the Tampa Java (JVM) User Group meeting last month. Venkat's presentation and live programming invigorated my (programmer) soul as he spoke about the truths we developers face on a daily basis. He elaborated on how we approach simple problems with an abundance of complexity, how we are gluttons for punishment as we write multi-threaded code to guarantee we will struggle to recreate that production defect in our tests as we run the debugger. I truly appreciate the passionate speakers/authors/programmers that evangelize the truth with an incredible amount of passion for the craft of programming, who invigorate our (programmer) souls so we can continue on our programming mission for a lifetime of learning and personal growth.

Tuesday, March 31, 2015

Implementing and Delivering Software Solutions

Every software development project I have worked on since I started my career in 1999 has faced challenges. The types and complexity of the challenges have varied from project to project. Our goal as IT professionals (engineers, architects, analysts) is to overcome these challenges and deliver a solution. For some IT professionals the challenges become a crutch, an excuse to walk away. For others the desire to conquer these challenges becomes the reason we wake up everyday and make things happen.

Saturday, April 19, 2014

The Simplicity of Groovy and HTTP

Do you ever have the need to do some simple tasks in your IT environment? Maybe you need to run a few checks on some URL's and ensure that everything is copasetic (returning 200's). There are plenty of tools out there that can ping URL endpoints and give you feedback, but why put a tool in place when you can write a Groovy script in under 50 lines of code that is effective? My answer is a) I think writing Groovy is fun b) it can be simple enough that I would rather spend a little time and create something myself c) why bother with implementing a tool if it is not really needed?

The script is pretty straight forward and I first start with a few imports.
import groovy.transform.ToString

Then I define a simple class, Target, to hold some state for the URL endpoints we would like to query on. In the Target class exists the name property for identification purposes, the url property to hold our endpoint and finally the status property to hold the Target status. Pretty simple, right?
class Target {
    def name
    def url
    def status

The ToString annotation is quite powerful as it makes the output of our class state nice and readable. It overrides the default String toString() {} method with a nice default. We could also override the method in the class and format the data however we would prefer. The next part of the script defines a list of new Target instances that we can iterate through and check the status of each URL.
def targetList = [
    new Target(name:"Google", url:""),
    new Target(name:"Amazon", url:""),
    new Target(name:"Oracle", url:""),
    new Target(name:"Axiomatic IT", url:""),
    new Target(name:"Bad Endpoint", url:"")

I put together some sample instances of Target with some good data and some bad data so we can make sure things are working as they are expected. The next block of Groovy iterates through the list of Target instances, attempts to connect to each URL, checks for the 200 response code, checks to ensure that data is returned when a 200 response code is returned, assigns the appropriate status to each Target instance, prints each Target using the toString() method provided by the @ToString annotation and finally disconnects the HttpURLConnection.
targetList.each { target ->

    def url = new URL(target.url)
    def huc
    try { 
        huc = url.openConnection()
        huc.requestMethod = "GET"

        if(huc.responseCode == 200) {
            def br = new BufferedReader(new InputStreamReader(huc.inputStream))
            if(br) {
                target.status = "Success"
            } else {
                target.status = "Failure"
    } catch (Exception e) {
        target.status = "Failure"

    println target


Below, you can see an example of what the output looks like when I ran the script. The @ToString annotation is producing the format below by default for each Target instance. It just makes things pretty when we call println or log the value of a Target instance.
Target(name:Google, url:, status:Success)
Target(name:Amazon, url:, status:Success)
Target(name:Oracle, url:, status:Success)
Target(name:Axiomatic IT, url:, status:Success)
Target(name:Bad Endpoint, url:, status:Failure)

Groovy makes things pretty simple and in under 50 lines of code I have a simple script I can run to check the status of some Web site URL's. I can make things a bit fancier and have the list of Target instances populated from some external data source like a file or database. I could also check the data to ensure that the response is returning valid HTML or some other valid type of data format. The possibilities are there but for now, I have what I need without too much overhead.

Having Fun with Groovy and the Ternary Operator

Groovy is a great language to compliment your Java skills and to increase your productivity on the JVM. From time to time I work on some code and enjoy sharing its likeness here so I can ensure that a) I don't forget what I have done and b) encourage other developers who are interested in the technologies I find interesting. In this script, I have a model object, Policy, that would normally be fetched from a database or some flavor of Web service.
class Policy {
    def number
    def type
    def value

Next, I define a closure the expects a policy number as input. Using the ternary operator, we verify that a valid policy number has been provided. If a policy number is provided, the closure returns a new Policy with some default values. In a normal situation the second part of the ternary operator would make a call to access a database or call a Web service to return meaningful data rather than just return some static Policy object.
// static fetch method returns a default Policy or an empty Policy
def fetchPolicy = { policyNumber ->
    policyNumber ? new Policy(number:policyNumber, type:"Life", value:10000) : new Policy()

It is pretty straight forward. When the policy number is not null or not empty we get the static Policy object. If the policy number is null or an empty string we just return an empty Policy object. Here is the rest of script that does a few assertions on a null policy number, a valid policy number and a policy number which is an empty string.
def policyNumber

// policyNumber is a null value
policyNumber = null
def policy1 = fetchPolicy(policyNumber)

assert policy1.number == null
assert policy1.type == null
assert policy1.value == null

// policyNumber is a valid value
policyNumber = "123456"
def policy2 = fetchPolicy(policyNumber)

assert policy2.number == "123456"
assert policy2.type == "Life"
assert policy2.value == 10000

// policyNumber is an empty value
policyNumber = ""
def policy3 = fetchPolicy(policyNumber)

assert policy3.number == null
assert policy3.type == null
assert policy3.value == null

There is nothing too fancy with this script but you may have noticed that there are no null checks or empty string checks within the fetchPolicy closure. It may not be a big winner for every developer, but I think that these little nuances are what make Groovy a language all Java developers should have in their toolbox.

Friday, August 17, 2012

Hazelcast: Offline Systems Processing

Hazelcast offers many features to developers working with systems of all shapes and sizes. Hazelcast's implementations of distributed Queue and Map offer possibilities of running Web applications while operational systems are down for maintenance or unavailable. Here is an approach to solving such a problem with Hazelcast.

Let's start with our business model. We sell widgets online and through our call center. We also service order and customer related issues in our call center. Every evening, our widget product database is inaccessible because of some maintenance tasks. Here is one place where Hazelcast fits into the picture.

Before our maintenance window, we preload the widget product data into a Hazelcast distributed Map named "widgets". Each map entry has a key, which is our unique widget id, and a value, consisting of a Widget object. Now, our Web applications can access product data from our Hazelcast distributed Map "widgets", rather than relying on our product database.

When an order is created, Hazelcast's distributed Queue comes into play. The Web applications can submit an order and it will be passed into our "orders" distributed Queue. Here we can keep our orders ready and waiting until our database comes back online. We configure our Queue to be backed by a Map so our "orders" elements, consisting of Order objects, can be persisted in our intermediary storage before being processed when our target datastore comes off of maintenance mode.

A big part of this solution is to have a great services or middleware layer that can take on the burden of working with our distributed Maps and Queues. This will create a good abstraction of our backend datastore and distributed data from our Web applications. As a service oriented architecture is a common approach to abstracting a backend from Web applications, this solution does introduce some complexity into the services or middleware architecture.

Here is a high level diagram of the setup:

With a mature services layer, our call center and online applications can create orders, search through our widgets that exist in our "widgets" distributed Map and even verify and validate orders that are currently only in our distributed Queue "orders" or our Map that is backing our Queue. This type of solution does take some up front planning, but 24/7 business comes at a cost.

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

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 ->

def destination = { Message message ->

def origination = { Message message ->

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) }
            neq: { System system ->
                if(clos(message) != system)
                    destinations.each { messages << new Message(message.payload, message.origination, it) }
            contains: { String string ->
                    destinations.each { messages << new Message(message.payload, message.origination, it) }

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:
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);
            System.out.println("Annotation is here!");
    } catch (Exception e) {
    try {
        Method m = menu.getClass().getMethod("doSomething", String.class);
            System.out.println("Annotation is here!");
    } catch (Exception e) {
The statement
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
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.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


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...

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...

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.

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 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 {

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.


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(
    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:

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());
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; // persist the DomainObject instance
ModelAndView mav = new ModelAndView();
mav.addObject("domainObject", instance);
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/${}")
                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.

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");

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.

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

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.

Friday, December 17, 2010

A Mock Service with Groovy and Jetty

I recently needed to do some testing on a project that integrated with a Web service supported by another team of developers. After I completed my development work, I wanted to do some quick integration testing but I was forced to wait on the completion of the Web services. I was pretty confident that my code changes would work, but I really needed that "live" interactivity to know for sure.

In order to not be caught in this predicament again, I decided to create a simple mock service using Groovy, Jetty and some static XML files. Here is the result using an example domain model and sample data:

I put together a Groovy script to create an instance of a Jetty server. This is very similar to the example that can be found on the Groovy Web site (wink, wink).

import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*

@Grab(group = 'org.mortbay.jetty', module = 'jetty-embedded', version = '6.1.0')
def runServer = {
    def server = new Server(8181)
    def context = new Context(server, "/", Context.SESSIONS);
    context.resourceBase = "."
    context.addServlet(new ServletHolder(new TemplateServlet()), "*.html")
    context.addServlet(new ServletHolder(new DefaultServlet()), "*.xml")



First, we import what we need from Jetty and here I am using @Grab to resolve our Jetty dependency.

Next, runServer is defined to do all of our work. Within runServer, we define a new Jetty Server and use it to create a new Jetty Context. I then set the context's resourceBase to "." which is the directory where the above Groovy file, mockService.groovy, is located.

Now, we need to handle requests to our server. Instead of using a standard Web descriptor, web.xml, file we can write a few line of code to add a new Groovy TemplateServlet mapped to handle the *.html request pattern and a new Jetty DefaultServlet mapped to handle the *.xml request pattern.

The Jetty DefaultServlet will handle resolving our static, test XML files.

The TemplateServlet will handle resolving and running our HTML files and it will allow us to be able to create dynamic Groovy templates like the following:


File List

<% def f = new File(".") if(f.isDirectory()) { f.listFiles([accept:{file->file ==~ /.*?\.xml/}] as FileFilter).toList()*.name.each { %> ${it} <% } } %> </body> </html>

What is great about the TemplateServlet is that the above, fileList.html, contains Groovy that will be executed when the file is requested. This executed code will find all .xml files located in the current directory and display HTML links to each test XML file. For example, I have these two static, test files:


<?xml version="1.0" encoding="UTF-8"?>
    <name>Acount 12345</name>
        <street1>123 Test St</street1>


<?xml version="1.0" encoding="UTF-8"?>
    <name>Acount 54321</name>
        <street1>123 Test St</street1>

The fileList.html request will render something like:

File List


All we need to do to get started is open a command prompt, navigate to my development directory where the mockService.groovy file is located and run:

> groovy mockService.groovy

Now, my application can be configured to point to this local service. In this example, when I want to do a GET request for 'Account 12345', the application can make a call to http://localhost:8181/12345.xml. We can follow that pattern and request 'Account 54321' by calling http://localhost:8181/54321.xml or any other xxxxx.xml file I place in my development directory. I am now able to run simple integration tests with my application while the other team works to complete the final service.

To really understand the simplicity that is involved, here is a quick view of my development directory:

- 12345.xml
- 54321.xml
- fileList.html
- mockService.groovy

Nothing too magical going on here but for me it is just another way to bring Groovy into the work environment to get things done.