Simple Example of Event Emitters in Node.js

Very similar to the pub-sub or observer/listener pattern where events are triggered upon a particular action.

 

var fs = require('fs'); // get the fs module
var EventEmitterVar = require('events').EventEmitter, util = require('util');

var exampleEventEmitterClass= function () {
    console.log("emitter constructor");
}
util.inherits(exampleEventEmitterClass, EventEmitterVar);  //register class as emitter

exampleEventEmitterClass.prototype.emitMethod1 = function () {
    this.emit('emittedevent1');
} ;

exampleEventEmitterClass.prototype.emitMethod2 = function () {
    this.emit('emittedevent2');
}  ;

//register events
var evtEmitInstance = new exampleEventEmitterClass();
evtEmitInstance
    .on('emittedevent1', function () {
    console.log('Executing Event Emitter 1');
})
    .on('emittedevent2', function () {
        console.log('Executing Event Emitter 2');
    }
);

for (var i = 0; i < 3; i++) {
    evtEmitInstance.emitMethod1();
}

for (var i = 0; i < 3; i++) {
    evtEmitInstance.emitMethod2();
}

Setting up Yoeman (Compass and Sass)

Yoeman is a scaffolding and workflow platform for developing modern (HTML5) webapps. In a rough sense, it is to Node.js what Rails is to Ruby. When setting this up on my ubuntu based workstation, I ran into a few conflicts installing Compass and Sass (possibly because of conflicts between the “apt” and “gem” environments. Eventually, I backed out my ruby, compass, and sass installs and re-installed them via the following commands. Post install, “grunt serve” and “grunt test” worked without complaining about compass not being in the path etc.

sudo apt-get install ruby-full rubygems1.8

sudo gem install sass

sudo gem install compass
 

 

Decent dark theme (light text on dark background) finally available for eclipse.

I’ve been using intellij for a while now and usually cringe a bit whenever I need to use eclipse. One of my big issues with eclipse has been their atrocious support for dark themes (helpful to those of us who value our eyesight). I’ve tried various plugins in the past and have usually come away dis-satisfied (bad colour schemes, file navigator refuses to comply to the theme etc).

However, I’ve come across one plugin that seems to work okay (at least on my mac). It looks to be a clone of the intellij “darcula” theme and can be found at https://github.com/rogerdudler/eclipse-ui-themes .

Note that this plugin merely affects the eclipse ui framework windows (the file navigator etc). To change the color themes for the actual code windows, you will need another plugin such as http://eclipsecolorthemes.org/?view=plugin

Big thank you to the author.

A cyclic iterator

Sometimes, a cyclic iterator can be useful to supply an endless supply of deterministic data. Here’s an simple implementation that I wrote today.


import java.util.Iterator;

/**
 * This class iterates across an iterable object with the option to recycle amongst the elements infinitely.
 * In case the recycle option is not set, the original data is iterated upon once, and all subsequent calls to
 * next() will return the defaultDataValue
 *
 * @param <T>
 */
public class CyclicIterator<T>
 implements Iterator<T> {
 final private Iterable<T> data;
 final private boolean recycleData;
 final private T defaultDataValue;
 private Iterator<T> dataIterator;

public CyclicIterator(Iterable<T> data, boolean recycle, T defaultDataValue) {
 this.data = data;
 this.recycleData = recycle;
 this.defaultDataValue = defaultDataValue;
 resetDataIterator();
 }

private void resetDataIterator() {
 this.dataIterator = this.data.iterator();
 }

@Override
 public boolean hasNext() {
 return true;
 }

@Override
 public T next() {
 //if the iterator is done, check whether to reset or not
 if (!dataIterator.hasNext()) {
 if (recycleData) {
 resetDataIterator();
 } else {
 return defaultDataValue;
 }
 }

//at this point, next should be valid
 return dataIterator.next();
 }

@Override
 public void remove() {
 //NO-OP
 }
}

Testing for Equality using reflection

This utility tests for equality using reflection. Saves you from getting carpal tunnel by  writing multiple lines of the form

assertThat(result.getFoo(), is(equalTo(item.getFoo())));

Here’s the source. Modify as needed

public class MappingTestUtility {

public static void assertEquals(Object input, Object result) throws IllegalAccessException {
 assertThat(result, is(equalTo(input)));
 final Field[] fields = input.getClass().getDeclaredFields();
 for (final Field field : fields) {
 field.setAccessible(true);
 assertThat(field.get(input), is(equalTo(field.get(result))));
 }
 }
}

Implementing PUT REST requests when using Spring RestTemplate

Spring’s RestTemplate.put(…) method returns a void. Why is this a bother? One reason is to capture PUT response information and make logical decisions based on that data.

As it turns out, The RestTemplate’s exchange method can be used to implement the PUT request using the following snippet. It’s not complete code but enough to the point where it should be self explanatory


public boolean putIndex(String id) throws Exception {
 final String endpoint = endpoint("index/{id}");

HttpHeaders requestHeaders = new HttpHeaders();
 List <MediaType> mediaTypeList = new ArrayList<MediaType>();
 mediaTypeList.add(MediaType.APPLICATION_JSON);
 requestHeaders.setAccept(mediaTypeList);
 requestHeaders.setContentType(MediaType.APPLICATION_JSON);
 HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

 // Create the HTTP PUT request,
 ResponseEntity<Object> response = operations.exchange(endpoint, HttpMethod.PUT, requestEntity, null, id);
 if (response == null) {
 return false;
 }
 return HttpStatus.CREATED.equals(response.getStatusCode());
 }