Sunday 15 September 2013

How to configure Gradle build on Jenkins

This annoyed me a bit because of course if you read it fully it becomes clear but the GUI is terrible.  



It looks like the options 'Build step description', 'Switches', 'Tasks' etc belong to the lower radio button but actually they belong both.  There should really be a line in there between 'Use Gradle Wrapper' and 'Build step description' to make it clear.  Bad GUI!

So, for example, to run tests with the Gradle build simply write 'test' in the 'Tasks' field and it's done. 

Friday 13 September 2013

C# extension methods example

Extension methods can be used extend an existing class without creating a new derived type of the class to be extended or modifying and recompiling the class you want to extend.

Say we have a Utils project in our solution and in that project we have a class with a static method which converts a string to camel case.

To call this method we must add a reference to this project and pass a string to this method:


However, what we can do is change the ToCamelCase method to be an extension method. We do this by modifying the signature of the ToCamelCase method:


To call it now, we call it like we would call any other string method. It even appears in Intellisense!




Note that in an extension method the first parameter is the one to which you apply the 'this' keyword. Any normal parameters that the method should take follow that first parameter.


Wednesday 11 September 2013

Ref keyword example in C# with structs

In C# if you define a class, then an instance of that class is passed around by reference as it is a reference type.


The above code shows a class called 'Range' which has two int properties, X and Y.

However, if you are familiar with Mircrosoft's suggestions for when to use a struct, you might realise that we should use it here. Microsoft say that a struct should have all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc)
  • It has an instance size under 16 bytes (remember that an int is 4 bytes)
  • It is immutable
  • It will not have to be boxed frequently
Ok so let's define our Range.cs as a struct instead.  All that we need to do is change the keyword 'class' to 'struct'.

Easy peasy. 

Struct defines a value type and so instance of our range object will be passed around by value instead of by references. 

[Note: 
Passing by value: When the object itself is passed around
Passing by reference: Passing a reference to the object in memory]

To illustrate this point imagine that we have 2 move methods, one that takes in a Range and one that takes in a StructRange and moves them diagonally upwards to the right.

Now let's calls these methods:

The output is the following:

          [Range: X=1, Y=1]
          [Range: X=2, Y=2]
          [StructRange: X=1, Y=1]
          [StructRange: X=1, Y=1]

What what? It worked on the range object and moved the coordinates from (1,1) to (2,2) but on the structRange object nothing changed.

When the Move method was called with the structRange, the method was passed copies of the values 1 and 1.  It incremented those values, but the original objects were untouched. To fix this, we need to pass a reference to the struct object to the Move method.  Then the method goes and looks in memory for the ints stored at that memory location and increments them.

Passing by references is shown in the following snippet:

The output is then correct; the move method has been applied:

          [StructRange: X=1, Y=1]
          [StructRange: X=2, Y=2]

Java API for Websphere MQ

There are 2 ways of interacting with WMQ from Java.

1. A set of proprietary Websphere MQ classes for Java
2. A set of WMQ classes for JMS

I strongly recommend the latter because -
  • then you are not tied in to using WMQ.  You can change the message queuing software you are using without having to change your Java code. You may think this is unlikely but I've seen it done. 
  • you get to use spring JMS which is awesome.  It completely removes the need to write any boilerplate code and makes your configuration simple and your code minimal.  
Receiving Messages

You can either use a MessageListener or receive message explicitly. 

Receiving using a MessageListener

First you need to create a class which extends javax.jms.MessageListener and override the onMessage(Message message) method. 

 public class AlexandrasMessageListener implements MessageListener {  
    @Override  
    public void onMessage(final Message message){  
      if (message instanceOf TextMessage){  
         // process your message  
      }  
      else {  
         // throw some kind of error   
      }  
    }  
 }  

This needs to be plugged into a jmsContainer.  I used org.springframework.jms.listener.DefaultMessageListenerContainer rather than the SimpleMessageListenerContainer. The Default is used more commonly (probably because it allows XA Transactions).

 <bean id="alexandrasListener" class="com.alexandra.AlexandrasMessageListener"/>  
   
 <bean id="mqConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">   
   <property name="channel" value="${mq.channel}"/>    
   <property name="hostName" value="${mq.hostName}"/>   
   <property name="port" value="${mq.port}"/>   
   <property name="queueManager" value="${mq.queueManager}"/>    
   <property name="transportType" value="1"/>   
  </bean>   
   
 <bean id="alexandrasContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
    <property name="connectionFactory" ref="mqConnectionFactory"/>  
    <property name="destinationName" value="${mq.queue}"/>  
    <property name="messageListener" ref="alexandrasListener"/>  
    <property name="concurrentConsumers" value="1"/>  
    <property name="maxConcurrentConsumers" value="1"/>  
    <property name="idleTaskExecutionLimit" value="4"/>  
    <property name="maxMessagesPerTask" value="4"/>  
    <property name="receiveTimeout" value="5000/>  
    <property name="recoveryInterval" value="5000/>  
 </bean>  


