Saturday, April 27, 2013

JProwork Ready to Go

JProwork is a Java wrapper for Prowork. 

Prowork itself is an intuitive project management app that makes team collaboration easy. It was launched 2011 at Start-up Weekend in Nigeria. It recently won the Apps4Africa 2012: Business Challenge. 

For more information, check: About Prowork and the team behind it and  How it works.

Overview
JProwork is then a Java wrapper for Prowork’s API. It encapsulates the API calls to Prowork and exposes Prowork’s entities as Java objects to the developer. 

As can be seen below:


It sure would make developing on Prowork faster with Java. 

JProwork has been a weekend project for a couple of weeks now and right now it is done as far as covering the existing Prowork's API is concerned. Just need to put some structure here and there regarding versioning before we can have a first official release. But in the meantime you can grab the Source code from Github and to give it a spin, compile the source, update your class-path as necessary and you should be ready to go:

Dependencies
Jprowork requires Gsona Java library that can be used to convert Java Objects into their JSON representation and also to convert a JSON string to an equivalent Java object.

Roadmap and versioning
Things left to do?

Have a proper versioning structure in place. I plan to go with the format of: <major>.<minor>.<subminor> which, in this case, would translate to  <Prowork's API Version>.<Major Changes in Jprowork>.<Minor and Bugfixes>

Mavenized JProwork and also have it available as Jar files.

Documentation
Documentation is in the code. You can grab a copy of the documentation using Javadoc. A generated Javadoc is also included in the repository.

Do give it a spin ;)


Saturday, April 20, 2013

simpleJsMap


I find having to riddle the Dom with stuffs dirty :(

Just because there is no other way to easily keep stuffs on the client side, we sometimes do this; and it is painful! having to unnecessarily pollute the DOM.

I was in such a situation a couple of months back where I was on a project in which stuffs, AKA. the states of the application were being pushed to the DOM attributes just to keep them.  Dirty!!!

I didn't want to continue doing this, so instead, I rolled up a little thingy that enabled me put my stuff out of the DOM. :)

I called it simpleJsMap.

simpleJsMap is a simple MAP-like implantation that enables me to keep and retrieve my stuffs easily in the memory via keys and values without having to set things in DOM attributes.

This felt a lot cleaner :)

simpleJsMap is on github so it can easily be grabbed, and hopefully, someone apart from myself finds it useful. :)

Getting Started

Include the simplejsmap.js file into your script. The variable simplejsmap would then be available. 
<script src="//path/to/simplejsmap.js" type="text/javascript"></script>
<script type="text/javascript">
// simplejsmap now available
</script>

I am a big fan of pure Javascript first before framework, thus simplejsmap is not dependent on any Javascript framework; not even jQuery :p

So once you have the script included you ready to go.

Function reference


createMap()
var map = simplejsmap.createMap();

Creates the map like object and assigns it to variable map. You always start using simplejsmap by calling this function.

add(key, value)
var map = simplejsmap.createMap();
map.add("key1", "value one");
Adds stuff that needs to be kept. The stuff has a value and is associated with a key. Returns true if successfully added and false if not. If the key is already present, nothing happens and false is returned also. To modify the value of a key that is already added, update() function is used.

key and value can be of any Javascript type.

update(key, value)
var map = simplejsmap.createMap();
map.update("key1", "updated value");
Updates the value already added by a given key.  If the given key exists, its value is updated. If the key is not found, no update operationis done. False is returned instead.

remove(key)
var map = simplejsmap.createMap();
map.remove("key1");
Removes a value accessible via the given key.  If the given key is already in existence, it is removed and true is returned. If not, false is returned.

get(key)
var map = simplejsmap.createMap();
map.add("key2", "Hello World");
var val = map.get("key2");
Gets the value stored via given key.

getLength()
var map = simplejsmap.createMap();
var len = map.getLength();
Returns the number of stuffs/keys that has been added.

getKeys()
var map = simplejsmap.createMap();
var keys = map.getKeys();
Returns all the keys that has been added as an array.


UPDATE
simpleJsMap can now be gotten via bower. Just use "bower install simpleMapJs" to add it to your project.


Friday, April 19, 2013

Callback functions in loops in Javascript

In other to implement the Reddit twitter bot for r/Java (@redditJava) and r/programming (@redditprogrammn), I had to get the lists of entries from Reddit, loop through it and call a function to tweet each item. On successfully tweeting, a call back function is called that stores the id of the item that was tweeted. This list of saved Id is checked every time, before tweeting, in other to prevent double tweeting.

