Artikel Terbaru

Friday, 30 December 2011

Issues in configuring settings.xml in maven

As you know, maven is build tool for software java projects. Most of the developers have uses maven over ant these days because of maven resolve their dependencies.


settings.xml in maven is used to configure enviornment specific settings such as repositries(Local and remote repositories) and proxy configuration and server credetials.

what is repository in Maven:-

As you know, in java application, there are a lot of dependencies such as log4j,apache libraries. These are called dependencies to your project. you have to define all your dependecies in pom.xml.

This libraries are avilable in apache repositories. so you have to download all these files when we don't use maven in your project.
If we have used maven to your project, these libraries(jar files) are downloaded to your local repository for the first to your company host.

Local repository contain java libraries downloaded from different libraries repositories.







































This settings.xml is created in your {user's m2 folder}/.m2/settings.xml by default.

What is final keyword in java?

final keyword in java

final is one of the java keyword which can be applied to variables, method, and classe and the meaning is once final is applied, it's value or state can not be chnaged

what is final keywords for variables:-

if we apply final keyword to fields or meber variables , the varibles are tread as constants, that means once created , and assigned the value, The value can not be changed
final int value=20;
// Gives compile time error for the below line of code
value=40;

So you have to use the fields as final whenever the value of the field can not be changed once it is initialized.

what is final keywords for methods

:-
methods also can be declared as final. A final method can not be overriden in a sub class

following is the usage of final method
class SuperClass {
 public final void method1() {

 }

 public int method2() {
  return 0;

 }
}

class SubClass extends SuperClass {
 // the following method throws Compile time exception as this method has
 // been declared in Superclass.Final methods ca
 public final void method1() {

 }

 // This works fine
 public int method2() {
  return 0;

 }
 

what is final keywords for classe

:-

if we mark the class as final, the class can not be extended by other class. This makes the class as some specific class which is secure.
Most of the classes in java.lang.Math classes are final classes.
The compiler will throws error if we extends the final class.

Here is the example for final class
public final class SuperClass {

}

// the following class throws Compile time exception as the Superclass declared
// as final

class SubClass extends SuperClass {

}


Final as argument to the method

:-

You can also pass the final keyword to the parameters to the methods. That means the parameters can not be changed and local to the method

public void getValue(final int i){
  
 }


Please click on +1 button if you like this post

Wednesday, 28 December 2011

Top 10 Examples of SVN Commands

Top ten Examples of SVN Commands


SVN comamnds are used by most of developers when there is project development involves multiple locations by different teams.

I am listing down the some of the frequent used commands

1.

How to find the SVN version?


E:\techrocksz>svn --version
svn, version 1.6.12 (r955767)
   compiled Jun 21 2010, 16:00:59

Copyright (C) 2000-2009 CollabNet.

This will display the current svn client version

2. How to find different commands avilable in the SVN tool?


E:\techrocksz>svn help
usage: svn  [options] [args]
Subversion command-line client, version 1.6.12.
Type 'svn help ' for help on a specific subcommand.
Type 'svn --version' to see the program version and RA modules
  or 'svn --version --quiet' to see just the version number.

Most subcommands take file and/or directory arguments, recursing
on the directories.  If no arguments are supplied to such a
command, it recurses on the current directory (inclusive) by default.

Available subcommands:
   add
   blame (praise, annotate, ann)
   cat
   changelist (cl)
   checkout (co)
   cleanup
   commit (ci)
   copy (cp)
   delete (del, remove, rm)
   diff (di)
   export
   help (?, h)
   import
   info
   list (ls)
   lock
   log
   merge
   mergeinfo
   mkdir
   move (mv, rename, ren)
   propdel (pdel, pd)
   propedit (pedit, pe)
   propget (pget, pg)
   proplist (plist, pl)
   propset (pset, ps)
   resolve
   resolved
   revert
   status (stat, st)
   switch (sw)
   unlock
   update (up)

Subversion is a tool for version control.

This command will list down all the avilable commands (Add,checkout etc..) in svn client tool.

3.

How to Checkout from SVN

Checkout means creation a local workable copy of your project retrivied from remote repositiroy.

Let us say you have project located in repository created at url location http://www.techrockz.blogspot.com/svn/myrepo/myproject.
so you have to checkout myproject into your local system assuming myrepo is public repository.

svn co http://www.techrockz.blogspot.com/svn/myrepo/myproject

It will copy all your files located in myproject to current directory.

if you want to checkout the directory which is not located in public repository i.e private repository which is specific to your company. Then you have to give one more option--username and --password


svn co http://www.techrockz.blogspot.com/svn/privaterepo/myproject --username admin --password admin

Tuesday, 27 December 2011

How to Install Subversion or SVN Client on Windows?

SVN client is mostly used by software developers to do the svn based operations(creating branch, Checkout and commiting code etc..).
This task are mostly done daily to make code changes on java projects.

First try to get the required installation exe file CollabNet Subversion Client v1.6.12 (for Windows) from collab's site.
Once you downloaded the exe file, following the following steps to install the svn client on windows

1. click on CollabNet Subversion Command-Line Client v1.5.12.exe file and follow the instructions to install the client on your local box.
This will install to default folder in program files i.e Drive:\Program Files\CollabNet\Subversion Server.

2. After installed the svn client, go to Environment Variables in System properties, please make sure that "Drive:\Program Files\CollabNet\Subversion Server" value is added to PATH variable.
if PATH is not set, please add "%PATH%;.;Drive:\Program Files\CollabNet\Subversion Server" as value for the key "PATH".

3. Now SVN client is installed and read to use.
Please open a command prompt and type the following command in the command prompt to test the svn client is properly installed or not

svn --version

here is the result of the above command.


Command results the correct version 1.6.12. so you are ready to use svn client for doing more operations.

Please click on +1 button if you like this post.

Monday, 26 December 2011

How to Convert BigInteger to String?

How to Convert BigInteger to String?

Coversion of BigInteger to String is one of the day to day task for java programmer.
Few days back i have the need to conver the BigInteger to Integer in my programming
It is simple task to do the same

BigInteger is commonly used for storing the numerica values by result of arbituary arthamatic calculations.
In My Previous Post, we have discussed about the conversion of BigInteger to Integer or viceverse. we can also do the same for conversiton to String

We have two cases 1. BigInteger to String 2. String to BigInteger

Covert BigInteger to String object:-


We can do this in many wasy

One of the way is to use the BigInteger.toString() method or String.valueOf() in java.This is simple coding task to do.

BigInteger class constructor for passing String as parameter for BigInteger object creation

BigInteger bi=new BigInteger("123");

As you know every java class has toString method, To return the String object with for the BigInteger class.

Following is the line of code for returning String object

String str=bi.toString();

//The following case works without throwing exception
  BigInteger bigIntegerdemo = new BigInteger("123");
  System.out.println(bigIntegerdemo.toString());

  //The following case doest not works and throws NumberFormatException
  BigInteger bigIntegerdemo1 = new BigInteger("123");
  System.out.println(bigIntegerdemo1.toString());


The disadvatanges with this approach is alwasy we need to pass the numeric value in the form of String for BigInteger constructor.
if String like "abc" is passed, it throws NumberFormatException.


The other way around to conversion to String is first convert BigInteger object to bytes using toByteArray() method and then passing array bytes to String's byte Constructor

BigInteger bigIntegerdemo2 = new BigInteger("123");
  byte b[]=bigIntegerdemo2.toByteArray();
  String s=new String(b);

k


Covert String to BigInteger object:-

One way

Other way around is to use the BigInteger.toByteArray()
In this process, we are converting String to array of bytes using String.getBytes() method and then Bytes to BigInteger using toByteArray() method.
String msg = new String ("Hi Techrocksz!");
  BigInteger bi = new BigInteger(msg.getBytes());
  System.out.println(new String(bi.toByteArray())); // prints "Hi Techrocksz!"

Hoep you understand this. Please leave a comment if there are any more ways to convert this

Why main method is declared as static in java?

Why main method is declared as static in java?


As you know in simple java program, we declared the main method as following way

public static void main(String args[])


here the method name is main.

By using java javafilename command, JVM loads the java class into the memory and looks for the main class in the java file.

if main method is not found, it throws NoClassFoundError exception.
if main method is found, it will start the java exectuion code process.

if you want to access the any method, we can use method name with object (like object.method()),
For main method, we are declaring the method as static, means JVM can access the main method directly using the direct class name.That's why for being main method declared as static, object creation is not created.


Void in main method returns nothing.

public keyword means, any other outside all classes can be accessed.

Strings Args[]:- arguments are command line arguments for the java class. we can set arguments throug command line as part of java tool to send the some arguments while executing java program.


usage :- java javafilename argument1 argument2

arguments1,argument2 are available in string args[], once execution starts with the above command.

Hope you understand the basic usage of main method.

Please feel free to comment if you like this post, if you  have any questions.

How to convert BigInteger to Integer or Integer to BigInteger in java?


Conversion of Integer to BigInteger to Integer is day to day task for java programmer.
Few days back i have the need to conver the BigInteger to Integer in my programming

It is simple task to do the same

BigInteger is commonly used for storing the values beyond the range of 2 power 32 values. It is mostly used in arbitarly precession arthamatic operations.


Covert Integer to BigInteger object:
Conversion of integer to BigInteger is easy task as BigInteger object has provided one of the method BigInteger.valueOf(int value) method

int integerMaximumValue = 123;
BigInteger bigIntegerdemo = BigInteger.valueOf(integerMaximumValue);


Covert BigInteger to Integer object:

BigInteger has BigInteger.intValue() method to conver to Integer object.

BigInteger bigInteger =BigInteger.valueOf(123);
bigInteger.intValue();

Sunday, 25 December 2011

BigInteger tutorial with example in java

What is Big Integer?:-


BigInteger is one of java object in java.math package in java as part of JDK1.6.

Integer Primitive stores the number values between the range of 2 power 31 -1 -2 power 31
Long Primitive stores the numerica values between the range of 2 power 63 -1 -2 power 63.

When we are doing the Arthematic operations with either integer or long, if the result of the arthematic operation is not accomadating the their range,
saves the lower order 32 bits for integer,64 bits for long and gives the lower range result

But if we use BigInteger, it gives the correct result

BigInteger can also be used in numerious bit operations and other mathematical functions which can be store the numeric values over 2 power 64 values.
Big Integer Example:-


import java.math.BigInteger;

public class BigIntegerDemo {
 public static void main(String args[]) {

  int integerMaximumValue = 2147483647;// This is maximum value for
  // integer type i.e 2 power 31

  System.out.println("Case=1     = " + integerMaximumValue);
  System.out.println("Case=2 = " + (integerMaximumValue + 1));
  System.out.println("Case=3 = " + (integerMaximumValue * 2));
  System.out.println("Case=4 = " + (integerMaximumValue * 4));
  // All the above cases expect Case=1 gives wrong value as overflow
  // occured

  // All the below cases gives expected values as BigInteger Object
  // accomdates more values
  BigInteger bigIntegerdemo = BigInteger.valueOf(integerMaximumValue);
  System.out.println();
  System.out.println("Case=5 " + bigIntegerdemo);
  System.out.println("Case=6 " + bigIntegerdemo.add(BigInteger.ONE));
  System.out.println("Case=7 "
    + bigIntegerdemo.multiply(BigInteger.valueOf(3)));
  System.out.println("Case=8 "
    + bigIntegerdemo.multiply(BigInteger.valueOf(4)));
 }
}



and the following is the output

Case=1     = 2147483647
Case=2 = -2147483648
Case=3 = -2
Case=4 = -4

Case=5 2147483647
Case=6 2147483648
Case=7 6442450941
Case=8 8589934588


Attached is the methods available in BigInteger with using javap command.




This topic has been a very basic start to explore on BigInteger example. Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.


Please click +1 button if you like this article.

Monday, 19 December 2011

How to Store unique objects to avoid the duplicates in java List?.

In real time scenarios, you encountered the cases having duplicate objects in a list.
To remove the duplicates, There are no java Collections implementations to solve this.
In Collections, List allows duplicate values and maintain the insertion order, where as Set does not allows duplicates,doesn't maintain order.

To achive this,We can do this in number of ways.

Apporach1:-

1. We can write our own set and list implementation by extending List implementation and Implementing Set interface
You can not consider implementing List as already Set is implementing. You can Consider for extending ArrayList as it is not final
For this you need to overide the Add method and hashcode method to achive without duplicates and order

Apporach2:-

apache common-collection API provided org.apache.commons.collections.list.SetUniqueList class to avoid duplicates in a list

You can use this class for the same functinality
Please leave a comment if you need more information on implementation

what is volatile keyword in java?

Volatile is keyword in java which is applicable to member variables only.


what does it mean if we declare a transient member variable in an object.

In the multithreaded applications, state of any object can be modified asynchronously by multple threads

This causes the consistency to the state among different concurrent threads.

To maintain the consistence between all the threads for that state of an object we can declare member variable as transient.

Whenever thread is going to execute the object, it tries to get the state of an object from memory, and save the state after thread execution is over, so that object's state can be consistent among concurent multiple threads.

Declaration:-

private volatile String mState;

Sunday, 18 December 2011

What is a Subversion?

What is SVN or SubVersion :-
SVN is version configuration management system used in most of software projects to maintain the code at one of repository location.
SVN is implmented by apache framework and the current version is Apache Subversion 1.7.2

Subversion is same as like as CVS with additional features.

When we are creating any code base in subersion, First we need to create a repository. Repository is remote network folder which has all the code base as well as project related document.

Repository is located in remote server that can be windows based or linux based systems.

Clients or developers has to install the svn clients such as standalone Tortorise SVN clients or command based clients to get the code.

Once users are installed the svn clients they can copy the code from the repository to therir local systems, code chagnes can be modified in local copy, once the changes are done, again they save their code to the repositiroy. so that multiple users have synch to the repositiorys

SVN is used mainly to sync the code base that will be changed by mulitple teams in a project.

Most of java open source projects uses SVN as tool for maintaining the code base.

what is Checkout in SVN?:-

Checkout is cvs jargon used to create a local copy of the code base from the repository. This can be done either from the SVN GUI clients(Totorise SVN) or command based clients


what is commit in SVN?
commit is cvs jargon used to save the local copy of the code base to the repository code base, so that code in the local and repository is synch always.


What is Merge in SVN?Team A started work on code that is checkout from repository for the one project. Team b checkout the code from repositiory after Team A checkouts.

Team A finish their work for the local copy and commit their local changes to Repository.

But team b has their own local copy changes. when team B is going to commit their changes, SVN will do the merge process.
It will copy the all corresponding changes in local copy to repository.

while merge is happening, it will show conflicts for all the individual files, we need to see the difference between those conflict files and do the merge process

There are two types of merge in SVN

1. Automatic Merge :- Automatic means svn resolve the conflicts automatically. No changes are required from the developer
2. Manual Merge:- SVN provides the merge manager, in that we can compare the files that have conflicts and merge as per the code base.
We need to do this carefully as there is missing of code in if we have not done correctly


Advantages or benefits of Subversion:-
SVN is lightweight tool. Easy to learn and setup as well as for administration.
Full revision history of all the that are modified/added/delete/Renmated
Easyly integrated with other build tools to achive the Continuous Integration testing.

Maintaining the different version of code base in the repository by simple commands


This topic has been a very basic start to explore on SVN tutorial Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.

Sunday, 11 December 2011

What is the use of javap command in java?

javap is the tool provided by java framework which was bundled with JDK software. This tool(javap is located in JAVA_HOME\bin location) which is used by many java developers to find the different member variables and methods for any java object.


We can also use -c options to with javap command to complie the source code and display the information about the object

Saturday, 10 December 2011

Add Google +1 button to your website or blog

Google +1 is a for making your friends aware about your liking content.

It is more or less like a facebook like button. It will effect the search engine rankings. so Please give it try to your blog or website.

Google +1 is not that much popular, by adding this, we will see traffic increase due to the fact that if someone clicked on +1, their friends see it on google.

here are the steps to add +1 button to your site:-
1.First get the java script code provided by google.
Click here to get the javascript code. you can select and customize the design of the buton





2.the code plusone code can be placed wherever you want the required +1 button.

3.Above script code should be loaded whenever page loads. so you have to places this just like a javasript placement or css location before tag.
To add +1 button to blog:-

1.Go to Design link on your manage blogs in your blogger home page.
2.Click on edit link where you want the +1 button. pop window is show by clicking on edit link





Please let us know if you have any questions.

Distribute File System VS Normal File System

Difference between Distribute File System and Normal File System

Distrubted File System is like a normal file system with different nodes where each node has the local file system to store the data. This multiple local file system will coordinate with some protocal to give the data to external clients.

The clients call this multiple machines with some protocal to get the data. Most of times communication protocal is tcp/ip. For accessing any information on Distirubute file system, you need client software.

Listing out the differences between Normal File System and Distrubted File System.

Normal File System:-


1. Data is maintained in Single system. if machine is down, we can not able to get the data and failover chances are more.
2.The time taken to read the data in this less as there are only read call to hardisk and the local processing time

Distributed File System:-


1.Data is replicated in different nodes. clients able to read the data, if any node is failed.Failover is less.
2.The time taken to read the data in this is more as we have network remote call and local data read to disc and coordiating the data from multiple systems



This topic has been a very basic start to explore on maven dependency example. Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.

What is Hadoop?:Apache Hadoop Tutorials



Hadoop tutorial :-

Hadoop is a apache framework developed completely in java java with opensource brand.
Hadoop analyze and process large amount of data i.e peta bytes of data in parallel with less time located in distributed environment. Hadoop is not a single tool which contains combination of different sub frameworks called Hadoop Core,Map Reduce,HDFS,Pig,HBase. Hadoop is mostly used for OLTP transactions. Some big companies like facebook uses hadoop for OLAP transactions as well.Hadoop can be setup in clustered environment as well as single node environment.





HDFS is developed based on google file system (GFS)
Map Reduce is developed on google map reduce concept.
Pig framework is SQL wrapper for map reduce jobs

Basics of Hadoop HDFS :-

In Hadoop, data is stored in hadoop distributed file system (HDFS) software in the form blocks (chunk of size),data is replicated in different nodes (called machines) in clustered (many nodes) environment. In real time scenario, thousands of peta bytes data is stored in thousand of  nodes in distribute environment. The advantages with storing replicated data is data available when one of the node is down. With this, data available all the time for the clients apps. Do we need high end hardware for all these nodes? Answer is no, we can accommodate commodity hardware for all these nodes.

if data is grown rapidly, we can add nodes without fail over of the whole system and losing the data. This we can call it as scalable system in network terminology. This system handles the case of losing data while adding machines to the existing machines or after the machine add to the cluster.
As you know cluster has different nodes, if one node fails, hadoop handles the scenario without losing the data and serves the required work as expected.

HDFS stores the data in the files where this files uses the underlying operating system’s file structure.

HDFS is suitable for storing the large amount of data like peta and tera bytes of data which process the data using Map reduce for OLTP transaction.

Data storage in HDFS:-

In HDFS, set of data is called as blocks,each block of data is replicated in different node or machines. The number of nodes where this data is replicated is configured in hadoop system.


Basics of Hadoop Map Reduce :-

In hadoop system, peta bytes of data is distributed in thousands of nodes in cloud environment.To process the data stored in HDFS, We need a applications.
Map Reduce is a java framework  used to write programs, which are executed parallel  to process large amount of data in clustered environment.
Hadoop provides Map Reduce API’s to write map reduce programs. We have to make use of those API’s and customize our data analysis login in the code.
The map reduce piece of code fetchs and process the data in distributed environment

As we want to process the data stored in HDFS,For this we need to write programs using some langugage like java or python etc.


Map reduce has two different task 1.Mapper 2. Reducer

Map takes the input data and process this data in set of tasks with dividing input data. and out of this map is result of set of task, which are given to reducer. reducer process this data and combine the data output the data.

Basics of Hadoop Hive:-

Hive is apache framework which is SQL wrapper implementation of map reduce programs. Hive provides sql languages which understand by hadoop system.

Most of the times, data analysis done by database developers, so DB developer is not aware of the  java programs, in that case, hive tool is useful.

Database developer writes Hive Queries in hive tool for the result. This queries calls the underlying map reduce jobs, process the data, finally data is returned to hive tool.
Advantages with hive is no need of java programming code in hadoop environment.

In some cases, sql queries are not performing well, or some database feature (group by sql function) is not implemented in hive, then we have to write map reduce plugin and register this plugin to hive repository. This is one time tasks.


On top of all these, we have Hadoop Common which is core framework written for processing distributed large set of data to handling the hadoop features.

Hadoop Use case explained:-

Let me take scenario  before apache hadoop is introduced into software world

i am going to explain about the use cases of data processing for one big data company.
Retail company has 20000 stores in the world. Each store will have the data related to products in different regions.This data will be stored in different data sets including different popular databases in multi software environment. Data company would need licenses of different softwares including databases and hardware

For each month, if this company wants to process the data by store wise for finding the best product as well as loyal customer that means we need to process and calculate the data and findout the best customer as well as best selling product in each region to give better offers.
Assume that 2000 stores will have the data of all the products and customer details, and customer purchase information per each stores.


To target the the below use cases.

To find the popular product sold in the last year Christmas per the Store A, so that this year we can target the customers to give different discounts for this products
Top 10 Products sold
selecting the top 100 customers per each store to give more offers.


From the technical point of view, we have large data infrastructure to store this data as well as we need to process the data, for this we need data warehousing tools to process this normalized and unorganized which are costly. and also storing should have reliable as it will impact the data loss
Over this time data process is complex and license cost of maintain is more.

Suppose 10000 more stores added, data is grown, more nodes are added to current infrastructure, but overall performance system degrades as the  nodes are added

Apache hadoop  solve the above problems.


This topic has been a very basic start to explore on what is hadoop. Hopefull you have enough information to get started.

If you have any questions, please feel free to leave a comment and I will get back to you.




Sunday, 4 December 2011

Top 10 JDBC Interview Questions

1.what are different frequent JDBC classes or interfaces used in java code?

Connection,DriverManager,ResultSet,Statement,PreparedStatement,CallableStatement.

. 2.How do you load the JDBC driver class?.

Class.forName("DriverClass") is used load the driver class. whenever DriverClass is loaded with this, create a new instance of DriverClass and register the driver with DriverManager Class.Once Driver is registered, it is ready to create physical connections to database using Connection object.

3.What is connection pooling?.

as a creating a database connection is like a opening a socket connection to remote machine, so this call is expensive. whenever we have to do CRUD operations(create,read,update and delte) on data to database,Connection object is used for this. creating a connection for each operation is expensive. To avoid this, at the Initial state(application startup), creating a pool of connections which are created and connected to the database. whenever an database operation is to needed by application, the connection from pool of connections are reused,once the operation is over, the connection is returned instead of closing(in case of normal connection) connection, so that Database calls are reduced and nonperformance is increased.

Statement,PreparedStatement and CallableStatement

In JDBC, There are different statements to execute the sql queries in databases. We can send the simple SQL,complex SQL and PL/SQL queries using this statements There are three types of Statements. The following statements are returned from the connection object.before creating any statement object, connection should be presented. The connection object can be returned from the following lines of code
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con= DriverManager.getConnection("jdbc:odbc:orc", "scott", "tiger");
1.Statement :-

This is simple Statement to execute SQL queries like insert,update and delete operations. for this we can not know the input values. For each query, compilation and execution is done at database level.we can use this for static queries and input values are not accepted

try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from employee where employee_id=11");
......
} catch (SQLException e) {
} finally {
stmt.close();
}

Whenever this query is passed from jdbc application to database for getting the result,At Database level,query is complied first and execute the query and return the result. if we want to execute the multiple same queries with different employee_id, multiple compilation and multiple executions are happened. To avoid the multiple compilations, we have to use PreparedStatement.

2.PreparedStatement :-

This Statement is to be used to execute multiple SQL queries like insert,update and delete operations multiple times. for this, we will pass multiple different input values for the same query. if there are multiple queries with different input values, query is complied (parsed and create a plan) for the first time and execution will be happened for different values multiple times by using the same plan at database level.This improves the performances as compared to Statement .we can use this for dynamic queries and dynamic input values are accepted.Same query takes the values as placeholder(?,?,?).

PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET name= ? WHERE employee_id = ?";
pstmt = con.prepareStatement(SQL);
...
} catch (SQLException e) {
} finally {
stmt.close();
}
3.CallableStatement :-

