VULab VULAB provides hands on training in IT. Our training areas include Java, J2EE, WebServices, SOA, Spring Framework, Hibernate, Android, Apple IOS, HTML5, Windows 8 Metro, Web Development, Apache, Tomcat, Jboss.....

Posted on 12 May 2012 by Sri Nivas

Websockets with tomcat 7

HTML5Apache tomcat team recently added websocket support to tomcat.
WebSocket is a web technology providing for bi-directional communications channels over a TCP connection.

WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket protocol makes possible more interaction between a browser and a web site, facilitating live content and the creation of real-time games. This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. In this way a two-way (bi-direction) ongoing conversation can take place between a browser and the server. A similar effect has been done in non-standardized ways using stop-gap technologies such as Comet.

In addition, the communications are done over the regular TCP port number 80, which is of benefit for those environments which block non-standard Internet connections using a firewall. WebSocket protocol is currently supported in several browsers including Safari, Firefox and Google Chrome. WebSocket also requires web applications on the server to be able to support it.

Vulab will provide code with example shortly.

0 Comments

Posted on 12 May 2012 by Sri Nivas

Tips and Tricks to write better articles (not coding!!)

Writing tipsRecently I was helping a colleague to write an article for html5rocks. We used tips from Kevin at google to write the article. Use the tips for your own blog or article.

These are the same industrial-strength tips used by 9 out of 10 technical writers. (That one writer who doesn’t follow the rules explains some of the bad docs out there.)

Literary writing and tech writing have their own sets of conventions. Other writing forms are like strolling on meandering paths in a meadow where you’re supposed to take in the words and enjoy them; technical writing is like driving a taxi with a surly passenger who is in a big hurry to get to the airport. The passenger (your reader) would scream colorful words if you decide to take the scenic route.

So here are ten tips to improve your technical writing.

The 10 tips at a glance

Tip 1: Know your audience.

Tip 2: Have a conversation.

  • Pretend you are writing an email to a friend.
  • Use simple words.

Tip 3: Know your goals.

  • Tell them what you’re going to say and then tell them.
  • Wrap up.

Tip 4: Make the organization clear with good headings.

  • Make your headings task-oriented.
  • Use parallel structure.
  • Show sequence.

Tip 5: Assume that your reader has the attention span of a gnat.

  • Get to the point.
  • Bulleted lists are your friends.
  • Break up concepts.
  • Use graphics and charts.

Tip 6: Be consistent.

  • Just pick a word and stick with it.

Tip 7: Write lively.

  • Use the active voice.
  • Use action words (verbs).
  • Let your personality shine through.
  • Avoid Latin.
  • Don’t start a sentence with “There…”.

Tip 8: Be precise.

  • Stay in the present; don’t use future tense.
  • Use the right auxiliary verbs.
  • Keep the pronouns clear.
  • Don’t anthropomorphize inanimate objects.

Tip 9: Explain enough.

  • Explain why you’d want to use anything.
  • Catch the pitfalls.
  • Examples, examples, examples.
  • When saying something odd, back it up.
  • Don’t lie or oversimplify.

Tip 10: Read your own stuff.

  • Read your docs out loud.
  • Get rid of all that dead weight.
  • Test your sample code.
  • Have someone read your work .

But wait, there’s more! click here to read more….

0 Comments

Posted on 12 May 2012 by Sri Nivas

Encryption with java

Java EncryptionSecurity is one of the most important aspect of any web or mobile application. It is a very common practice to encrypt sensitive information like passwords in the database.

Jasypt library is a good and simple solution for any java project to have encryption capability.

Jasypt is a very advanced library with support for integrating with Hibernate, Spring, Spring Security and number of other java frameworks and technologies.

Basic usage example code is as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
...
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(userPassword);
...
if (passwordEncryptor.checkPassword(inputPassword, encryptedPassword)) {
  // correct!

} else {
  // bad login!

}
...

More security: the StrongPasswordEncryptor util class with a much more secure (but slower!) algorithm:

...
StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
String encryptedPassword = passwordEncryptor.encryptPassword(userPassword);
...
if (passwordEncryptor.checkPassword(inputPassword, encryptedPassword)) {
  // correct!

} else {
  // bad login!

}
...

Enjoy your code. Vulab provides hands-on training in java, android, apple ios and many other technologies.

0 Comments

Posted on 12 May 2012 by Sri Nivas

Spring MVC 3 returning JSON to Web User Interface

Spring LogoSpring MVC can return data in the JSON format to your front end. You can use jQuery to make ajax requrest to the MVC controller and controller can return the data in json format. Let us see how this can be acheived.

Assuming you are using Maven for dependency management.
Add this dependency to your pom.xml