A simple way to get this done is to get the items to be tweeted in a form of an iterable (array or object in javascript), loop through the items and in the loop, put the logic that tweets the item and the call back function.

A pseudo code would look thus:
for (var n=0; n < thingstotweet.length; n++) {
      // tweet function
      Tweet(thingstotweet[n], function(e,r) {
         // the call back function
          //if no error, then save the id of the tweet
          if (!e) {
              Db.save(thingstotweet[n]);
          }
      })
   }

In Javascript, this is a faulty implementation. If you implement such a solution for having callbacks inside a loop you would soon find out that the things gets out of sync. For instance in the tweeting example, one tweet would be sent while a different one would be saved in its place. And the reason is simple: It takes time before the function sending the tweet returns and the call back is called. And since functions call like this in Javascript are non blocking, in the time it takes before the calling function returns and the callback called, the value of n would have changed leading to saving the wrong item. 

For example.
1. Start the loop when n is 0;
2. Tweet the item in index 0 in the thingstobetweet list
3. The tweet function is sending the tweet but it takes a couple of seconds.
4. Value of n increased to 1. Still tweet has not been sent, so call back Is not to be called yet
5. Value of n increased to 2. Still tweet has not been sent, so call back is not to be called yet
6. Value of n increased to 3. Finally the tweet was sent successfully, time to call the callback
7. The call back is called. But n is now 3. So thingstobetweet[3] is saved for a tweet at thingstobetweet[0]

How then do you deal with this? What would be the correct way to implement a task that needs a callback function inside a loop?

There are two ways I normally implement a solution for this specific scenario:

Use Closures

In a previous post I briefly explained closures in Javascript.  Dealing with callbacks in loop is a situation where closures can be put to use. The solution is to create a closure for the tweet function. A pseudo implementation would be thus:
  for (var n=0; n < thingstotweet.length; n++) {
      (function(clsn){
          // tweet function
          Tweet(thingstotweet[clsn], function(e,r) {
              // call back function
             //if no error, then save the id of the tweet
              if (!e) {
                  Db.save(thingstotweet[clsn]);
              }
          });
               
      })(n)
 }

You can check the post on closures in Javascript for more information and why the pseudo code above works.

Use Recursive Function

The other solution is to implement a recursive function.  An implementation would be thus:
 var tweetRecursive = function (n) {
      if (n < thingstotweet.length) {
          // tweet function
           Tweet(thingstotweet[clsn], function(e,r) {
              // the call back function
              //if no error, then save the id of the tweet
              if (!e) {
                 Db.save(thingstotweet[clsn]);
                 tweetRecursive(n + 1);
               }
           });        
       }
  }


  //start the recursive function
  tweetRecursive(0);


The logic to send the tweet is defined as a recursive function.  This works because the function to tweet the next item (the recursive function) is also called in the callback function. This would ensure that there is no out of sync situation and the correct tweet would be saved for the one that was sent.

The only repercussion in this implementation is that it breaks the asynchronous nature as the tweets would be sent in a procedural manner, i.e. one after the other instead of asynchronous fashion.


Saturday, April 06, 2013

Closures are hard? Not really: A simple introduction to closures in Javascript


The concept of closures exists in various programming languages. Javascript is one of such language, and anybody who spends an ample time with it would sooner or later run into situation where using closures is warranted.

But closures are hard? Not really.

So what are closures? From personal experience, giving a detailed pseudo-academic explanation benefits little in really getting the concept; well, at least for me. I realized that even after understanding it, translating that knowledge into practical usage remained a little fuzzy for a while until I had to use it in real projects once or twice after which I sort of formed a personal mental model for it.

So I won’t give a too much detailed explanation. There are tons of posts and articles out there that already did that. I listed some at the end of this post. What I would quickly outline is how I came to understand it to the extent of practical usage.



Sunday, March 17, 2013

Difference Between Protoype and __proto__ in Javascript


So what’s the difference between __proto__ and prototype property in Javascript?


The prototype is used to create __proto__  Simple!

Yes, I know. That statement does not help much in terms of explaining what is going on :) But stick with me, the plan is to make it clear by the end of the post.

So let's dig into explaining this stuff!

The subject of prototype is related to Javascript objects and object creation and relation; so before going further, I recommend first reading Understanding Constructor Function and this Keyword in Javascript as this would provide some basic information that would help in understanding some of the basic concepts needed.


Saturday, March 16, 2013

Understanding Constructor Function and this Keyword in Javascript