This Statement is to be used to execute database stored procedures which resides at database.stored procedures are set of sql statements stored at database level under single name, thus improves the performance.

CallableStatement cstmt = null;
try {
String SQL = "{call procedureName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
   . . .
}
finally {
. . .
}

SQL statement has the procedure name with place holders.

Here the placeholders are of type IN,OUT,INOUT parameters.

IN parameters means input parameters, we can set using setXXX methods. OUT or INOUT parameters should be used by having one more method registerOutParameters which are mapped the java datatypes to database column data types.

Please leave a comment if you have any questions.

Convert of String to Integer or Integer to String in java

As a developer, in day to day programming, we have encountered in number of situations to convert from String to Integer or vice verse.

convertion of String to Integer:-

There are number way to convert from String to integer. For this, String should holds valid int value. if an invalid numeric value is presented in string, then NumberFormatException is thrown by parseInt method.For this, you have to handle using try and catch blocks

one way is to create a Integer object which has Constructor of String type. This conversion happens at object creation.
String s="123";
Integer i=new Integer(s);

second way is to using parseInt method of Integer object To convert this to integer we have used Integer.parseInt method.

String s="123";
Integer i=Integer.parseInt(s);
and other way is using valueOf of Integer object
String s="123";
Integer i=Integer.valueOf(s);
Exception Handling:-