Receive using a JmsTemplate

Create a receiver class which contains a JmsTemplate.
 public class AlexandrasReceiver {  
   
    @Autowired
    private final JmsTemplate alexandrasTemplate;  
   
    public TextMessage receiveMessage(){  
      final Message message = alexandrasTemplate.receiveMessage();  
      if (message instanceof TextMessage){  
         return (TextMessage) message;  
      }  
      else {  
         // do something else  
      }  
    }  
 }  

Configure your JmsTemplate in spring and wire it in.

 <bean id="alexandrasTemplate" class="org.springframework.jms.core.JmsTemplate"  
 p:defaultDestinationName="${mq.queue}" p:receiveTimeout="2000">  
 <property name="connectionFactory" ref="mqConnectionFactory"/>  
 </bean>  



Best Practices for using var in C#

Var was introduced in version 3 of C# and Resharper was updated such that now, any time you don't use a var, Resharper shouts at you and highlights the offending line by underlining it in a squiggly green line.




However, sometimes C# developers can get a little bit 'var happy' and turn everything into a var, which isn't always a good idea.  The most 'non-functional requirement', if you will, that a developer should fulfil is to produce code that is readable and easy for another person to understand quickly.  The extra minute or two it takes to understand a simple line of code may seem like nothing, but if this extra time is required to understand a whole chunk of code the time adds up.

Here are a few examples of when and when not to use var.

Example 1


Consider the following code:

Dictionary<string, List<Person>> myDictionary = new Dictionary<string, List<Person>();

Talk about LONG WINDED.  This is clearly a good candidate for var.

                      var myDictionary = new Dictionary<stringList<Person>();

I think we all agree that it it obvious what time the variable 'myDictionary' is.

Example 2

var hobby = person.Hobbies.First("baseball");

This is slightly more ambiguous that the previous example.  What are we returning? Is is perhaps an object of type 'Hobby' or maybe 'IHobby' or what about 'Baseball'?  It is obvious that we are returning something to do with someone's hobby but without knowing the codebase or going and looking inside the Person class we don't know what object we are dealing with.

If there are a string of method calls then avoid assigning the result to a var.

Example 3

var i = 1;
var s = "hiya";

Apart from the fact that I think that 1-character variable names are of the devil (except inside a loop) this is fine. It is obvious that these are an int and string respectively.

Summary

In general, follow your instincts.  I think it is far worse to write ambiguous code overusing var that to be a bit long winded and spell everything out.

It is also worth mentioning that if you are using var, it is generally a good idea to make sure that your variables are named appropriately (though of course you should be doing this anyway regardless of whether or not you are using var :) ). 

A short introduction to delegates in C#

Imagine that you have some code that iterates over a list of ints and prints them.

Now, suppose that you decide that you want your display method to display them in a different way.  You actually want to write your list to a file rather than printing to the console, but you need to be backwards-compatible, so you need to retain the ability to simply print to console.

The first thing that you think of might be to create some sort of Handler object and call the equivalent of the handler.handle() method on it (this is essentially the strategy pattern, if you are interested). This is shown in the following example:

We have classes implementing the IDisplayHandler interface which display objects in different ways.

Example usage is shown below:

Lovely, you say.  Where on earth do delegates come into this?  Well, in C# you can use delegates to do make this solution much simpler.

Introduction to Delegates


Essentially, a delegate is a type which defines a method signature. An instance of a delegate can point to any method with the corresponding signature and delegates are used to pass around methods as parameters.

For example:

public delegate int ExecuteCalculation(int x, int y); 

This defines a method signature which takes in two ints and returns one int. Let's understand this more clearly with a simple example based on our strategy pattern display example above.

Simple Delegate Example


Define a delegate using the delegate keyword.

 private delegate void DisplayIt(object o); 

This delegate will need to point to a method which takes in any object and returns void.

I know a method like this! The plain old Console.WriteLine().

var display = new DisplayIt(Console.WriteLine());

All that remains is to pass it into the Display method which, instead of calling Console.Writeline() explicitly will simply pass the objects to the delegate which in turn calls its 'Invoke' method and VOILA, you have printed to the console.  

