Wednesday 31 December 2014

Basic Operations in MongoDB


Below are various MongoDB statements.

Three database commands you should know.
show dbs – List all databases.
use db_name – Switches to db_name.
show collections – List all tables in the current selected database.


MongoDB Installation On Windows

In this tutorial, we will show you how to install MongoDB on Windows7 step by step.
  1. MongoDB 2.2.7
  2. Windows 7
Download the binary for your operating system from official site.

            http://www.mongodb.org/downloads

MongoDB Introduction

MongoDB  is an open-source document database, and the leading NoSQL database. Written in C++, with many great features like map-reduce , auto sharding, replication, high availability and etc.

Thursday 28 August 2014

Spring Data MongoDB Hello World Example

In this Post we will see how to Integrate Spring Data + MongoDB + Maven step by step.
To integrate Spring with MongoDB we require Spring Data and Mongo DB jars.

Java + MongoDB Hello World Examle

A simple Java + Maven  + MongoDB  hello world example.

In this Post we will see step by step how to connect MongoDB, create database, collection and document, save, update, remove, get and display document.



Wednesday 6 August 2014

How to generate MD5 Hash in Java


There are multiple ways to generate MD5 hash in Java Program. Not only Java API provides convenient method to generate MD5 hash, you can also use popular open source frameworks, like Spring and Apache commons Codec to generate MD5 digest in Java.

 MD5 is popular Message Digest Algorithm, which is most commonly used to check data integrity e.g. comparing MD5 check-sum to see, if any file is altered or not. Though, MD5 was not considered a good cryptographic algorithm for security purpose due to several vulnerability found on it, it's still good enough or cheking integrity of file. 

How do I encode URL parameters

When using the GET method, parameter names and their values get submitted on the URL string after a question mark. Different parameter name/value pairs are separated by ampersands.

However, what happens if the parameter value in the URL string has a space or some other special character? Submitting an HTML form will result in special characters being automatically converted to special codes for us. However, sometimes it is necessary to encode these characters without the aid of an HTML form. Java  has a class called URLEncoder that can encode these characters so that they are properly handled. The encode method takes two parameters, the string to be encoded and the encoding scheme. Unless you're smoking crack, you probably want the encoding scheme to be "UTF-8".

How to read a properties file with a Resource Bundle

A ResourceBundle offers a very easy way to access key/value pairs in a properties file in a Java.
ResourceBundle class is used to internationalize the messages. In other words, we can say that it provides a mechanism to globalize the messages.

The hardcoded message is not considered good in terms of programming, because it differs from one country to another. So we use the ResourceBundle class to globalize the massages. The ResourceBundle class loads these informations from the properties file that contains the messages.

Tuesday 5 August 2014

Find Out Your Java Heap Memory Size

In this article, we will show you how to use the -XX:+PrintFlagsFinal to find out your heap size detail. In Java, the default and maximum heap size are allocated based on this – ergonomics algorithm.


Heap sizes
Initial heap size of 1/64 of physical memory up to 1Gbyte
Maximum heap size of 1/4 of physical memory up to 1Gbyte

Spring MVC And Excel File

In this Post we will see step by step use of AbstractExcelView class in Spring MVC application to export data to Excel file for download.

In this sample we are going to export data to Excel file via Apache POI library.



Monday 4 August 2014

Java Virtual Machine Internals

This article explains the internal architecture of the Java Virtual Machine (JVM). 






Sunday 27 July 2014

Examples on String Class in Java

In this post we will see some examples on String Class in java

How to reverse a String