String s = "abc";
try {
Integer ii = Integer.valueOf(s);
} catch (NumberFormatException e) {
System.out.println("Invalid integer value in String " + s
     + "exception=" + e);
  }

Jdbc Basic Example to connect to database in java

Following steps for writing a sample java program to connect to database and get the result. JDBC API is provided by sun framework which contains different interfaces and classes to connect to databases.
The below diagram depicts the steps to connect to any database.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnDemo {
 public static void main(String args[]) throws Exception {
  // establish connection to database this includes loading driver
  // and fetching data.
  // first step is to register jbbc driver with driver manager
  // class.forName loads class which in this case is jdbc
  // implementation of interface Driver
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  int rowcnt = 0;

  Connection con;
   con = DriverManager.getConnection("jdbc:odbc:orc","scott","tiger");
  System.out.println(con);
  // Once connected, we can execute any sql statement
  Statement stmt = con.createStatement();
  ResultSet rs = stmt.executeQuery("select * from employee");
  while (rs.next()) {
   System.out.println(rs.getLong("employeeid"));
   System.out.println(rs.getString("EmployeeName"));
   rowcnt++;
  }
  System.out.println("No Of Rows Fetched " + rowcnt);
 }
}
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");:- loads the JdbcOdbcDriver class into the jvm and avialble to ready to use.
DriverManager.getConnection("jdbc:odbc:orc","scott","tiger"); :-connection string has to be provided, which contains username,password,database name of oracle.
con.createStatement(); :- return the statement object which is used to get the result set using executeQuery method.
ResultSet object holds all the rows of table which are in the order by result of the query.we have to traverse the result set and fetch the each column value.
Here is the high level flow of any application connect to any database


