Sunday, July 20, 2014

Common Date-Time Operations In Java - Formatting and Parsing Date-Time

In Date and Time With Java, a general overview of date/time related API was given. This post walks through formatting and Parsing Date-Time in Java.


Parsing and Formatting Date and Time.


What is the difference between December, 04, 1984 and 12/04/1984, and 04/Dec/1984 and ... or difference between 13:00hr and 1PM and...

Formating. They all represent the same date and time but are formatted differently.

Formatting date/time values as string, and parsing date/time values expressed in string into objects, are one of the common tasks when dealing with date/time. 

Formatting allows you to take a Java object that represents date or time and convert it into a string represention using a predefined formatting.

Conversely, with parsing, you take date or time values expressed as strings and have it converted it into valid Java date or time objects.

We quickly go over how to accomplish these tasks:

Saturday, July 19, 2014

Date And Time With Java

How do you deal with dates and time in Java and perform common operations like finding difference between two dates or translate dates into a particular string formats?

This post seeks to provide an answer to those questions.

I would start off by giving a brief description of the available date related classes and packages you might encounter on the Java platform and then do follow up posts exploring some of the common date/time operations like how to format date-time, dealing with time zones and locale, finding differences between dates/times etc.

Sunday, July 06, 2014

Hooking Into Container and Bean Life Cycle in Spring.

"What is the difference between BeanFactoryPostProcessor and BeanPostProcesser" This, said one of my colleagues, was part of his interview question, a question to which he promptly replied: "I don't know".

Once you pass the stage of actually getting Spring to work, passing the configuration huddle, in no time, the next couple of things you would probably run into would involve using or hooking into the various life-cycles in Spring and you start seeing things like BeanFactoryPostProcessor, BeanPostProcessor, DisposableBean, InitialzingBean, PostConstruct etc, which all seems to be callbacks mechanism that enables you plug in, somehow, into all the magic going on in Spring.

...And probably just like me, it all starts feeling like too much to grasp...Also, sooner or later, you run into the *Aware sets of interfaces.

Dang! What are all these, How do they fit into the picture? I just want to write a web application, why do I have to grapple with all these what not?

I initially had all these concepts swirling all about without having any concrete mental model to attach them to or a good understanding of what actually is going on. I knew about the @PostConstruct annotation and maybe what it does, I also have come across various *Post Processors and maybe the IntializingBean interface a couple of times, but actually grokking and understanding where they fit did not happen until after spending some time working with other parts of Spring which allowed for a broader view of what is going, helping create some sort of mental model.

Monday, June 09, 2014

How to Autowire a Bean That Requires Constructor Argument In Spring

Spring allows you to inject a managed object (bean) as a dependency into another object via the @Autowired annotation.

For example, if I have a UserService that has a dependency on UserRepository, I can have the UserRepository injected using @Autowired annotation like this:

UserRepository Class...
class UserRepository {
UserRepository () {}
}


UserService Class...
class UserService {

@Autowired
private UserRepository userRepository;

UserService () {}

}

This is done using Field Injection. The same thing can be accomplied using Setter Injection:

class UserService {

private UserRepository userRepository;

UserService () {}

@Autowired // Using setter injection
public void setUserRepository(
UserRepository userRepository) {
this.userRepository = userRepository
}

}


or via Constructor Injection:

class UserService {

private UserRepository userRepository;

@Autowired // Using constructor Injection
UserService (UserRepository userRepository) {
this.userRepository = userRepository
}

}


There are different opinions on which method is "the right way" but since this post is not about that debate. I would point you to this post instead: Why I changed My Mind About Field Injection

Which ever method you choose to use, you are essentially doing the same thing: instructing Spring to supply an object's dependency by using the @Autowired annotation.

But what happens when the Object you want injected in has a constructor that requires an argument?

Making Aliases Permanent


Aliases provides you with short cuts to commands or group of commands.

..For example, instead of always having to type ls -la to get the long listing format of a directory's content, you can set up a short form, say ll and type that instead. You do this via aliases by typing in an open terminal this:

alias ll='ls -la'