The example below shows the complete code:






Monday 26 August 2013

Do you adhere to the Single-Responsibility Principle?

The single-responsibility principle is one of the fundamental principles of object orientated design.  It is the idea that any object, method, variable etc has one purpose and one purpose only.

'Yes', I hear you say, 'I'm a super-duper expert in object-orientated design. I follow this principle and I defy you to find a single part of my code where I haven't followed SRP!'

Well, dear reader, how are your tests?

In my opinion, the SRP should apply to tests as well, meaning that every test should have a point, and one point only. Here is a little example showing a common way to structure tests:

Here is a little MessageListener.java class.  When the a message is received, the onMessage method is called and the messageListener both stores the message and increments a counter of the total number of messages received.


All is beautiful so far.

However here is our MessageListenerTest.java:


What on earth is going on here? This test is not adhering to the SRP as it is clearly testing multiple things.  There are 6 asserts in one test, which should set off alarm bells.  If the messageCount is broken in the message listener, or the message isn't added to the receivedMessages collection etc, then this test will fail and the developer will have to waste time figuring out exactly what went on.  Okay, in this example it's not exactly difficult to understand what is happening, but in more complicated examples this problem quickly becomes apparent.

How about writing the test like this:

Every test method has one distinct purpose which is summed up in the method name.  If a test fails, you can immediately understand what has failed and which part of the code is incorrect.


So, things to look out for in your own code:

- a test method with some code, then asserts, then more code, then more asserts.
- if you break one tiny bit of your application, how many tests fail? If we change one tiny bit and suddenly 20 tests break all over the shop then what is going on? 

Sunday 25 August 2013

Simple JUnit Example Test

This is a simple introduction to using JUnit to unit test classes.

I am writing this post because recently a friend of mine started to dabble in Java and in order to test his code he was fiddling around with a main method and printing expected output etc.  Manual tests like this can seem quick initially, but you can't check everything every time you make a change. Investing half an hour in setting up some tests will save you oodles of time later.

Put JUnit on your classpath

You can manually add it by downloading it from the junit site and in your eclipse project do the following: 

Right click on JRE System Library > Build Path > Configure Build Path > Libraries > Add External Jar. 

Navigate to wherever you have stored the junit jar locally and click okay: it should now be on your classpath (and you should see junit.jar or something similar under 'JRE System Library').

Alternatively you can use a nice dependency management tool like Maven or Ivy.  With Maven you don't even need to do anything - JUnit jars are on the classpath by default when you create a maven project. 

Sample class to Test

 I have a very simple 'Circle.java' class with 1 method to test: 



Using JUnit to write tests

Test methods have the annotation '@Test' above them.  The '@Before' annotation means that that method (in this case the method called 'setup') is called before every class. 

Note that all test methods (ie methods with the @Test annotation must be public, void, and take in no parameters). 


To run this test from eclipse - 
Right click anywhere in the class > Run As > JUnit Test

Boom, done. 







Folder Structure of a Java Project

My favourite way of structuring a Java project is into the following folders (in eclipse: File > New Folder. For the two folders calls 'Java' you should also right click on the folder after it has been created, go to 'Build Path' and choose 'Use as source folder'):

-- src
        -- main
                -- java
                -- resources
        -- test
                -- java
                -- resources

This is basically the maven way of organising projects (if you haven't heard of maven then don't worry about that right now).

What goes where? 

  • src/main/java
    • This is where your Java code will live.  It will be nicely arranged into packages (which I will discuss shortly)
  • src/main/resources
    • As you many have guessed, this is where any files other than .java files can go.  For example, if you are using properties files to configure parameters in your application, you might have a file 'src/main/resources/properties/my-awesome-properties-file.properties'.  
  • src/test/java
    • This is where your tests will go. I usually have the structure of this folder mirroring the structure of src/main/java. For example if you have a class 'Circle.java' in the package 'com.ojha.shapes' in src/main/java, then I would have a corresponding package 'com.ojha.shapes' in src/test/java with a class 'CircleTest.java'. 
  • src/test/resources
    • If, for example, you are writing tests to check you can read in a file correctly or something then you might put sample files for your tests in this folder. Another very popular use case is if you are using Spring and want to separate your test configuration from your application configuration. 
Why should I do this?

- You test code should have nothing to do with your application code and you are reflecting this separation by physically putting the code and resources in separate location. 

- Your tests can mirror the package and class structure of the main code which makes it easier to structure tests logically.

- It is a commonly used pattern in Java projects.  Being a Software Engineer isn't just about making code work but also producing clean, logical, intuitively-understood code bases.