This topic has been a very basic start to explore on JDBC example. Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.

Learn Basics of Inside Java Virtual Machine?

As you know in any machine, we have different components like a hardware (physical machine call it as hardware(CPU,RAM.. etc) and software (Operating System). if you want to perform any operation from other machine, we need to write some code (say in c language) which will open a socket connection, that is a remote network call to other machine and make a OS call i.e native call. Each machine should have different ways to handle this situation. Here the code is tightly coupled means dependent on the target machine. if target machine is changed or new machine. The existing code would not work in this case. so that means platform dependent. After Java virtual machine is introduced, many problems are solved. write once deploy to any machine.


Inside Java Virtual machine:- as the name suggests it is a virtual machine run as java process which talks to physical machine. JVM is dependent on physical machine, but it gives independent to different machines in the form of java code.
It is a virtual platform on top of your physical processor.JVM is one of component of Java runtime environment.

JRE contain set of java base API as well as JVM. The following are responsibilites of the JVM
  • Compiling your java code java byte code which is understood by physical machine.
  • Interpret the java byte code and covert this byte code into the corresponding native calls i.e Operating system calls
  • Object managment hadling such as object creation and garbage collection.
JVM has different components.
  • Heap memory:-
  • Heap memory is one of the component in JVM machine which stores the object. here object means which holds the member variables, constructors and methods. By default heap size is 64 mb. we can increase the size using -Xmx(maximum heap size) and -Xms(initial heap size) options. life time of an object as long as it is referenced. whenever object is unreferenced, Garbage collector using some algorithm will destroy the objects
  • Stack Memory:-
  • holds the local variables. The life time of the local variables are the temporary as long as method executed. Once the function/method execution is over,these variable are removed. This follows Last In First Out model.
  • Method section:-
  • This section holds the current byte code that is executed presently. once the byte code is executed, it will point to next byte code.
  • registers:-
  • which are used by stack variable.
There are multiple different JRE by different vendors
  • 1.JRocket JVM is developed by BEA Systems.
  • 2. Java HotSpot VM developed by Sun Microsystems.



Related Posts:-
1.Learn More about Data transfer Object Design Pattern
2.Learn the basics about Java code to connect to database using JDBC
3.Tutorial with Hello World JSP example

Saturday, 3 December 2011

Hellow World Jsp Example

Before setting up deploying JSP on your environment, make sure that JAVA_HOME environment is set. and also download tomcat from the apache site annd should set TOMCAT_HOME environment is set.

Please make sure that PATH and CLASSPATH environment variables are set

Steps to create a first webapplication.
  • Create a HelloWorld folder and the folder structure looks like as followng structure
  • HelloWorld root folder containts following structure
  • Create a first.jsp which prints the hello world code to the console
  • 
    
    Hello World JSP page
    
    
    
    <%@ page language=”java” %>
    <% System.out.println(“Hello World ”); %>
    
    
    
    type the above code in the notepad and name it as 'first.jsp'. please this file into your HelloWorld root folder of your webapplication.
  • deploying HelloWorld webapp to tomcat application. to deploy first webapp to tomcat, simply copy HelloWorld app to tomcat installed directory i.e webapps and start the tomcat server. The start script is located under TOMCAT_HOME\bin\startTomcat.bat for windows.
  • Accessing jsp file. For example, to run first.jsp” file, open a browser to the address: http://localhost:8080/first.jsp This will show you the executed JSP file.
so you are ready with learning with your first jsp page creation.

java Collections overview

following are the different collections that we used in java 1.Vector:- is an implementation of list's class and accommodation the allowable array of objects i.e dynamic Synchronized. order of the elements are insertion order. 2.ArrayList:- same as Vector except synchronized supports dynamic array. unsynchronized. order of the objects is in insertion order. 3.LinkedList:- is also same as ArrayList when we will use LinkedList;- retrieving an objects is faster compared to ArrayList and Vector

Front Controller Design pattern in java/jsp applications

Front Controller is one of the most important design pattern mostly used in web applications.

The problem:-

As you know in a webapplication, whenever clients send the request to the server, server process the request, if possible make a database call, get the data from the Database or other third party systems and process the data, and send the response. Here there are different components involved,business data validation,holding the database data(model) and view process. Because of this process, there is a lack of single point of contact for the request. Front Control design pattern is introduce. In This Servlet act as a controller sitting infront of other resources. In this patter, all the request that send by different resoures like browser, mobile client as well as Standalone apps is handled by this servlet and delegate the request to approriate web resources. It is the entry point for the request sent by browser.

ActionServlet is the front controller for Struts based applications DispatchServlet is the front controller for spring web mvc based applications

Common exceptions in java language

In java programming, daily coding, we have encountered different exceptions,so i am listing out the list of common exceptions, and the scenarios, how to solve those exceptions.

following are the exceptions in java programming language. NullPointerException:-

One of common exception occurred, This will be happened when you are calling the object's method with object is not created or not initialized properly.

String str=null; System.out.println(str.toString());

the solution in our code is if(str==null){ //initialize the string object here }else{ System.out.println(str.toString()); } ClassCastException:- This exception is occurred if we assign the incorrect object. NumberFormatException:- This exception is occurred if we convert the string data itmes to number items format object.

Sorting List of Numbers

In a java programming, Let us say We have a set of numbers say 100,200,4,5,79,26. In java, we can use either Array or List implementation(ArrayList or LinkedList in java.util package

.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


public class SortDemo {
public static void main(String args[]){
 Integer[] numbs=new Integer[]{100,200,4,5,79,26};
 System.out.println("Initial List="+numbs);
 /*For sorting numbers we can use Arrays's sort method*/
 Arrays.sort(numbs);
 
 Integer[] numbs1=new Integer[]{100,200,4,5,79,26,20};

 /*For sorting numbers we can also use List's  sort method*/
 List listNumbers=Arrays.asList(numbs1);
 Collections.sort(listNumbers);
 System.out.println("Sort List using List sort="+listNumbers);
 }
}

Arrays can store the static list of data items, that means size cannot be grown and fixed.where as List store the list of dynamic data itmes.

Thursday, 1 December 2011

Linux sudo Command

sudo is linux/unix command which is used by system administrator to give privileges to some set of users as root. This could be applied to commond level only.

To check your current sudo privileges, run this command: sudo -l

How to fix java.lang.OutOfMemoryError issue in Maven?

java.lang.OutOfMemoryError in maven

:-

Maven is automation build project management tool.
if the project has lot 10000 java files, whe you try to build the project using "maven clean install", build failed with error.


maven clean install will tries to clean/delete the project and complie the project, and test the project and build the applicaiton

OutOfMemoryError issues occurs either in compile phase of your project or test phase of your project while building your maven project
For test case execution, maven uses surefire-plugin. in any case you have heap to increase the heap size in number of ways.
Actuall OutOfMemoryError error there is no enough space for your maven process to execute the java project or java class loading issue with your classes.

java.lang.OutOfMemoryError: Java heap space
or
java.lang.OutOfMemoryError: Perm Gen space

For debugging the exact reason, use the maven -x clean install, it gives exact root cause with detailed print stack trace.


First you have to find out which phase this error is occurring
if the error is giving with compliation, the you have to increase heap size as per your system capactiy as with following lines of code in linux,windows.

Java heap space means there is no enough space to allocate your object execution in heap memory
Perm Gen space means classloader loads the classes, but when your application is still maintain the references of classes after execution is over, this we call it as memory leak, so you have to use the systemclassloader when this errors occurs in maven


Fix for OutOfMemoryError for maven in windows:-


change the environment variable MAVEN_OPTS in such way that increase the heap size with following piece of code

set MAVEN_OPTS=-Xmx768M -XX:MaxPermSize=768M

Fix for OutOfMemoryError for maven in Linux/Unix:-


Increase heapszie for evnironment variable MAVEN_OPTS.
the processing for linux version is different

export MAVEN_OPTS=-Xmx768M -XX:MaxPermSize=768M


Most of the times OutOfMemoryError solves withe above lines of code, if it does't solve, then follow the below approache

issue with maven-surefire-plugin in maven:-


As discussed , surefire plugin loads the classes using different mechanism, we will instructs this plugin to use the system classloader with the following approaces

<configuration>
          <usesystemclassloader>false</usesystemclassloader>
    <forkmode>never</forkmode>
        </configuration>



the following commands more helpful in debugging your app for running your project
maven -x
mvn  -Dmaven.surefire.debug

Hope you have idea on solving OutOfMemoryError issues in maven with windows,linux and unix environment.

Feel free to comment if you have anything to share

Maven commands

As we have encountered the usage of maven in java projects, following are the list of maven commands for your reference. Whenever you run maven command with different goals, It tries to download the different dependencies from the different repositories configured in xml file. If mvn install command unable to download dependent artifacts from repositories, then use the following command with proxy settings enabled
mvn install -Dhttps.proxyHost="" -Dhttps.proxyPort=""
To run the maven by skipping unit and integration tests
mvn clean install -Dmaven.test.skip=true or 
mvn clean install -DskipTests=true
To run the maven without downloading artifacts from the repositories i.e offline
mvn -o install
To run one test class using maven
mvn clean test -Pintegration-test -Dtest=java test class
To execute the maven profile
mvn -PprofileName install

Maven Tutorial Part One

maven is a build tool for the java projects. It speed up the java development build process.maven is one of the java tool for continuous build integration. Maven has predefined phases or goals. The goals are similar to ant targets. developer will invoke goals to do their tasks.

Please make sure that you download maven from the apache software and install it.

what are the things to considere while making your java projects to implement maven as build tool
      project object model file
      java project folder structure
Hello World maven applicaiton:- I am going to createa HelloWorld java application.
mvn archetype:generate -DgroupId=com.techrocksz -DartifactId=HelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Output of this mvn command:-

E:\techrocksz>mvn archetype:generate -DgroupId=com.techrocksz -DartifactId=HelloWorld -DarchetypeArtifactId=maven-archetype-quickstart
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO]    task-segment: [archetype:generate] (aggregator-style)
[INFO] ------------------------------------------------------------------------
[INFO] Preparing archetype:generate
[INFO] No goals needed for project - skipping
[INFO] Setting property: classpath.resource.loader.class => 'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on => 'false'.
[INFO] Setting property: resource.loader => 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound => 'false'.
[INFO] [archetype:generate]
[INFO] Generating project in Interactive mode
Define value for version:  1.0-SNAPSHOT: : 1.0.0-SNAPSHOT
Confirm properties configuration:
groupId: com.techrocksz
artifactId: HelloWorld
version: 1.0.0-SNAPSHOT
package: com.techrocksz
 Y: : Y
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating OldArchetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.techrocksz
[INFO] Parameter: packageName, Value: com.techrocksz
[INFO] Parameter: package, Value: com.techrocksz
[INFO] Parameter: artifactId, Value: HelloWorld
[INFO] Parameter: basedir, Value: E:\techrocksz
[INFO] Parameter: version, Value: 1.0.0-SNAPSHOT
[INFO] ********************* End of debug info from resources from generated POM ***********************
[INFO] OldArchetype created in dir: E:\techrocksz\HelloWorld
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 30 seconds
[INFO] Finished at: Fri Dec 02 10:47:29 GMT+05:30 2011
[INFO] Final Memory: 8M/254M
[INFO] ------------------------------------------------------------------------

In the above example created,see the folder structure, In the root folder we have folder named 'src' and file pom.xml and also we have following sub directories

src\main\java :- This folder contains all your java classes src\test\java :-This folder contains all your java test related classes and also we have com\techrocksz\App.java and com\techrocksz\AppTest.java files which is a HelloWorld applicaiton and it's test class

what is pom.xml:- pom.xml is a project object model configuration file which is used by maven.

Maven uses pom.xml which contains all details about your project as well as the configuration details.


  4.0.0
  com.techrocksz
  HelloWorld
  jar
  1.0.0-SNAPSHOT
  HelloWorld
  http://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    
  


In the above, groupId represents the package of the project where ExampleDemo-1.0.0.jar file is created artifactId is the project name as well as jar/war name of the module. packaging specify whether this module is webapplication i.e war or java module i.e jar. if packaging option is not specified, maven consider this as jar module. dependencies tag specifies the what are dependencies this project has. here as we have written App, by default junit dependency is added as part of sample project. Running Maven Project:-
  1. cd HelloWorld
  2. mvn clean install
maven execution process:-

whenever you executed maven install command, we configured repositories location in pom.xml and the dependencies, For the first time it tries to download different plugins and dependencies from the repository and copy those dependicies to folder (your user profile of your document and Settings folder(i.e C:\Documents and Settings\username\.m2\repository). This is time consuming for the first time as it tries to download all your plugins to your local repository.next time onward, it will download those already downloaded jars and executes quickly

. Proxy settings to be enabling for maven

settings.xml in folder C:\Documents and Settings\username\.m2\ have to be created for this.

Here is the output of the command.
E:\techrocksz\HelloWorld>mvn clean install
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloWorld
[INFO]    task-segment: [clean, install]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean]
[INFO] Deleting directory E:\techrocksz\HelloWorld\target
[INFO] [resources:resources]
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory E:\techrocksz\HelloWorld\src\main\resources
[INFO] [compiler:compile]
[INFO] Compiling 1 source file to E:\techrocksz\HelloWorld\target\classes
[INFO] [resources:testResources]
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory E:\techrocksz\HelloWorld\src\test\resources
[INFO] [compiler:testCompile]
[INFO] Compiling 1 source file to E:\techrocksz\HelloWorld\target\test-classes
[INFO] [surefire:test]
[INFO] Surefire report directory: E:\techrocksz\HelloWorld\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.techrocksz.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] [jar:jar]
[INFO] Building jar: E:\techrocksz\HelloWorld\target\HelloWorld-1.0.0-SNAPSHOT.jar
[INFO] [install:install]
[INFO] Installing E:\techrocksz\HelloWorld\target\HelloWorld-1.0.0-SNAPSHOT.jar to C:\Documents and Settings\kinturu\.m2\repository\com\techrocksz\HelloWorld\1.0.0-SNAPSHOT\HelloWorld-1.0.0-SNAPSHOT.j
ar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5 seconds
[INFO] Finished at: Fri Dec 02 11:58:46 GMT+05:30 2011
[INFO] Final Memory: 15M/254M
[INFO] ------------------------------------------------------------------------

Finally your module HelloWorld-1.0.0-SNAPSHOT.jar is created. Now Any other app is ready to use this module. Finally learning maven is started. Please leave a comment if you have any questions.

Data transfer object or Value Object Design Patter

DTO stands for Data transfer object or Value Object (VO) design patter is a one of the design pattern used for transferring the data between one different machines.

The problem :-

In most of the java projects, we have to retrieve the data from the database. In a system, you are queried (select employeeid, employeename from employee) in the databases from your application. Here application is either webapplication or standalone application (applet or Eclipse RCP client). Assume that the applicaiton is executed in Host-1 and MySQL database is hosted in host-2 box. Whenever you are getting the employee information from the application,applicaiton queried the employee id for the first time and employee name for the second time and so on ,repeats this process for all the records.

Solution:-

here application to database is a network or remote call which is expensive from the application point of view.

The advatnages with this approaches:-
  • To reduce the network traffic, we will create a java object which has member variables holding each row data and returned the each object or list of objects.
  • Data transfer is made easy and network traffic is reduce.
  • Reduce code duplication with this approach

public class Employee {

 private long mEmployeeId;
 private String mEmployeeName;

 public void setEmployeeId(long pEmployeeId) {
  this.mEmployeeId = pEmployeeId;
 }

 public long getEmployeeId() {
  return this.mEmployeeId;
 }

 public void setEmployeeName(String pEmployeeName) {
  this.mEmployeeName = pEmployeeName;
 }

 public String getEmployeeName() {
  return this.mEmployeeName;

 }
}
I forgot to one more point, whenever java object is transfered between different JVM's or machines, that must be serializable. How to make the java object serializable.

for any java object to make serializable, we have to implement java.io.Serializable interface, which has no methods to implement. we can also call this type of interfaces are marker interfaces. so how do we achieve serializable without implementing methods.

JVM assumes that whenever objects are implemented with serializable interfaces. it is eligible for serialization process. JVM checks each object for using the method (object instanceOf Serializable) for process.

}