It would set up an alias of ll that equates to 'ls -la'. As you see the format of setting up an alias is:

alias alias_name="command"

The only issue with this, is that the alias is lost once you end the terminal session. i.e. once you close the terminal. To make the aliase permanent you need to add it in a place where it gets loaded and available at the start of a terminal session.

The most appropiate place to put the aliases in other to make it permanent is in an hidden file called .bashrc in the user's home directory. Or better still, put it in a file usually named as .bash_alaises and have it refereced from .bashrc

This is straight forward.

with vim ~/.bashrc




and you add the aliases in the .bashrc file as shown above. The other, more prefered way is to create another file, usually named .bash_aliases and put your aliases inside instead.

The reason this works is due to the presence of a code section in .bashrc that loads the content of the .bash_alaises.

The portion of the .bashrc looks like this:


If you do not have this piece of code, feel free to add it.

All this has been easy, straight forward and clear enough. The confusing part to all this, especially if you are new to linux, is the seemingly plethora of other files you can put your aliases in and all mysteriously seem to get the job done.

If you do a google search you may find results that points to other files where you can define aliases. /etc/profile, ~/.profile, ~/.bash_login, .bash_profile

The reason these all seems to work is because they are all special kinds of files that have their contents sourced by the shell at different point in time. Some are sourced at login, some are sourced when the shell is invoked interactively.

To really understand how they all fit, lets go over some basic stuff here:

Friday, April 25, 2014

Configuring Aspect With Spring AOP

tl;dr Using AOP involves you identifying cross cutting concerns (Advice), extracting them out into a separate module and have them called at certain points in your code execution (Join Point) using certain expressions (Point-cut) to select these points where you want your cross cutting concern logic to run. Configuring thus involve telling Spring where your extracted logic is and the point-cut required to know where to apply them.

This post is part of the Configuring Spring Series.

Develop a sizable application and you would soon find yourself repeating some operations: certain logic; function calls that keeps recurring now and then. An example of such a recurring operation is logging. At different places, through out your application, you may find the need to have some information logged; either for debugging purposes or for auditing or for whatever reasons logging was invented. After a while you would soon find out that the log calls are sprinkled about the place in your code base. Not good.

I have worked on a code base where this was the case. This is generally not advisable for various reasons: One, it fast become tedious having to repeat the same boring logic over and over again. Two, it leads to code entanglement as you have the flow of business logic being interrupted by mundane things that does not add to the business logic at hand. Third, it leads to code scattering. Same logic scatted all over the place. Even though the logic might be encapsulated into a method or function call, the method or function call would still be scattered all about the place. Not too good.

The explicitly of having to repeat these recurring calls might seem like a good thing, but with scale, it becomes not that much of a good thing.

Would it not be nice if it were possible to extract out, these recurring method calls, have it in some sort of separate module and then have it magically called when those operations that require them are reached during your code execution?

These kind of problems/situations is what Aspect Oriented Software Development seeks to solve/mitigate with Aspect Oriented Programming. It allows you to extract operations that cut across different aspect of your application and have them called when needed.

These kind of operations are usually called cross-cutting concerns, because, well they cut across various concerns in your application. :)

Apart from logging, operations that you would most likely run into, that can easily be classified as being cross-cutting concerns includes: Authorization, Error Handling, Performance Monitoring etc.

This post describes the process of configuring Spring framework in other to be able to use AOP in your application. As you might have guessed, the topic of Aspect Oriented Programming is a very broad one. And since these post are mainly focused on configuration activities in Spring, I would not go into details of programming with Aspects; but instead explain basic concepts needed to get started and provide an overview of how AOP can be configured in Spring Application.

If you are familiar with event driven languages like Javascript (or any UI framework in most languages), you won't be totally wrong if you think the concept of Aspect sounds very familiar to what you do when you define functions as event handlers. And with event delegation, you can have this function registered to be executed when certain operations/event occurs within your application. The same reason why doing this makes sense also applies to why Aspects are recommended.

So let's get started with some of the basic concepts.

Saturday, April 19, 2014

A Tale of Bicycles, Complex and Stereotypes

