Basic Concepts of Node.js (Server Side JavaScript)

As Wikipedia states: “Node.js is a packaged compilation of Google’s V8 JavaScript engine, the libuv platform abstraction layer, and a core library, which is itself primarily written in JavaScript.” Beyond that, it’s worth noting that Ryan Dahl, the creator of Node.js, was aiming to create real-time websites with push capability, “inspired by applications like Gmail”. In Node.js, he gave developers a tool for working in the non-blocking, event-driven I/O paradigm.

In this post i will demonstrate some of the basic concepts of Node.js using which you can start server side coding using javascript.this tutorial assume you have a basic knowledge of javascript. please install node.js in your system prior going through the code snippets below. once you have the environment setup save the code in “[Name].js” and to run it open the command prompt and type the following command
node [Name].js as simple as that.

The below code demonstrate how to open a file from the file system and displaying its statistics. also the below code tells the given file is a file or not.

var fp = require("fs");

/**
 * getting file statistics. 
 */
fp.stat('NodeTestFile.txt',function(error,stats){
	if(error){
		throw error;
	}else{
		console.log('NodeTestFile.txt is a file:'+stats.isFile());
		console.log(stats);
	}
});

now its time for us to read a file’s content in bytes and display it in console.

/**
 * reading file content in bytes.
 */
fp.open('NodeTestFile.txt','r',function(err,fd){
	if(err){
		throw err;
	}else{
		var readBuffer = new Buffer(1024);
		bufferOffset = 0;
		bufferLength = readBuffer.length;
		filePosition = 0;
		fp.read(fd,readBuffer,bufferOffset,bufferLength,filePosition,function read(err,readBytes){
			console.log('just read ' + readBytes + ' bytes');
			if (readBytes > 0) {
			console.log(readBytes);
			}
		});
	}
});

Now if we need to read the content from file and display it con console(not as bytes), below is the code

/**
 *	reading file content
**/
fp.readFile('NodeTestFile.txt',{encoding: 'utf-8'},function read(err,data){
	if(err){
		throw err;
	}else{
		console.log(data);
	}
});

as we are done with reading of file, lets us take a chance to write back to the file, please follow the below code to write the content to the file

/**
* Writing the content back to file
**/

fp.open('NodeTestFile.txt','a',function opened(err,fd){
	if(err){
		throw err;
	}else{
		var writeBuffer = new Buffer('content from Buffer'),
		bufferPosition = 0,
		bufferLength = writeBuffer.length,filePosition = null;
		fp.write(fd,writeBuffer,bufferPosition,bufferLength,filePosition,function wrote(err,data){
			if(err){
				throw err;
			}else{
				console.log("content written to file");
			}
		});
	}
});

so here ends our concepts on file handling, now ill show how to create simple http server using node.js.

/**
 * 
 */
var http = require('http');