public class StringReverseExample{
   public static void main(String[] args){
      String string="abcdef";
      String reverse = new StringBuffer(string).
      reverse().toString();
      System.out.println("\nString before reverse:
      "+string);
      System.out.println("String after reverse:
      "+reverse);
   }
}

Stuff about String class

In this Post we will discuss about some important concepts of String Class in Java.

Memory leak issue


 Have you tried creating substrings from a string object. Do you know the internals of substring in java. How they create memory leaks?

Sorting a Map In Java

In this Post we will see how to sort Map by its keys and by values.


1. Sort a Map by Keys

Uses TreeMap, and keys are sorted automatically.

SortMapOnKeyExample.java

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortMapOnKeyExample {

Identify Duplicated Items In Java List and count

The Below example show you how to count the total number of duplicated entries in a List, using Collections.frequency and Map

Saturday 26 July 2014

Collections Looping Example

Concept of the Iterator
An iterator is an object that enables us to traverse a collection. There is an iterator (java.util.Iterator) in all the top level interfaces of the Java Collections Framework that inherits java.util.Collection interface. These interfaces are java.util.List,java.util.Queue, java.util.Deque, and java.util.Set. Furthermore, there is the java.util.Map interface that does not inheritjava.util.Collection.

Sorting List Collections Examples

In Java, it’s pretty easy to sort elements in a list collection using the Collections.sort() static utility method. This method has two forms as follows:
    • void sort(List<T> list): sorts the list into ascending order according to its elements’ natural ordering.
    • void sort(List<T> list, Comparator<? super T> c): sorts the list into the order specified by the given comparator.
Behind the scenes, the sort operation uses a merge sort algorithm which is slightly optimized to be fast and stable:

Lambda - Collections Comparator Example

The following examples illustrate how to use Lambda expressions - the main feature coming with Java SE 8 - to improve the boilerplate code of comparator written for sorting list collections.

Examples for enum type

The enum keyword is used to declare a new enumeration type. This keyword has been introduced since Java 5. The declaration syntax for an enum type is as follows

How to make a java class immutable

An immutable class is one whose state can not be changed once created. There are certain guidelines to create an class immutable. In this post, we will revisit these guidelines.

Here we will Discuss below sections
  • Benefits of making a class immutable
  • Guidelines to make a class immutable

Friday 18 July 2014

How To Bypass Certificate Checking In A Java Jersey WebService Client


How To Bypass Certificate Checking In A Java Jersey WebService Client


To Turn Off Certificate Validation in Java HTTPS Connections 
This can be done by replacing the default SSL trust manager and the default SSL hostname verifier.

Here’s a source code for Java Web Services which is used to by pass all the certificate and hostname checking. 
A very useful code in testing environment ONLY.

How to get Client IP Adress in Java

Simply getting the IP of the remote client in Java is an easy task. Assuming we have a request instance, we can simply invoke the “getRemoteAddr” method

servletRequest.getRemoteAddr() 


But, if user is behind a proxy server or access your web server through a Load balancer (for example, in cloud hosting), the above code will get the IP address of the proxy server or load balancer server, not the original IP address of a client.

To solve it, you should get the IP address of the request’s HTTP header

Sunday 13 July 2014

Sorting a list by multiple attributes example

There are several ways in order to sort a list collection by multiple attributes (keys) of its elements type. For example, sorting a list of employees by their job title, then by age, and then by salary.

In this article, we are going to discuss using a CompareToBuilder class of the Apache Commons Lang library.

Friday 30 May 2014

spring mvc internationalization example

Internationalization (i18n) support in spring mvc example tutorial

 Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. The term is frequently abbreviated as i18n (where 18 stands for the number of letters between the first i and last n in internationalization). Above definition essentially means making changes in your application such that it should be usable in multiple locales (or languages in simple words).

In this Post we will see step by step implementation of Spring with internationalization.

Wednesday 28 May 2014

Spring Jersey Rest Service Example

Spring Integrated with Jersey Restful Service Example

In this Post we will see how to integrate Jersey rest service with Spring Framework step by step.


Monday 12 May 2014

Exception Handling in Spring MVC

Exception Handling in Spring MVC using SimpleMappingExceptionResolver.

Spring has long provided a simple but convenient implementation of HandlerExceptionResolver - the SimpleMappingExceptionResolver. It provides options to:
  • Map exception class names to view names - just specify the classname, no package needed.
  • Specify a default (fallback) error page for any exception not handled anywhere else

In this Post you can get simple example on  SimpleMappingExceptionResolver step by step.

Wednesday 5 March 2014

Spring Security access control + Customize Acces Denied Page Example

In this Post We will check how to implement access control or authorization using spring security. and customizing 403 Access Denied Page.


In below example you can find step by step to implement access control or authorization and customizing 403 Access Denied Page in Spring.


Thursday 27 February 2014

Maven Spring MVC Cookie example

In this example we will see how to access and modify HTTP Cookies of a webpage in Spring MVC framework step by step.

Spring 3 MVC framework provides a very useful annotation @CookieValue to access data set within any http cookie. This annotation can be leverage to fetch the cookie value without getting into hassle of fetching cookies from http request and iterating through the list.
@CookieValue annotation can be used within Controller argument. It automatically bind the cookie value with method argument.


Wednesday 26 February 2014

Saving and Retrieving of BLOB object in MySQL using Spring 3 MVC and Hibernate

In this example we will show step by step how to save and retrieve  Blob Object in Mysql DB using Spring MVC + Hibernate


Tuesday 25 February 2014

Logging in Spring Framework using Log4j

LOG4J is most commonly used framework for logging in Java applications. LOG4J is a open source logging framework from apache software foundation. LOG4J can be used in any Java program to provide easy, fast and customizable logging.

While using LOG4J with spring a programmer can manage and control logging nature and flow from an external configuration file i.e. log.xml or log4j.properties. The external property file can be used to set the log format and the level of logging.

LOG4J Architecture


LOG4J with spring consists of a layered architecture, it has three main components :

1) Logger
2) Appender
3) Layout