"You Africans please listen to me as Africans...and you non Africans, listen to me with open mind"

So began Fela Anikulapo Kuti in Shuffering and Smiling before he lunched into a musical rendition that describes a reality only mostly Africans might be able to relate with...

And in that same spirit, I write this post...

Of late I have become more acutely aware of certain thought patterns the social system I live in has unconsciously etched in my mind. And it reeks of acceptance of stereotypes and of inferiority complex.

I would explain with a story involving bicycles...

You Nigerian? Do you remember when one minister proposed the idea that we should all start riding bicycles?

I remember and I remember my reaction it. It was that of disgust, disdain and incredulity.

Why? my God, we are in the twenty something century! Keke? This guy wants to take us to the stone age! Why do these leaders like to make us look so backwards! Imagine! Just look to the "developed countries" (whatever that means)...they have moved past riding bicycles! This dude wants to take us back! Uncivilized, uneducated baga! So we would now be the backward African country these "developed people" would now start looking down on as the place where everybody rides bicycles: the primitive transportation machine? How do this people get to become leaders sef...?

State of mind? Disdain!

Then I went to Togo and spent about 3 months working there. And saw that a large amount of the populace goes about on bicycles and scooters...I viewed this with a mixture of amusement and disdain. But not only these, there was some smugness also. See them...backward African country...even for 9ja, we don pass this stage. How can you be riding "keke" all about the place? So Ara'ko-ish!

State of mind? Smugness and disdain!

Only for me to get to the Netherlands and discover there are more bicycles than people.

And people jolly well go about their daily life using bicycles. It is not a strange sight to see people all dressed up in their suit and tie with their briefcase, riding their bicycles to work. It is no strange sight to see mothers strap their babies to a seat that has being specially attached to the back (or sometimes front) of the bicycle.

Just Google Dutch people riding bicycles.

...And all of a sudden riding bicycles stopped being uncivilized or backwards! In fact it is something to recommend! Look, it is nice on nature, you don't want to continue harming our dear planet Earth with all these locomotives that emits dangerous chemicals? With bicycles, you don't get to emit any of such, so it helps us fight this global warming thing.

And also, it is soooo good for the heart! You know, cycling is good exercise and helps keep body and heart in good shape!

State of mind? Let's do it!

Gbam!

What changed? The people riding the bicycle!

It is quite shocking and sad to observe how my emotional reaction towards the idea of riding bicycles moved from utter disgust and disdain to one of admiration and commendation to the point of recommendation due to the type of people involved.

It is a different thing if my initial negative reaction to populace adopting the bicycle as a prominent mode of transportation was based on valid points. Perhaps something in those locality that makes bicycle riding ineffective? costly? But no, that was not the case.

When I shared this with a very good friend of mine, he made the following statements

...One May question the mediums through which we rationalize some of these things- and how societies have ebbed some systematic prejudice to how we view things. We are all guilty, to strive beyond it has to be a conscious decision that is by no means easy...

There are different angles to this observation and a quick look at history can help explain why things are currently the way they are. But it is quite jarring how the world we live in and its social structures affects the stereotypes we end up holding of the world around us and most importantly of ourselves. The harmful thing with these inclinations is that it could go unnoticed. An unconscious lens set up inside our minds, through which we now view the world.

It is also harmful when you consider the implication. When you have a situation where a societies' choice of solutions to their problems, when a societies identity etc are all unconsciously measured and framed against a mental yardstick of what we think some people from another society entirely would think of it, then we have an insidious problem at hand.

Where then is self determination. self identity, self realization? Where then is the ability to look inward, tackle your problems squarely and apply solutions as needed? Just as needed.

It would be good for my people to stop, take a while and try to be introspective and observe some of our reactions to things around us; how we frame our problems, how we frame our identity, how we consider the solutions we think is cool and see if it does not suffer from this unconscious tainting...

As my friend said. "...to strive beyond this state, has to be a conscious decision..."

And with that, I end with the words of another conscious musician: Bob Marley...emancipate yourself from mental slavery, none but ourselves can free our minds.