http.createServer(function handler(req, res) {
		
	res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end("Hello Node JS\n");
    
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

once the above code is saved in file please run from command prompt and open the browser and hit the url you will be seeing “Hello Node JS” in the browser. there is little to take about the code above as you see the very first statement “require(‘http’)” is called the module loading by node.

so far we have covered node.js interacting with file system and http requests by creating http server, now its time for us to make node.js to interact with database.

/**
 * New node file, with database connectivity and handling
 */
var db = require('mysql');
var connection = db.createConnection({
	host : "localhost",
	user : "username",
	password : "password"
});

connection.connect(function(error, result) {
	if (error) {
		console.log('Connection Error: ' + error.message);
		return;
	}
	console.log('Connected to MySQL Database');
	clientReady(connection);
});

clientReady = function(connection) {
	connection.query("use test", function(error, result) {
		if (error) {
			console.log('Connection Error: ' + error.message);
			return;
		}
		console.log('Ready to fetch the results...');
		fetchResults(connection);
	});
};

fetchResults = function(connection) {

	var strQuery = "select * from country";
	connection.query(strQuery, function(err, rows) {
		if (err) {
			throw err;
		} else {
			console.log(rows);
		}
	});
};

thats all folks on the basics of node.js.
Happy coding Node.js 🙂

Calling C Code from Java

Hello All, over this week end one of my friends asked me to call a C Code from Java, As C has got its own advantages in programming domain, in fact i am a java developer but personally feel “C is Powerful than Java in some aspects”.
Now in this below tutorial i will demonstrate how to call “C code”(Native code) from java Using one of the popular API of java called “JNI”(Java Native Interface).

First of all lets start with the java code as below.

public class JavaToC {
	
	public native void helloC();
 
    static {
        System.loadLibrary("HelloWorld");
    }
 
    public static void main(String[] args) {
        new JavaToC().helloC();
    }
}

Once we have java code let us follow the below steps:

  • Lets make use of the standard tool provided in jdk called ‘javah’, used for generating the header file from java code
  • use the generated header file in the subsequent C code
  • before generating the header file, please compile the java file
  • use : javah JavaToC

the generated header file looks as below.

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JavaToC */

#ifndef _Included_JavaToC
#define _Included_JavaToC
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JavaToC
 * Method:    helloC
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JavaToC_helloC
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

Now its time for us to code the C source file as below.

#include <stdio.h>
#include <jni.h>
#include "JavaToC.h"
JNIEXPORT void JNICALL Java_JavaToC_helloC(JNIEnv *env, jobject javaobj)
{
  printf("Hello World: From C");
  return;
}

Please note the below are few points regarding the above C Code.

  • stdio.h is the standard C header file include.
  • jni.h is the bridge header file between the java and C languages, also its available in standard jdk
  • Please note that you can see JavaToC.h file after you issue javah JavaToC command

Now, the major thing comes here, to access C Code from java we need to make the C Code as a shared Lib, inorder to do this we need to hava C Compiler already installed in our system. There are many C Compilers available in market as Turbo C, Cygwin MingW, Tiny C etc, for now i used Tiny C in this example. Here are the instruction to Download and generate the Shared Lib using Tiny C.

  • Please Download the Tiny C from here
  • Unzip the file and set OS path to tcc.exe
  • tcc HelloWorld.c -I D:\Java8\jdk1.8.0_05\include -I D:\Java8\jdk1.8.0_05\include\win32 -shared -o HelloWorld.dll
  • The above command is used for generating the shared Lib (.dll), also the above command is argumented with two folders which contain jni.h and jni_md.h file from standard jdk

Thats all folks, if you are set and every thing went smooth, now its time to call Java code using “Java JavaToC”.
finally the output is as follows.
OP

Happy JNI 🙂

Calling REST Services using Spring’s REST Template

Hi guys, here is my 80th blog post which talks about calling Restful service using Spring’s “RestTemplate”. This codebase is executed under Spring 3.1 and 4.0 dependencies. The project structure looks as shown below.
RestTemplate_proj_struct

let me explain one scenario here, the calling REST service can return JSON Object or an XML Document back to consumer. it si up to the implementation how to convert JSON back to Java Object or convert Xml Back to Java.
We have many Marshallers and UnMarshallers available some of them are Jaxb2Marshaller,Jibx Marshaller, XStreamMarshaller,XmlBeanMarshaller..etc, i personally used Jaxb2Marshaller in this project. let us now dive into the code, there is no much explanation needed in the code, please follow the comments over the code blocks.

ConfigUtil.java

/**
 * 
 */
package com.spark.spring.rest.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.client.RestTemplate;

import com.spark.spring.rest.models.Customer;

/**
 * @author PavanKumar Mantha
 * 
 */
@Configuration
public class ConfigUtil {

	/**
	 * @return the RetTemplate Object. This method sets the marshaller object as
	 *         params to RestTemplate leveraging the marshalling capability to
	 *         the template.
	 */
	@Bean(name = "restTemplate")
	public RestTemplate getRestTemplate() {
		RestTemplate restTemplate = new RestTemplate();

		List<HttpMessageConverter<?>> converters = new ArrayList<>();
		converters.add(getMarshallingHttpMessageConverter());
		converters.add(new FormHttpMessageConverter());
		converters.add(new StringHttpMessageConverter());
		restTemplate.setMessageConverters(converters);
		return restTemplate;
	}

	/**
	 * @return MarshallingHttpMessageConverter object which is responsible for
	 *         marshalling and unMarshalling process
	 */
	@Bean(name = "marshallingHttpMessageConverter")
	public MarshallingHttpMessageConverter getMarshallingHttpMessageConverter() {

		MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter();
		marshallingHttpMessageConverter.setMarshaller(getJaxb2Marshaller());
		marshallingHttpMessageConverter.setUnmarshaller(getJaxb2Marshaller());
		return marshallingHttpMessageConverter;
	}

	/**
	 * @return Jaxb2Marshaller, this is the Jaxb2Marshaller object
	 */
	@Bean(name = "jaxb2Marshaller")
	public Jaxb2Marshaller getJaxb2Marshaller() {
		Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
		jaxb2Marshaller.setClassesToBeBound(Customer.class);
		return jaxb2Marshaller;
	}
}

RestServiceConsumer .java, RestService call

/**
 * 
 */
package com.spark.spring.rest.consume;

import org.springframework.web.client.RestTemplate;

import com.spark.spring.rest.models.Customer;

/**
 * @author PavanKumar Mantha
 *
 */
public class RestServiceConsumer {

	/**
	 * @param restTemplate, this is the exact call to the service
	 */
	public static void consumeService(RestTemplate restTemplate){
		// getting xml directly from the response as string
		String xml = restTemplate.getForObject("http://www.thomas-bayer.com/sqlrest/CUSTOMER/18/", String.class);
		System.out.println(xml);
		
		// unmarshalling xml string to java object using Jaxb
		Customer customer = restTemplate.getForObject("http://www.thomas-bayer.com/sqlrest/CUSTOMER/18/", Customer.class);
		System.out.println(customer.getFirstName());
	}

}

Customer.java, Jaxb mapping POJO

/**
 * 
 */
package com.spark.spring.rest.models;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author PavanKumar Mantha
 * 
 */
@XmlRootElement(name="CUSTOMER")
public class Customer {

	private String id;
	private String firstName;
	private String lastName;
	private String street;
	private String city;

	/**
	 * @return the id
	 */
	@XmlElement(name="ID")
	public String getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	@XmlElement(name="FIRSTNAME")
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	@XmlElement(name="LASTNAME")
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the street
	 */
	@XmlElement(name="STREET")
	public String getStreet() {
		return street;
	}

	/**
	 * @param street
	 *            the street to set
	 */
	public void setStreet(String street) {
		this.street = street;
	}

	/**
	 * @return the city
	 */
	@XmlElement(name="CITY")
	public String getCity() {
		return city;
	}

	/**
	 * @param city
	 *            the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}

}

Main Method

/**
 * 
 */
package com.spark.spring.rest.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.client.RestTemplate;

import com.spark.spring.rest.config.ConfigUtil;
import com.spark.spring.rest.consume.RestServiceConsumer;

/**
 * @author PavanKumar Mantha
 *
 */
public class TestRestApp {

	/**
	 * @param args
	 */
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConfigUtil.class);
		RestServiceConsumer.consumeService((RestTemplate)applicationContext.getBean("restTemplate"));
	}

}

finally when we run the main method you should see the below output on the screen.
console

Happy RESTing…(RestTemplate) 🙂