Thursday, 24 November 2011

What is hive in Hadoop?



Hive is open source framework developed in java, and one of sub component of hadoop system, developed by facebook on top of hadoop hdfs system.

I have already blogged about the basics of HDFS Basics of HDFS in Hadoop.Hive can be used to accesse the data (files in hdfs ) stored in hadoop distributed file system or data stored in HBase.
and Map reduce is java framework to process the data parallelly

Hive can be used to analyze the large amount of data  on Hadoop without knowing java map reduce programming.

Hive provides hive query language (HQL). which is simpilary to Structured query language. Hive provides all queries with minimal ansi sql support.
if we wan to support complex query features like aggregation, custom functions, in that case we have to write custom map reduce program that can be plugged to hive sql repository.

Execute Hive Queries?:-
Hive provides command line interfaces platform i.e hive shell for executing hive queries. You can write the queries in shell script and call the shell script. This hive queries calls the map reduce jobs  and query, process the data.

Hive Advantages:-
1.Hive is built on hadoo, so supports and handles all the capablities of hadoop provides like reliable, high avialble ,nodefailure,commodatiy hardware
2.Database developer need not to learn the java programming for writing map reduce programs for retrieving data from hadoop system.

Hive Disadvantages:-
1. Hive is not for OLAP processing

This topic has been a very basic start to explore on what is hadoop. Hopefull you have enough information to get started.