Note that if you create folders and organise your files within eclipse, the same folder structure is reflected in the filesystem. This is not the case in Visual Studio where you can arrange your classes nicely into folders within your IDE, but then they end up in different places on disk (this confused me a lot when I first moved to C#!) 





Thursday 23 May 2013

JAXB with an adapter: Date formatting example

So, moving along from the absolute basics, I will now demonstrate how to add an adapter for formatting.

We had a kennel class which contained a list of puppies.  Each puppy has a birthday and a timestamp when it arrived in the kennel.  These are both of the type XMLGregorianCalendar but I would rather have use Joda LocalDate and LocalDateTime. Therefore I add an adapter which is called when the contents of the <birthday> and <timestamp> tags are unmarshalled.

The DateAdapter.java has two static methods, unmarshal and marshal, which convert a string to a LocalDate and vice versa respectively.


Run it to generate the code:

xjc ../resources/puppy/kennel.xsd -p com.ojha.jaxb.kennel.generated


The DateAdapter generates an Adapter1.java

Monday 22 April 2013

Jaxb: A very simple example from xsd

Converting from xml to Java objects isn't the most fun thing to do in the world, but all need to do it at some point or another.  When I need to, I use JAXB which ships with the JDK.  In this post, I'll show a basic example to illustrate how to generate the Java code from an xsd, then how to unmarshal some xml and finally how to write an adapter to format dates.

Firstly, here is a simple example of a kennel which has puppies in it.  A kennel has a list of puppies and each puppy has a name, date of birth and a timestamp of the time they arrived in the kennel (not sure why these kennel owners need a timestamp but it illustrates the point with times well later :) ).

1. Defining an xsd


The xsd definition looks like this:


2. Run the xjc compiler to generate code


To run it from the command line, I use the following command.  I am running it from src/main/java.  The  -p options tell the compiler which package to put your generated code in.

xjc ../resources/puppy/kennel.xsd -p com.ojha.jaxb.kennel.generated

This generated the package, com.ojha.jaxb.kennel.generated, which has 3 classes in it: Kennel.java, Puppy.java and an ObjectFactory.java

3. Unmarshal a sample xml file


Here is an example xml message:


The following JUnit test demonstrates how to unmarshal the xml.


Output (note that I had to generate a couple of toString() methods):


Kennel [puppy=[Puppy [puppyName=Rufus, puppyBirthday=2000-10-10, timeStamp=2013-04-12T18:30:00], Puppy [puppyName=Jasper, puppyBirthday=2012-09-12, timeStamp=2013-04-12T18:30:00]]]

I told you it would be simple.  The next couple of posts will be marginally more interesting, showing how to add adapters to do things like format the dates and how to generate enums using JAXB.








Sunday 20 January 2013

A Very Brief Summary of Websphere MQ

I'll begin with a basic overview of MQ.  Most of the below is from the IBM WMQ docs .

Queue Managers

A queue manager's job, funnily enough is to manager queues.  Every queue in MQ belongs to one queue manager to whom it is local and who 'manages it'.  This includes the following:

  • ensuring that message are stored safely
  • messages are recoverable
  • messages are delivered once and only once (this is known as the 'assured delivery property' of Websphere MQ. 
Note that the application program and Queue Manager do not have to run on the same machine. 

Types of Queue

Local Queue:

A queue is local is it is owned by the Queue Manager to which the application program is connected.  

Remote Queue:

A queue managed by a different Queue Manager.  It is not a real queue, merely a definition of a queue. Note that you cannot read from a remote queue (only local queues), though you can, of course, write to a remote queue.  This is done bye using a... 

Transmission Queue

This is a special type of local queue which is used to send messages to a remote queue. Note that to send messages to a remote queue a channel is required to connect your Queue Manager and the Queue Manager of the remote queue you are trying to send messages to.  Channels are described later. 

Dead Letter Queue

These are where messages are put if they cannot be sent. Every Queue Manager should have one dead letter queue.  

Message sending may fail for a number of reasons: 
  • destination queue is full
  • destination queue doesn't exist
  • sender is not authorised to put to destination queue
  • message is too large
  • message contains duplicated sequence number
Channel

This is a logical communication link.

The only type of channel I have used is a Message Channel which connects two Queue Managers to allow messages to be sent between queues on these two Queue Managers. 

Note that channels are unidirectional; to define a channel you must specify which Queue Manager is the sender and which is the receiver.  If you want bidirectional communication then you need two channels between the two Queue Managers. 

The other type of channel is apparently a MQI Channel.  



Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...