1
2
3
4
5
6
7
8
9
10
11
<!-- Jackson Dependencies -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.0.0</version>
		</dependency>

Make sure you have enabled mvc in your configuration as below:

1
2
3
<!-- Enables the Spring MVC @Controller programming model -->
	<mvc:annotation-driven />

In your controller method use the following style of code to return json.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@RequestMapping(value="/testjson.html", method = RequestMethod.GET)
	public @ResponseBody User getUserInJSON() {

		User user = new User();
		user.setActive(false);
		user.setEmail("test@test.com");
		user.setFirstName("test");
		user.setLastName("user");
		user.setUserId(10);
		return user;

	}

@ResponseBody annotations is the most important annotation in the code below. This annotations is making the framework to convert the user object into json format and return to the front-end.

http://localhost:8080/vulab/testjson.html

When you invoke the controller’s method you will get back output in json format as below:

1
{"userId":10,"firstName":"test","lastName":"user","email":"test@test.com","password":null,"active":false,"roles":[],"phone":null,"interests":[]}

For your reference a code snippet from : User.java code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.trainingram.code.domain;
// Generated Mar 1, 2012 8:17:04 PM by Hibernate Tools 3.4.0.CR1


import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;

import javax.persistence.CascadeType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * User generated by hbm2java
 */
@Entity
@Table(name="user"
    , uniqueConstraints = @UniqueConstraint(columnNames="email")
)
public class User  implements java.io.Serializable {

     private Integer userId;
     private String firstName;
     private String lastName;
     private String email;
     private String password;
     private boolean active;
     private Set<Role> roles = new HashSet<Role>(0);
     private Phone phone;
     private Set<Interest> interests = new HashSet<Interest>(0);

    public User() {
    }

    public User(String firstName, String lastName, String email, String password, boolean active) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.active = active;
    }
    public User(String firstName, String lastName, String email, String password, boolean active, Set<Role> roles, Phone phone, Set<Interest> interests) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.email = email;
       this.password = password;
       this.active = active;
       this.roles = roles;
       this.phone = phone;
       this.interests = interests;
    }

Enjoy your code. Vulab provides handson training in spring framework and other technologies.

0 Comments

Posted on 11 April 2012 by Sri Nivas

About Spring Data Projects

Spring Logo

Spring data projects helps with the following aspects:
Building spring applications with noSQL databases like MongoDB, Redis, Riak, Redis, neo4j
Building spring applications using Map-reduce frameworks like Hadoop
Using Cloud based services and relational databases with spring projects.

Spring Data Jpa is a wonderful solution for any project connecting to relational databases. It will reduce the code written as the JPA repositories will provide Query DSL support as well as CRUD functionality for all domain objects mapped to the DB.
These are the full list of advantages:

  • Sophisticated support to build repositories based on Spring and JPA
  • Support for QueryDSL predicates and thus type-safe JPA queries
  • Transparent auditing of domain class
  • Pagination support, dynamic query execution, ability to integrate custom data access code
  • Validation of @Query annotated queries at bootstrap time
  • Support for XML based entity mapping

The same advantages of Spring Data can be utilized for MongoDB, Redis, Riak, Neo4J.
Apache Hadoop is another important project to watch as it will make the Map-Reduce technology much easier to use by removing any framework complexities.

If you are using any relational database, mongoDB, Redis , Riak or Neo4J, consider integrating Spring Data libraries to your project. Spring Data will reduce the amount of code you write as well as bring in a number of good features.

If you are interested in map reduce with Hadoop, please read this excellent post from Costin Leau from Spring Source.

0 Comments

Posted on 10 April 2012 by Sri Nivas

Using new Tomcat JDBC Connection Pool

tomcat

tomcat

org.apache.tomcat.jdbc.pool is the new JDBC connection pool class available in tomcat 7. If you have been using commons dbcp you can try the new JDBC Connection Pool in tomcat and see if you can benefit from its functionality.

There are plenty of advantages of using the tomcat 7 jdbc connection pool as described in the linked document.

As most of the projects use JNDI lookups to get the data source. Let us look at a code snippet of how to configure this in tomcat.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<Resource name="jdbc/TestDB"
              auth="Container"
              type="javax.sql.DataSource"
              factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
              testWhileIdle="true"
              testOnBorrow="true"
              testOnReturn="false"
              validationQuery="SELECT 1"
              validationInterval="30000"
              timeBetweenEvictionRunsMillis="30000"
              maxActive="100"
              minIdle="10"
              maxWait="10000"
              initialSize="10"
              removeAbandonedTimeout="60"
              removeAbandoned="true"
              logAbandoned="true"
              minEvictableIdleTimeMillis="30000"
              jmxEnabled="true"
              jdbcInterceptors=
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
              username="root"
              password="password"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/mysql"/>

