Getting started with node.js

10 05 2013

Those who are familiar with JavaScript as a client side code now its time to write some server-side java script.

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. More details are here.

Lets write Hello World with node.js

Installation: http://nodejs.org/download/

Writing code (It’s already in node.js website): Create a file name helloWorld.js


var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

open your terminal

>node helloWorld.js

http://127.0.0.1:1337 here is the hello world. Isn’t is simple?

Now its time to write a calculator:

It’s a simple calculator which will add two number and give you the result. Grab the code from github.

https://github.com/atiq21/sample-nodejs/blob/master/calc.js


var http = require('http');
var qs = require('querystring');
http.createServer(function (req, res) {
	console.log("[200] " + req.method + " to " + req.url);

    switch(req.url) {
        case '/':
            res.writeHead(200, "OK", {'Content-Type': 'text/html'});

            res.write('<html><head><title>Simple Calculator</title></head><body>');
            res.write('<h1>Its a simple calculator to add 2 number</h1>');
            res.write('<form enctype="application/x-www-form-urlencoded" action="/formhandler" method="post">');
            res.write('Number 1: <input type="text" name="number1" value="" /><br />');
            res.write('Number 2: <input type="text" name="number2" value="" /><br />');
            res.write('<input type="submit" value="Add"/>');
            res.write('</form></body></html');

	        res.end();
            break;
        case '/formhandler':
            res.writeHead(200, "OK", {'Content-Type': 'text/html'});
            res.write('<html><head><title>Simple Calculator</title></head><body>');

            var body = "";
            var result = 0;
            if (req.method === "POST" &&
                    req.headers['content-type'] === "application/x-www-form-urlencoded") {

                req.on('data',
                          function(chunk) {
                              // append the chunk to the growing message body
                              body += chunk;
                          });

                req.on('end', function() {
                    var params = body.split('&');

                    for (param in params) {
                        var pair = params[param].split('=');
                        result = result + parseInt(pair[1]);
                    }
                    res.write("Result: " + result);
                    res.write('</body></html');
                    res.end();
                });
            }

            break;
        default:
            res.writeHead(404, "Not found", {'Content-Type': 'text/html'});
            res.end('<html><head><title>404 - Not found</title></head><body><h1>Not found.</h1></body></html>');
            console.log("[404] " + req.method + " to " + req.url);
    }
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Now its time to do some real thing. What about a framework. Express is a good framework for web application with node.js. Will explore it in next post.

 





Australia tour some photograph and some memory (Melbourne Night)- part 2

20 01 2012

Australia tour some photograph and some memory (MLIA) – part 1

The seat of Malaysia to Melbourne was much comfortable than Bangladesh to Malaysia. I was so tired that I felt sleep just after fasten the seat belt and woke up when the lunch served. It was a very long journey for about 7 hours. There was no latest movie on the palylist of plane so had to repeat Fast and Furious 4.

You can not take any kind of seed, plant or living thing in Australia. As I was carrying some flute for my friend Mehedi so I mention it in the form they provided during my check-out and got appreciation for that. When I reached hotel it was around 8 p.m. I phoned Mehedi and he came to my hotel at around 10 p.m. Thanks to Mehedi for a wonderful dinner. After doing lunch we went out to enjoy the beauty of Melbourne at night. I was worried about my camera but he assured me that there is no such problem. The weather was very cold at least for me as most of the people was wearing T-shirt. Melbourne at night will be a life time experience for me.

This slideshow requires JavaScript.





Australia tour some photograph and some memory (MLIA) – part 1

20 01 2012

Last Year in September I went to Melbourne, Australia to take part in HIMSS Conference. That was my first time outside Bangladesh so I was really excited. Mehedi (My best friend doing phd at Swinburne ) helped me to complete my Web Check-in form which really helped me at Shah Jalal international Airport.

After taxing for couple of minutes when the plane started to fly there ware some bumping but it became normal within a moment. When the seat belt sign is off I relaxed and looked around myself and found that the passenger beside me is going to Sydney,  Australia to do BBA. Though I did some chit-chat with him but it was a boring journey. After 4 hours of flight, landed at Malaysian Airport. The planning of the Airport really amazed me. They setup the shops in such a way that you have to go through them to go one terminal to another. There ware some accelerator and a train to help the passenger. My first job was to find my departure terminal then I looked around the airport. As the transit was only for 2 hours so I did a quick go through and here are some of the outputs.

This slideshow requires JavaScript.





Going to perticipate JUDCon 2012: India in NIMHANS Convention Center, Bangalore, India

20 01 2012

My 5 colleague and me are going to take part in JUDCon 2012 in India on January 24-25, 2012. JUDCon is a conference “By Developers, For Developers.”

Presentations at JUDCon include a range of technology deep dives into JBoss Community projects and related technical topics of user and developer interest. The JUDCon 2012 program will feature topics which will include the JBoss AS7 app server, Business Rules, Workflow, SOA and Enterprise Application Integration and OpenShift/Cloud – in fact, some of coolest and best technology the industry has to offer.

Therap Migrated from Weblogic to JBoss Applicaton Server recently. We are hoping this conference will help us to adopt other features of JBoss community.





Deploy Grails 1.3.3 in Jboss eap 5.1.1

26 10 2011

Deploy grails in jboss is not an easy task. Will discuss one by one.

1. JNDI Data Source

Create a file named JNDI-ds.xml deployed in JBoss’ deploy directory

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<datasources>
<local-tx-datasource>
<jndi-name>Jndi</jndi-name>
<rar-name>jboss-local-jdbc.rar</rar-name>
<use-java-context>true</use-java-context>
<connection-definition>javax.sql.DataSource</connection-definition>
jboss:service=invoker,type=jrmp
<min-pool-size>2</min-pool-size>
<max-pool-size>10</max-pool-size>
<blocking-timeout-millis>60000</blocking-timeout-millis>
<idle-timeout-minutes>15</idle-timeout-minutes>
<prefill>false</prefill>
<background-validation>false</background-validation>
<background-validation-millis>0</background-validation-millis>
<validate-on-match>true</validate-on-match>
<use-fast-fail>false</use-fast-fail>
<statistics-formatter>org.jboss.resource.statistic.pool.JBossDefaultSubPoolStatisticFormatter</statistics-formatter>
<isSameRM-override-value>false</isSameRM-override-value>
<allocation-retry>0</allocation-retry>
<allocation-retry-wait-millis>5000</allocation-retry-wait-millis>
xsi:type="securityMetaData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<metadata>
<type-mapping>Oracle9i</type-mapping>
</metadata>
<type-mapping>Oracle9i</type-mapping>
<local-transaction/>
<user-name>admin</user-name>
<password>pass</password>
<!-- <check-valid-connection-sql>SELECT * FROM DUAL</check-valid-connection-sql> -->
org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter
<prepared-statement-cache-size>0</prepared-statement-cache-size>
<share-prepared-statements>false</share-prepared-statements>
<set-tx-query-timeout>false</set-tx-query-timeout>
<query-timeout>0</query-timeout>
<use-try-lock>60000</use-try-lock>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<connection-url>jdbc:oracle:thin:@host:port:sid</connection-url>
</local-tx-datasource>
</datasources>
 

Edit grails-app/conf/DataSource.groov

dataSource {
  pooled = false
  driverClassName = "oracle.jdbc.driver.OracleDriver"
  dialect = 'org.hibernate.dialect.Oracle10gDialect'
}

hibernate {
  cache.use_second_level_cache = true
  cache.use_query_cache = true
  cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
}

Edit grails-app/conf/spring/resources.groovy

dataSource(org.springframework.jndi.JndiObjectFactoryBean) {
  jndiName = "java:JndiDS"
}

//if you need jdbc for query
jdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) {
  dataSource = ref("dataSource")
}

2. Remove conflicting jars
Edit grails-app/conf/BuildConfig.groovy

grails.war.resources = {stagingDir ->
    def toRemove = [
          "$stagingDir/WEB-INF/lib/com.springsource.oracle.jdbc-10.2.0.2.jar",
          "$stagingDir/WEB-INF/lib/com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar",
          "$stagingDir/WEB-INF/lib/log4j-1.2.14.jar", // log4j supplied by JBoss
          "$stagingDir/WEB-INF/lib/log4j-1.2.15.jar", // log4j supplied by JBoss
          "$stagingDir/WEB-INF/lib/slf4j-api-1.5.6.jar", // slf4j supplied by JBoss 5+
          "$stagingDir/WEB-INF/lib/slf4j-api-1.5.8.jar", // slf4j supplied by JBoss 5+
          "$stagingDir/WEB-INF/lib/slf4j-log4j12-1.5.6.jar", // slf4j supplied by JBoss 5+
          "$stagingDir/WEB-INF/lib/slf4j-log4j12-1.5.8.jar", // slf4j supplied by JBoss 5+
          "$stagingDir/WEB-INF/lib/jcl-over-slf4j-1.5.6.jar", // jcl supplied by JBoss as well
          "$stagingDir/WEB-INF/lib/jcl-over-slf4j-1.5.8.jar", // jcl supplied by JBoss as well
        // see also Config.grails.logging.jul.usebridge - shouldn't be used
        //     http://www.slf4j.org/legacy.html#jul-to-slf4j
        //          "$stagingDir/WEB-INF/lib/jul-to-slf4j-1.5.6.jar",
        //          "$stagingDir/WEB-INF/lib/jul-to-slf4j-1.5.8.jar",
        // you might want to remove JDBC drivers when using server supplied JNDI...
        //          "$stagingDir/WEB-INF/lib/hsqldb-1.8.0.5.jar",
    ].each {
        delete(file: it)
    }
}

3. Add hibernate-validator-*.jar in lib dir

Enjoy jboss and grails😀





Going to perticipate HIMSS AsiaPac 2011 in Melbourne, Australia

17 09 2011

I am going to take part in HIMSS AisaPac 2011 along one of my colleague . I am very excited about the conference as this is the premier professional member organization exclusively focused on providing leadership for the ideal use of healthcare information technology. Delegates from all over the world like Japan, Germany, Norway, China, Korea, New Zealand, Singapore, Hong Kong and off-course Bangladesh.

This is the first time I am going outside Bangladesh. A bit nervous. Hope participating the conference in the first livable county of the world will be amazing.





Working with csv date

25 08 2011

Working with csv is like a nightmare is you need to import it in Excel and if there is any date in csv. Excel will treat that as string and have to remove the preceding ‘ then change the cell format. If csv is very small then its ok but what about 1000 of row and column.

There is a great tool out there to do this like a charm🙂. Its a open office extension to Convert Text To Number (and date).

1. Download extension: like: http://extensions.services.openoffice.org/en/project/CT2N
2. Tools | Extension manager | Add button.
3. Close Office and reopen it.
4. There should appear new toolbar icon if not then make sure View | Toolbars | CT2N is checked.
5. Mark cells you would like to convert into numbers and click on icon from toolbar to convert to numbers








Follow

Get every new post delivered to your Inbox.