If you have any questions, please feel free to leave a comment and I will get back to you.


Wednesday, 23 November 2011

setup tomcat server on desktop

Tomcat is a open source application server built on java framework. Tomcat can be downloaded from apache site, extract zip file to D drive example D:\ jakarta-tomcat-5.5.0 First importantent thing is make sure that you installed and set up the java/JDK software. Tomcat requires jdk installation i.ethe location in which java is installed for this we need to add set JAVA_HOME=“path where jdk is installed” and add set CATALINA_HOME=.. in both startup.bat and shutdown.bat. set the following environment variables like this JAVA_HOME=D:\JDK1.5 i.e where jdk installed to the drive CATALINA_HOME=D:\ jakarta-tomcat-5.5.0 Starting and Stopping Tomcat : To start Tomcat run CATALINA_HOME\bin\startup.bat To stop Tomcat run CATALINA_HOME\bin\shutdown.bat By default tomcat is configured to run on 8080 port. it means tomcat is listening on at port no#8080, if you want to change the port, we can change the configuraiton located in CATALINA_HOME\confi\server.xml. Deploying webapplications:- webapplications are in the form of war file. so you can deploy to tomcat using console or direct your file to webapp folder Please leave us a comments if you have any difficulty in setup tomcat server

Installation of Hadoop in Windows