Wednesday 19 February 2014

Spring Quartz Batch Example - CSV File Reader

In this Spring Quartz Batch Example - CSV File Reader, we will show you how to read items from CSV file.


Monday 17 February 2014

Maven + Spring MVC Multiple File Upload example

In this tutorial, we show you how to develop a Spring MVC Multiple File Upload in Spring 3 MVC based application.

How to upload a file in Spring MVC and save it to a directory' .Spring supports MultipartResolver to handle file upload capabilities in a web application. We will add a 'MultipartResolver' bean to our spring configuration file to take advantage of Apache Commons upload library to handle upload in application.

The requirement is simple. We have a form which displays file input component. User selects a file and upload it. Also its possible to add more file input components using Add button. Once the files are selected and uploaded, the file names are displayed on success page.


Friday 31 January 2014

Maven + Spring JPA Hibernate MySql Example

 In this example we will demonstrate how to use JPA in Spring framework in MySql Database.

Using Maven create a simple Java project structure.

Thursday 30 January 2014

Maven + Spring Hibernate MySql Example

Spring Hibernate MySql Example

In this example we will demonstrate how to use Hibernate in Spring framework in MySql Database.

Using Maven create a simple Java project structure.

Wednesday 29 January 2014

Spring MVC form handling example

In this tutorial, we show you how to develop a Spring MVC form handling example.


Monday 27 January 2014

Spring 3 MVC hello world example

In this tutorial, we show you how to develop a Spring 3 MVC hello world example.

Our goal is to create a basic Spring MVC application.

Technologies used :
  • Spring 3.0.5.RELEASE
  • JDK 1.6
  • Maven 3
  • Eclipse 3.6

Tuesday 14 January 2014

Spring 3 + Quartz 1.8.6 scheduler example

To integrate Spring with Quartz scheduler framework. Spring comes with many handy classes to support Quartz, and decouple your class to Quartz APIs


Monday 13 January 2014

Spring JdbcTemplate + JdbcDaoSupport example



Spring provides a simplification in handling database access with the Spring JDBC Template.
The Spring JDBC Template has the following advantages compared with standard JDBC.

  • The Spring JDBC template allows to clean-up the resources automatically, e.g. release the database connections.
  • The Spring JDBC template converts the standard JDBC SQLExceptions into RuntimeExceptions. This allows the programmer to react more flexible to the errors. The Spring JDBC template converts also the vendor specific error messages into better understandable error messages.

Wednesday 8 January 2014

Spring Object XML mapping example

converting Object to XML or vice verse. This process is also known as
  • XML Marshalling – Convert Object to XML.
  • XML UnMarshalling – Convert XML to Object.

Example show you how to use Spring’s oxm to do the conversion, Object <--> XML.

Spring’s oxm itself doesn’t handle the XML marshalling or UnMarshalling, it depends developer to inject their prefer XML binding framework. In this case, you will use Castor binding framework.

Tuesday 7 January 2014

Spring Security Login Form Using Database

In this tutorial we will see how to use database to perform the form-based login authentication in Spring Security.

Example 

Create Database Tables

We are using MySQL as database

create database for users to authenticate.
 

Spring AOP + AspectJ in XML configuration example

Spring AOP + AspectJ in XML configuration example

Monday 6 January 2014

Spring Expression Language using XML

The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.

Spring Auto scanning components

Normally you declare all the beans or components in XML bean configuration file, so that Spring container can detect and register your beans or components.

Actually, Spring provides the capability of automatically detecting 'stereotyped' classes and registering corresponding BeanDefinitions with the ApplicationContext.

To autodetect these classes and register the corresponding beans requires the inclusion of the following element in XML where 'basePackage' would be a common parent package for the two classes (or alternatively a comma-separated list could be specified that included the parent package of each class).

Friday 3 January 2014

Spring Auto-Wiring Beans

In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in <bean>.

Spring Annotation Based Auto-Wiring


In Spring autowired bean via @Autowired, and it can be applied on setter method, constructor or a field.

See following full example to demonstrate the use of @Autowired.

Thursday 2 January 2014

Spring Resource Bundle With ReloadableResourceBundleMessageSource In Static Method

2 different ways to do this and one of them is a little bit harder to develop. I start with the hard way first, but in these examples you must need some environmental things:

My ResourcesBundle.properties file is directly inserted in the classpath.

My applicationContext.xml file is directly inserted in the WebContent/WEB-INF.