If you are creating a stand alone application, you can still use the tomcat connection pool. The connection pool creation only has another dependency, and that is on tomcat-juli.jar. To configure a connection pool in a stand alone project using bean instantiation, the bean to instantiate is org.apache.tomcat.jdbc.pool.DataSource. The same attributes (documented above) as you use to configure a connection pool as a JNDI resource, are used to configure a data source as a bean.

0 Comments

Posted on 09 April 2012 by Sri Nivas

Web application development in the browser (Eclipse Orion) released.

Eclipse foundation has made available Orion tools for the web, on the web.
You can develop future web applications on the web, test them and deploy them on the web to the cloud. Orion uses HTML5 and javascript.

orion

Orion is a very active open source project under the Eclipse top-level project.
Orion’s objective is to create a browser-based open tool integration platform which is entirely focused on developing for the web, in the web. Tools are written in JavaScript and run in the browser. Unlike other attempts at creating browser-based development tools, this is not an IDE running in a single tab. Links work and can be shared. You can open a file in a new tab. Great care has been taken to provide a web experience for development.

orion ide

orion_ide


Try it now and experience the future.

0 Comments

Posted on 09 April 2012 by Sri Nivas

Object pooling in Java and Performance

java-logo
I was recently working on a project in which we came across creating millions of expensive objects in a resource intensive environment. We immediately knew we need to decide on whether to use object pooling or not. So let me first define what is object pooling before we talk about what are the options of object pooling in java.

what is object pooling: An object pool is a collection of objects that an application will create and keep on hand for those situations where creating each instance is expensive. A good example would be a database connection or a worker thread. The pool can be used to check in and checkout resources as required.

In any of your project if you want to use object pooling, please do not try to write your own pooling mechanism and use the tried and tested Apache Commons Pool
Also take a look at object pool pattern.

Coming back to our problem, we could not just start using object pooling. we did create a test harness and used a profiling tool and proved that object pooling was actually giving us a slight performance benefit.

Even after all the effort, we did rule out this slight performance benefit and implemented the solution with out object pooling to follow the “keep it simple” mantra.

Looking at the history of java object pooling used to be very good prior to JDK 1.4 but from JDK 1.5 that advantage is no longer great and try to avoid object pooling for any thing other than for database connection pooling or any similar scenario. Actually object pooling will have negative impacts with the latest JDK.

measure measure measure as measuring and analyzing is the only way you can decide whether object pooling is enhancing or degrading the performance of your process. Try not to rely on speculation or written guidelines as they might have been written for an older version of JDK and no longer hold’s good for the version of JDK that you might be using.

0 Comments

Posted on 07 April 2012 by Sri Nivas

Hibernate Annotations Module no longer required

Since hibernate core 3.6 the Hibernate Annotations module has been merged with hibernate core. You no longer need Hibernate annotations dependency in your maven pom.

Some background from Hibernate guys is as follows:
before hibernate-core 3.5, it was JDK 1.4 compatible, so, to use Annotation, the new feature of JDK 1.5, we had to create a new module, aka, hibernate-annotations. but since we had moved to JDK 1.5 since hibernate-core 3.5, there is no reason to keep hibernate-annotations as a separated module, so, we merged back into hibernate-core.

Also read this blog from Spring source regarding

upgrading to Spring 3.1 and Hibernate 4.1

Tags: ,

0 Comments

Posted on 07 April 2012 by Sri Nivas

Java 8 Java 9 Java 10 What?

java-logo
Quoting for the original article Java won’t curl up and die like Cobol, insists Oracle

These details are provided by Simon Ritter from Oracle former employee of Sun Micro Systems.

Java 8 will be released in middle of 2013.
Java 9 and Java 10 will tackle

Big Data, Multi language interoperability, cloud computing, mobile

Simon was stressing that Oracle is going to keep Java fresh and powerful with lots of features, He said Oracle is working to make sure Java is relevant to building the kinds of mobile- and server-based, web-connected and massively parallel apps that are currently being built.

Will JDK 10 be 100% Object Oriented?

There is a proposal out there to remove primitives support from java from JDK 10. Once this proposal is implemented java will only support creation of objects from classes.

Java SE8 will be designed to run on all mobile devices. There will be significant opportunities for java developers. JDK will also be supporting Java Script using project Nashorn.

Java has been here for 15 years and started with 200 files and now has 4000 files. JDK 8 is heavily moving towards modularity. This will help applications to choose the modules they need from JDK and leave the unwanted features. Oracle is closely working with OSGI to implement modularity in JDK 8.

Good job oracle, keep going.

Tags: ,

0 Comments