Hadoop installation on windows.

Hadoop is a apache framework used to process large amount of data with parallel process. Hadoop is mostly used for linux flavours systems for production use.

As a developer, To explore more things on hadoop, we need a start on windos.

As hadoop is developed and executed in linux flavours, We have many options to setup on windows with either cygwin or vm player.


I am going to list down the steps required for installation and configuring hadoop on windows using cygwin.

What is Cygwin:-
Cygwin is mock enviornment for windows based systems to run as linux based systems. They provided command line interfaces which process this commands and call the windows dll and API's. So you need of knowing most unix commands for this.

It is free and open source software.

1. Download from cygwin from cygwin site and click on setup.exe. and select type openssh in search box of search box in Selected Package as below and install required dependencies.




Once Cygwin is installed in your system, make sure that it works.

2. makesure you set JAVA_HOME point to jdk1.5 or jdk1.6 in your environment variable


3. try to unpack the hadoop hadoop rar distribution In the distribution,


trpe the below command
c:\ bin/hadoop

Now you are ready to start hadoop node


Other tutorial that you may like.
Learn Basics of HDFS in Hadoop
Introduction to Hadoop
Difference between Distribute File System and Normal File System


Tuesday, 22 November 2011

Find last Element/Object of ArrayList

Most of the times we encountered the situation to read the first element of ArrayList using get(0) method. In Some instances you want to read the last element of anArray List, you can use the following code snippet.
ArrayList list=new ArrayList();
list.add("one");
list.add("two");
list.add("three");
list.add("four");