Back in 2006 I wrote a post on using constructor functions in Javascript to create objects. This post builds on that post, expounding it a little bit further.

By definition, a constructor function is a normal Javascript function. Nothing more, nothing less. What makes a function a constructor is how it is used. When a function is used in such a way that it can create an object, by calling it with Javascript's new operator, then it becomes a constructor function.


This means all and any function you have in Javascript can be used as a constructor function.

var Person = function () {
  console.log("I am a function");
}
We can call this function normally:
Person(); //prints to the console "I am a function"
console.log(typeof Person) //prints to the console ‘function’
So let’s now use this function as a constructor and create an object:

var bond = new Person();
Now let us confirm that bond is indeed an object:

console.log(typeof bond) //this prints "Object"
Now that is all about Constructor functions.  It is as simple as that: A function that is the same as your normal Javascript function but can be used to create objects.

But you would notice that the object created above is empty (without properties) and maybe of little or no use. Compared to the example given in my previous post, which had properties. 

So how do you actually make an object with some already set properties at creation? Before we go ahead and look at this, its worth mentioning a characteristics of functions in Javascript (apart from this fact that they can be used to create objects).
Functions are first class citizens in Javascript and also Functions can have properties just as objects! Yes just like you add properties to an object, you can do same to a Javascript function.


Friday, January 04, 2013

Now You Know What I Did Last Weekend: @redditJava




I am a regular reader of Hacker news: It’s a great place to discover interesting stuffs. But I don’t go checking http://news.ycombinator.com every now and then, neither do I subscribe to their RSS feed. I get most of the stuffs I read on Hacker news via twitter. There are Hacker news’ bots that I follow on twitter which provides the utility of having *hot* articles tweeted once they have attained a certain number of points or comments. Namely: @newsyc150, @newsyc100, @newsyc50 and @newsyc20.

So recently, when I decided to pay a little more attention to Reddit, the first thing I looked for were twitter bots I can follow that would feed me with interesting contents from Reddit. One nice thing about Reddit, unlike Hacker news, is the fact that Reddit have sub categories or channels which are called subreddits which cater to specific topics. You got subreddits for Politics, Gaming, Movies, Music…the list is almost endless. So I basically was on the lookout for twitter bots for subreddits I may be interested in.

But my searched returned null.

Since I could not find one, I decided to make one for myself. And I decided to make one for the Java subreddits since I recently started playing with the language again. (By the way having the bot track other subreddits is simply a matter of configuration).

The idea is simple enough: get stuffs from Reddit, have a way of getting only the interesting ones based on the number of points and comments, and then tweet only those. Also, make sure you also don’t have the same thing tweeted twice. The content is there, the APIs are there, so I set about getting this done within a weekend.

For this, I used Node.js. Reason? Well, I spend a lot of time with Javascript now, notable because I work with the language at work, building the world smarter customer service app, which enables business to keep more happy customer: Casengo; and since Javascript is very much capable, why not?

It was fun hacking this bot together the last weekend as I also took time to play around with stuffs: For storing information to prevent double tweets, mongoDB was used; this allowed me to get pretty conversant with the idea of document based DB and how it works in mongoDB. I also stumbled on node-supervisor. A handy Node Module which prevented the need to manually stop and start the server on every change in the code. Use node-supervisor to run a node script, it watches for any changes in your file; on change, it automatically reloads the script. This definitely made the development flow smoother.

I also checked up on writing Node Modules while following generally accepted guidelines especially if you want your module to be compatible npm. Also learnt one or two things about setting up mongoDB on AWS’s EC2.

Apart from the obvious Twitter and Reddit API’s I equally got to play around with bit.ly and goo.gl API’s.

And finally once deployed, I used forever to keep the script running. Forever ensures that a node process continuously runs and automatically restarts itself when it exits unexpectedly.

Javascript is definitely a pleasant language to work with. But you could trip if you fail to wrap your head around some of its unique and basic characteristics. First all, it is a Prototyped based OOP language (not class based) it is also event driven and easily supports asynchronous programming. This alone could result in some unexpected behaviour if you do not put these unique characteristics in mind. An example, where one can easily be tripped would be handling asynchronous API calls inside a for loop. (More on this in coming post) You also have things like variable hoisting, scoping, closures, the abstruse this etc., all which may make the language appear weird at first approach.

It was a weekend well spent and would spend some more free time modifying things and perhaps adding more subreddits that catches my fancy. The bot is already up and running by the way and you can follow on twitter here www.twitter.com/redditjava and the code is hosted on github here https://github.com/dadepo/redditTwitterBot.git