To Access the fourth object, we have to use list.get(list.size()-1). Here size() method returns the size of the list and size -1 return the last index of the list. Note:-

In runtime if there are no elements in the list,if you call method list.get(list.size()-1), it will throws IndexOutOfBoundsException. always make sure that you call this method if list is not empty or null check.

Here is the code snippet
if((list!=null)||(list.size()>0){
String lastElement=(String) list.get(list.size()-1);
}

Sunday, 20 November 2011

Unix Interview questions

In Unix environment we have sevaral frequent used commands to work 1. What is relative path and absolute path Absolute path:- It is the path from the root directory to current directory Relative Path:- It is the relative path from the current directory. 2.What are SHELL OR BASH SHELL variables. SHELL or BASH variables are symbolic names which assigned the names. 3.how do

Friday, 18 November 2011

Pros and Cons of Design patterns

In Software development, reusable code to solve the frequent problems occured in the designation of any system In OOPS programming, we have several design patterns the following are the Populare design patters
There are different categories types of design patterns in object oriented programming



1. Creation patterns:- This type of patterns are used to describe the object creation in best possible ways in different contexts . Singleton is the example
2.Structural design patterns:-

3. Behavioral design pattern


Advantages of design patterns:-


1.Improves the performance of the system.
2.Solve the bottleneck of the problem.
3.Best design for the system is possible
4.Improves the code for writing in more object oriented way like inheritance and encapsulation

Disadvantage of the Design patterns:-


As per me, he more code is introduced in the current existing system for better design.
As design patterns are for best design, More complex to understand the system.

Please leave if you see any pros and cons of design patterns.


3.

Singleton Design pattern

Singleton design pattern is one of the design pattern to maintain the single instance of object in a system. whenever object created using new Object() code, one new instance created, if we call this multiple instances are created in heap memory. Over the time the calls to the new objects grows, size of the object size grows in the heap memory and it will cause performance overahead. To avoid this, we will make the one object creation for multiple calls and return the same object

Example:-
public class Singleton {
 /*
  * Initializing the static member variable as null
  */
 public static Singleton single = null;

 /*
  * private means, we can not create any object using new operator outside
  * this class
  */
 private Singleton() {

 }

 /*
  * this method always return same instance. you can make this method as
  * synchronized to create amultiple isntances by different thread at a time
  */

 public static Singleton getInstance() {
  if (single == null) {
   single = new Singleton();
  }
  return single;
 }

 /*
  * clone is not supported and throws exception if we make the clone of this
  * object
  * 
  * @see java.lang.Object#clone()
  */
 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException(
    "This is singleton class, cloning is not supported");
 }

 public static void main(String args[]) {
  /*
   * calling the multiple getInstance method always returns the same
   * instance
   */
  System.out.println("Object=1 " + getInstance());
  System.out.println("Object=2 " + getInstance());
 }
}
Advantage:-

This pattern maintains one instance of java object in heap memory of java virtual machine instead of creating multiple instances. Improve the performances and less objects created for heap memory

Tuesday, 15 November 2011

Linux and Unix PS commands

PS abbreviated as process status command list information about the active process running in the linux/unix machine.this command list out all the active running process

. Command #1:- ps -aef list all the process in system.

Command #2:- ps -aef| grep java We can use ps command piping with grep .List all the process in the linux/unix with name java.

Command #3:- Kill proceesId to kill the process which has id of process. we can use kill -9 pid for forcible killing the process.

Command #3:- Killall proceesName to kill the process which has name of process.

Command #4:- Kill 0 to stop all the process.

Friday, 11 November 2011

How to avoid ConcurrentModificationException for map or List

ConcurrentModificationException exception is occurred because of while one thread is iterating the collections and other thread trying to modify the object in collections. This will be happened for below map and list of collections. 1. Modifying state of any key or value in map implementations(example,HashMap,HashTable,LinkedHashMap) during iteration of Map objects 2.Adding/remove(Iterator.remove) the object in a collections class while iteration of collection of objects at the same time. you can use ConcurrentHashMap for avoiding this exception but there is no guarantee of all your objects are iterated. Solution is use map.entrySet for modifying object while iteration HashMap mapDemo = new HashMap(); mapDemo.put("key-1", "value-1"); mapDemo.put("key-2", "value-2"); mapDemo.put("key-3", "value-3"); for (Map.Entry entry : mapDemo.entrySet()) { if (entry.getKey().contains("key-2")){ entry.setValue("new Value-2"); } } for (Map.Entry entry : mapDemo.entrySet()) { System.out.println(entry.getKey()+"==="+entry.getValue()); } } and the output is:- key-1===value-1 key-2===new Value-2 key-3===value-3

Friday, 18 February 2011

zgrep and zcat ussage

finding content in uncompressed files (extension, gzip).

In a directory, there are many .gz files , how do we search for a particulary word in those files.
one solution is to unzip the .gz file and use the grep command.

Here are the steps

gunzip filename.gz
grep "searchword" file


The other and better solution is using zgrep command in unix

zgrep "search word" filename.gz

grep comand work on text files, zgrep works on compressed logs.

To view the compressed files, use zcat command in linux or unix

Thursday, 3 February 2011

Maven dependency example explained

One of the feature of maven over ant tool is dependencies management for software projects.
When you are using maven in your project, you need to define the dependencies in pom.xml,once the dependencies are defined , these will be downloaded into your local machine from repositories. To configure the dependencies , you have to use the dependency plugin which manipulates the artifcats when you are installing with maven
So here is sample code snippet for configuring spring-core to your project


org.springframework
spring-core
2.5.6





When you compiled, your project downloads spring-core jar for the first time from the spring repository server. You also should have to configure repository server in pom.xml with the following piece of code.


spring-release
http://repository.springsource.com/maven/bundles/release




So you can configure multiple repositories, the order of repositories that looks for the artifact should have to mention in the order in pom.xml
What is transitive dependency in maven ?
For example,Take the scenario, what happened if spring-core artifact has log4j as one of dependency. Should log4j dependency also download into your local project? Yes all the direct dependencies should resolve automatically. Transitive dependency meaning is that all the dependencies resolves for your project transitivily configured in pom.xml.



In this example, your project is configured only spring-core, but your project has indirect dependcies log4j and jmx which are depenendnt to spring-core. So maven resolves all these dependencies and your project has all direct and indirect these dependencies.
Your project 1.0.0 has spring-core-2.5.6 direct dependency, log4j-1.2.12 and jmx-1.0.2 indirect dependencies


As per your project needs, you want to use log4j-1.2.14 only, but as per above spring-core dependency you got log4j-1.2.12 as dependency. So you have to avoid log4j-1.2.12 dependency.

For this we have to use exclusion tag in pom.xml in dependency tag. Following is the code snippet


org.springframework
spring-core
2.5.6


log4j
log4j




log4j
log4j
1.2.14



This topic has been a very basic start to explore on maven dependency example. Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.