String is Immutable - String Vs String builder

String is Immutable - String Vs String builder

String is immutable

  • String a=”a”; address is 12345
  • a=”b”; address will be 3456
  • String a=new String(“a”);
  • Will create one object in String pool and create one more object for new operator will get created and that will point to it.
  • String a=”a”; will create object in string pool and object a will point to it.

StringBuffer is mutable

  •  StringBuffer b=”a”; address is 12345
  •  b=”b”; address is 12345
  •  This is synchronized

StringBuilder : This is similar to StringBuffer but this is not synchronized


Read more

Inner join Vs Outer join

Inner join Vs Outer join

This is most common interview question for many developers ... I would like to give a easy understanding of this to remember for life ...

  •     An inner join of A and B gives the result of A intersect B, i.e. the inner part of a venn diagram intersection.
  •     An outer join of A and B gives the results of A union B, i.e. the outer parts of a venn diagram union.

Suppose you have two Tables, with a single column each, and data as follows:

A    B
-    -
1    3
2    4
3    5
4    6

Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.

Inner join

An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.

select * from a INNER JOIN b on a.a = b.b;
select a.*,b.*  from a,b where a.a = b.b;

a | b
3 | 3
4 | 4

Left outer join

A left outer join will give all rows in A, plus any common rows in B.

select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*,b.*  from a,b where a.a = b.b(+);

a |  b 
1 | null
2 | null
3 |    3
4 |    4

Full outer join

A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.

select * from a FULL OUTER JOIN b on a.a = b.b;

 a   |  b 
   1 | null
   2 | null
   3 |    3
   4 |    4
null |    6
null |    5


Inner join


Full Outer join


Reference : [1]

Read more

Polymorphism - Java - Examples static, dynamic, runtime - overloading - overriding

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

Polymorphism can exists in two ways... 1. Static polymorphism - Overloading
2. Dynamic polymorphism  - Overriding

Overloading : Creating mutiple methods with same name in a class but with different signatures (either number of parameters should be different or type of parameters should be different in each method)
Overriding :  Creating same method same parameters but with different behavior in both super class and extended class is called as overriding.

Dynamic binding is nothing but choosing which method to chose when super class object is created with extended class type.
Please have a look at the below program and output to understand the polymorphisms...

public class Ploymorphism {

public interface Vegetarian{
void eatVeg();
public class Animal{
void eat(){
System.out.println("All animals can eat");
public class Deer extends Animal implements Vegetarian{

public void eat(String veg) {
System.out.println("I am eating :"+veg);
public void eatVeg(){
System.out.println("I eat only veg");

public class Tiger extends Animal{
void eat(){
System.out.println("I'm tiger, I eat what I want");
void eat(String veg, String nonveg){
System.out.println("I can eat:"+veg+" and "+nonveg);
public static void main(String[] args) {
System.out.println("Java has two types of polymorphism");
System.out.println("1.Static Polymorphism : Achived using \"overloading\" ");
Ploymorphism p = new Ploymorphism();
Tiger tiger = Tiger();"leaves", "creatures");
System.out.println("Tiger has two methods with same name but with different paramaetrs/ signatiures(either no of parameters should be different or type of paramters should be different)");
System.out.println("2.Dynamic Polymorphism : Achived using \"overriding\" ");
Deer deer = Deer();"carrot");
System.out.println("deer is extended from animal but eat method has different in the deer than animal class- it is overriding");
Animal whiteTiger = Tiger();;
//System.out.println("The above commented line gives error as there is no eat method of such type in the animal class");



Ouput of the above program :

Java has two types of polymorphism
1.Static Polymorphism : Achived using "overloading"
I can eat:leaves and creatures
Tiger has two methods with same name but with different paramaetrs/ signatiures(either no of parameters should be different or type of paramters should be different)
2.Dynamic Polymorphism : Achived using "overriding"
I am eating :carrot
deer is extended from animal but eat method has different in the deer than animal class- it is overriding
I'm tiger, I eat what I want


Reference : [1] [2] [3]

Read more

Collections - Java

Introduction to Collections

A collection  sometimes called a container  is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers). If you have used the Java programming language  or just about any other programming language  you are already familiar with collections.

What Is a Collections Framework?

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

    Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
    Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
    Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

Benefits of the Java Collections Framework

The Java Collections Framework provides the following benefits:

  •     Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. By facilitating interoperability among unrelated APIs, the Java Collections Framework frees you from writing adapter objects or conversion code to connect APIs.
  •     Increases program speed and quality: This Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance.
  •     Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a collection of node names and if your GUI toolkit expects a collection of column headings, our APIs will interoperate seamlessly, even though they were written independently.
  •     Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away.
  •     Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.
  •     Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.

The core collection interfaces encapsulate different types of collections, which are shown in the figure below. These interfaces allow collections to be manipulated independently of the details of their representation. Core collection interfaces are the foundation of the Java Collections Framework. As you can see in the following figure, the core collection interfaces form a hierarchy.

Core collection interfacces

  • The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
  •  HashTable : Whenever a program wants to store a key value pair, one can use Hashtable.
  • Set :      The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
    • Implements Collection Interface
    • Does not allow duplicate
    • EnumSet (classes)
    • HashSet (classes) : HashSet uses map to store. It stores element as KEY and "PRESENT" object as VALUE.
    • Sortedset (Interface)
      • Ascending order
      • Does not allow duplicate
      • TreeSet (classes)
      • LinkedHashSet (classes)
  • List :  The List interface provides support for ordered collections of objects.
    • Implement collection Interface
    • Can contain duplicate and it’s ordered
    • Stack class implements list interface
    • Linked List class implements list interface
    • Vector (classes) - Syncronized : The Vector class provides the capability to implement a growable array of objects.Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
    • ArrayList (classes) - nonsynchronized . Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.
    •  The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
    • How to sort list in reverse order?How to sort list in reverse order?
      • This question is just like above to test your knowledge of Collections utility class. Use it reverse() method to reverse the list.
        List reversedList = Collections.reverse(list);
    • cc
  • Queue
  • De-queue:
  • Map: Map interface is a special type of collection which is used to store key-value pairs. It does not extend Collection interface for this reason.Main classes implementing Map interface are:
    • HashMap,
    • Hashtable,
    • EnumMap,
    • IdentityHashMap,
    • LinkedHashMap,
    • Properties.
  • When to use HashMap or TreeMap?
    • TreeMap is special form of HashMap. It maintains the ordering of keys which is missing in HashMap class. This ordering is by default “natural ordering”. The default ordering can be override by providing an instance of Comparator class, whose compare method will be used to maintain ordering of keys.
  • SortedMap :
  • To remember :
  • Legacy collection frame works are Synchronized:
    •     Vector
    •     stack
    •     dictionary
    •     hashTable
    •   Properties
  • New collection framework are not synchronized:
    • LinkedList
    •     ArrayList
    •     HashSet
    •     TreeSet
    •     HashMap
    •     TreeMap


Some famouse repeated interview questions :

Difference between Set and List?

The most noticeable differences are :

  • Set is unordered collection where List is ordered collection based on zero based index.
  • List allow duplicate elements but Set does not allow duplicates.
  • List does not prevent inserting null elements (as many you like), but Set will allow only one null element.

Difference between List and Map?

Perhaps most easy question. List is collection of elements where as map is collection of key-value pairs. There is actually lots of differences which originate from first statement. They have separate top level interface, separate set of generic methods, different supported methods and different views of collection.

I will take much time hear as answer to this question is enough as first difference only.

Difference between HashMap and HashTable?

There are several differences between HashMap and Hashtable in Java:

  • Hashtable is synchronized, whereas HashMap is not.
  • Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  • The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not.

Difference between Vector and ArrayList?

Lets note down the differences:

  • All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized.
  • Vector is a Legacy class added in first release of JDK. ArrayList was part of JDK 1.2, when collection framework was introduced in java.
  • By default, Vector doubles the size of its array when it is re-sized internally. But, ArrayList increases by half of its size when it is re-sized.

Difference between Iterator and Enumeration?

Iterators differ from enumerations in three ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with its remove() method. You can not add/remove elements from a collection when using enumerator.
  • Enumeration is available in legacy classes i.e Vector/Stack etc. whereas Iterator is available in all modern collection classes.
  • Another minor difference is that Iterator has improved method names e.g. Enumeration.hasMoreElement() has become Iterator.hasNext(), Enumeration.nextElement() has become etc.

Difference between HashMap and HashSet?

HashMap is collection of key-value pairs whereas HashSet is un-ordered collection of unique elements. That’s it. No need to describe further.

Difference between Iterator and ListIterator?

There are three Differences are there:

  • We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.
  • By using Iterator we can retrieve the elements from Collection Object in forward direction only whereas List Iterator, which allows you to traverse in either directions using hasPrevious() and previous() methods.
  • ListIterator allows you modify the list using add() remove() methods. Using Iterator you can not add, only remove the elements.

Difference between TreeSet and SortedSet?

SortedSet is an interface which TreeSet implements. That’ it !!

Difference between ArrayList and LinkedList?

  • LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
  • LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list. ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.
  • LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node.

Reference : [1] [2]

Read more

Java - J2EE Interview Preparation

Java - J2EE Interview Preparation
 Method overloading means having two or more methods with the same name but different signatures in the same scope. These two methods may exist in the same class or another one in base class and another in derived class.Generally, you should consider overloading a method when you have required same reason that take different signatures, but conceptually do the same thing.
Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class.
Overriding methods
Overriding method definitionsIn a derived class, if you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the base class, this new definition replaces the old definition of the method.
A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass to modify the methods defined in the superclass. This is referred to as method overriding. The following example demonstrates method overriding.
  • Constructor
  •      It will invoke when an object is instantiated.
  •      Will have same name as class name.
  •      This will not have any return type. Not even void.
  •       It will be called only once when an object is created.
  •       It cannot be override.
  •       It can be overload.
  • Interface Vs Abstract class
  • Final 
    •  Members, Variables are final means Constant
    •  Method is final means cant override
    • Class is final means cant inherit i.e. cant extend
  • Finally
    • The code which needs to executed before even if any exception occurs or not.
  • Finalize
    • If any resource needs to be freeze before the object gets destroyed we can use finalize Garbage collector internally call finalize.
  • Inheritance
    • Taking the properties of another class
  • Encapsulation
    • Wrapping the member and method with the use of access specifiers to prevent from the outside use
  • Exceptions:  Throwable >>
    • Error (checked exception) compile time exception no such Method,class not found exception
    • Exception (unchecked exception) runtime exception Index out of bounce, Null pointer exception
  • Try :
    • Nested try is allowed try can have either catch or finally
    • Exception should be on top and IOException sub class should be in down that the order
    • try{}catch(IOException){}catch(Exception)
  • Catch  : Catches the exception and handle it.
  • Finally : It will execute the code no matter whether the exception is catches or not.
  • Throw : To manually throw an exception
  • Throws : Any exception that will throws by an system built-in exception.
  • Threads : Running multiple process in a sequence .
    • Threads shares same heap memory but different stack memory
    • Two ways of creating threads : Extends thread and  Implements Runnable Interface
    • What are the different states of a thread's life-cycle?Ans) The different states of threads are as follows:
      1) New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
      2) Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
      3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
      4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked.
      5)      Dead – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a run-time exception will occur.
    • Sleep Vs Wait ?
      1) wait is called from synchronized context only while sleep can be called without synchronized block.
      2) wait is called on Object while sleep is called on Thread.
      3) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awaken by calling notify method.
      4) wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread on sleep.
      5) wait release lock on object while waiting while sleep doesn’t release lock while waiting.
      6) The notifyAll() method must be called from a synchronized context.
    • What is garbage collection? What is the process that is responsible for doing that in java?
      Ans : Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process.
    •  What kind of thread is the Garbage collector thread?
      Ans. It is a daemon thread.
    • What is a daemon thread?
      Ans : These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
  • Synchronization : It is the process of making only one thread to access the resource at a time by using synchronized(this) .
    • we can use synchronize block also to avoid the deadlock condition
  • String Vs StringBuffer : Read more about this here :
  • Static class loading : Class will be loaded statically with new operator
  • Dynamic class loading : Class.forName(); string class name
  • Connection pool :
    • It's a technique to allow multiple clinets to make use of a cached set of shared and reusable connection objects providing access to a database.
    • Opening/Closing database connections is an expensive process and hence connection pools improve the performance of execution of commands on a database for which we maintain connection objects in the pool.
    • It facilitates reuse of the same connection object to serve a number of client requests.
    • Every time a client request is received, the pool is searched for an available connection object and it's highly likely that it gets a free connection object.
    • It's normally used in a web-based enterprise application where the application server handles the responsibilities of creating connection objects, adding them to the pool, assigning them to the incoming requests, taking the used connection objects back, returning them back to the pool, etc.
  • Wrapperclass : As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object and give back the data type. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
    • Example :
    • int k = 100;
    • Integer it1 = new Integer(k);
    • The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.
  • Session tracking :
    • By using URLRewriting
    • Using session object
    • Using cookies
    • Using hidden fields
  • Collections : Read this article for more information on collecitons

  • Sorting list in collection - using sort method : refere this article for more information :
  • JSP Scripting elements :
    • JSP scripting elements enable you insert Java code into the servlet that will be generated from the current JSP page.
      • There are three forms:
        •     Expressions of the form <%= Java_expression%> that are evaluated and inserted into output, Example :Your hostname: <%= request.getRemoteHost() %>
        •     Scriptlets of the form <% java_code %> that are inserted into the servlets service method, and Example : <%
          String name = request.getParameter("name");
          out.println("name: " + name);
        •     Declarations of the form <%! Java_code %> that are inserted into the body of the servlet class, outside of any existing methods. Example : <%!
          public int getValue(){
              return 78;
  • Difference between JSP & Servlet : Servlet is html in java ,     JSP is java in html .  JSP is a webpage scripting language that can generate dynamic content while Servlets are Java programs that are already compiled which also creates dynamic web content.In MVC, jsp act as a view and servlet act as a controller.
  • What is the servlet lifecycle?

    Instantiation and initialization
    The servlet engine  creates an instance of the servlet. The servlet engine creates the servlet configuration object and uses it to pass the servlet initialization parameters to the init() method. The initialization parameters persist until the servlet is destroyed and are applied to all invocations of that servlet.
    Servicing requests
    The servlet engine creates a request object and a response object. The servlet engine invokes the servlet service() method, passing the request and response objects.
    The service() method gets information about the request from the request object, processes the request, and uses methods of the response object to create the client response. The service method can invoke other methods to process the request, such as doGet(), doPost(), or methods you write.
    The servlet engine stops a servlet by invoking the servlet's destroy() method. Typically, a servlet's destroy() method is invoked when the servlet engine is stopping a Web application which contains the servlet. The destroy() method runs only one time during the lifetime of the servlet and signals the end of the servlet.
    After a servlet's destroy() method is invoked, the servlet engine unloads the servlet, and the Java virtual machine eventually performs garbage collection on the memory resources associated with the servlet.
  • Design patterns : Refer this link for more information on designpatterns :
  • Webservices :
    • Web services are Web based applications that use open, XML-based standards and transport protocols to exchange data with clients. Web services are developed using Java Technology APIsWeb services are Web based applications that use open, XML-based standards and transport protocols to exchange data with clients. Web services are developed using Java Technology APIs.
    • Web services are client and server applications that communicate over the World Wide Web’s (WWW) HyperText Transfer Protocol (HTTP). As described by the World Wide Web Consortium (W3C), web services provide a standard means of interoperating between software applications running on a variety of platforms and frameworks. Web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions, thanks to the use of XML.
  • Simple Webservice code for online Webservice Stock Quote 
  • Hibernate :
    • Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.
    • Hibernate's primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from manual result set handling and object conversion. Applications using Hibernate are portable to supported SQL databases with little performance overhead
    • If you are designing the database schema and your domain objects afresh.
    • You envision that your domain objects and your schema will be in sync, for example an automobile vendor application where your vehicle objects are likely to be close to your table structures. Just an example.
    • You really want to use an ORM and tie your objects closely to schema.
    • Want to use a ORM framework to handle connections etc.
  • Struts :
    • Apache Struts is a web page development framework and an open source software that helps developers build web applications quickly and easily. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework.
    • Struts is based on famous MVC design pattern.The role played by Structs is controller in Model/View/Controller(MVC) style. The View is played by JSP and Model is played by JDBC or generic data source classes. The Struts controller is a set of programmable components that allow developers to define exactly how the application interacts with the user.
    • core classes of Struts: Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.
    • configuration files used in Struts : , struts-config.xml .These two files are used to bridge the gap between the Controller and the Model.

  • JDBC :
  • SQL Injection :
  • xcfd
 References : [1] [2] [3] [4]

    Read more

    How to manage Websphere Profiles ? Create , delete websphere profiles

    How to manage Websphere Profiles ? Create , delete websphere profiles

    Below are some handy commands to use while working with Websphere manageprofiles.bat / .sh

    To create a profile :
    ./ -create -templatePath /opt/IBM/WebSphere/AppServer/profileTemplates/default/ -profileName AppSrv01 -profilePath /opt/IBM/WebSphere/AppServer/AppSrv01

    To list all the profiles:
    <Webesphere_installed_location>\bin\manageprofiles.bat -listProfiles

    c:\Program Files\IBM\WebSphere\AppServer\bin>manageprofiles.bat -listProfiles

    To delete particular profile:
    <Webesphere_installed_location>\binmanageprofiles.bat -delete -profileName <Profile_Name>

    c:\Program Files\IBM\WebSphere\AppServer\bin>manageprofiles.bat -delete -profileName JazzSMProfile

    To delete all the Websphere profiles:
    <Webesphere_installed_location>\bin\manageprofiles.bat -deleteAll

    c:\Program Files\IBM\WebSphere\AppServer\bin>manageprofiles.bat -deleteAll

    Read more

    Using Websphere(WAS) API in Java class to get WAS server details

    Using Websphere(WAS) API in Java class to get WAS server details

    Here is a simple Java class which WAS(Websphere) API's to get WAS(Websphere) server details like cellname and nodename etc.

    To make the below java class work we need to Jar files to be added to build path in our eclipse . These jar files will be available in WAS 851 installaiton.

    C:\Program Files\IBM\WebSphere\AppServer\runtimes\

    C:\Program Files\IBM\WebSphere\AppServer\plugins\

    Java class: 


    import java.util.Iterator;

    import java.util.Set;




    public class AdminClientTest {

    public static void main(String[] args) {

    AdminClient ac = null;

    java.util.Properties props = new java.util.Properties();

    props.put(AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);

    props.put(AdminClient.CONNECTOR_HOST, "localhost");

    //16313 : bootstrap port , check corresposding port from ur Aboutheprofile.txt

    props.put(AdminClient.CONNECTOR_PORT, "16313");

    props.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, "true");

    props.setProperty(AdminClient.USERNAME, "UR_PROFILE_USERNAME");

    props.setProperty(AdminClient.PASSWORD, "UR_PROFILE_PASSWORD");

    // Trust store properties

    props.setProperty("","C:\\Program Files\\IBM\\JazzSM\\profile\\etc\\DummyClientTrustFile.jks");

    //WebAS : this is a default password to be used . Don't change this


    // Key store props

    props.setProperty("", "C:\\Program Files\\IBM\\JazzSM\\profile\\etc\\DummyClientKeyFile.jks");

    //WebAS : this is a default password to be used . Don't change this

    props.setProperty("", "WebAS");

    try {

    ac = AdminClientFactory.createAdminClient(props);

    System.out.println ("connected"); on = new ObjectName("WebSphere:type=Server,*");

    Set servers = ac.queryNames(on, null);

    Iterator itr = servers.iterator();





    catch(Exception ex) {

    System.out.println("getAdminClient: exception");





    Sample Output : 





    Reference : WAS 6.1 JMX AdminClient. (Websphere forum at JavaRanch)

    Read more

    Tutorial on Eclipse plugin extension-points and extensions - Simple step by step aproach

    Tutorial on Eclipse plugin extension-points and extensions.

    This is a basic tutorial on how to create a simple base eclipse plugin which will have extension-point defined and also creating another eclipse plugin which will have extension to hook to existing extension-point in base plugin.
    this whole tutorial has two primary tasks and they are
    1.Creating a base plugin having an extension point definition.
    2.Creating an extension plugin which implements the base extension point.

    Creating a base plugin having an extension point definition.
    Now let's see how this base plugin will be created which will have definition to a extension-point.
    Once after opening your eclipse in plug-in-development perspective, create a new project by name Base Plugin.
    1. Create a new eclipse plugin project from File > New

    2. Give it a name ex : Base Plugin

    3.Provide the vendor name , un-check Generate activator stuff.

    4.Select one of the Template , in this tutorial im using Command ... 

    5.Modify the below fields Message box Text etc.. 

    6. Now modify the plugin.xml file in the project created to that custom menu names and sub menus will be displayed.
    Modified plugin XML code looks like below ..

    7. Now right click on the Base plugin project and run it as eclipse plugin project. 

    8. Now you should see new eclipse plugin instance opened up showing a new menu item along with the default menu items with name Base plugin command.

    9.Just select the command and see the output for the base plugin we have created.

    Same post will be updated soon with steps to modify the base plugin to facilitate with definition of extension point and creating another plugin which will extend the extension defined in base with their own implementations.

    Read more

    wget command to copy directory containing multiple sub directories and files

    wget command to copy directory containing multiple sub directories and files

    Below is a simple WGET command which will download a folder recursively with its sub directories and files. 

    wget -r  --no-parent --http-user XYZ--http-passwd XYZ--no-check-certificate

    Simple explanation : 

    -r : Recursively copies 

    --no-parent : Do'nt copy the parent siblings. only downloads from the specified subdirectory and downwards hierarchy.

    --http-user : Username 

    --http-passwd : Password 

    --http-passwd : Accept https certificates if any .

    Read more

    batch script : date time stamp in file names for any date format

     batch script : date time stamp in file names for any date format

    Many of us seen failures in creating a file name when parsing output from date and time environment variables through batch script . Because of different spaces and delimiters like - or / or : etc used in the date output . So to avoid such problems and make a strong batch script which can generate file names uniquely with help of Date and time is to use VB script along with Batch script .

    So in the below code snippets I'm attaching one VB script and one batch script . Batch script internally calls the VB script to fetch correct year , month , date , hour , min and seconds.

    VB script code : 

    Wscript.Echo("set Year=" & DatePart("yyyy", Date))
    Wscript.Echo("set Month=" & DatePart("m", Date))
    Wscript.Echo("set Day=" & DatePart("d", Date))
    Wscript.Echo("set Hour=" & DatePart("h", time))
    Wscript.Echo("set Min=" & DatePart("m", time))
    Wscript.Echo("set Sec=" & DatePart("s", time))

    Batch script code: 

    @echo off
    echo Using VB SCRIPT
    for /f "delims=" %%x in ('cscript /nologo date.vbs') do %%x
    set TIMESTAMP=%Year%%Month%%Day%%Hour%%Min%%Sec%
    echo %TIMESTAMP%
    set fileName=my_%TIMESTAMP%.log
    echo File name(With time stamp): %fileName%
    echo Using Normal Way
    echo DATE : %date%
    set yy=%date:~-4%
    set mm=%date:~-7,2%
    set dd=%date:~-10,2%
    set MYDATE=%yy%%mm%%dd%
    Call Set "MYDATE=%%MYDATE: =%%"
    echo %MYDATE%
    echo TIME: %time%
    set hh=%time:~-11,2%
    set mm=%time:~-8,2%
    set ss=%time:~-5,2%
    set ms=%time:~-2,2%
    set MYTIME=%hh%%mm%%ss%%ms%
    Call Set "MYTIME=%%MYTIME: =%%"
    echo %MYTIME%
    set fileName=my_%MYDATE%%MYTIME%.log
    echo %fileName%

    Enhanced by Zemanta

    Read more

    How to run a shell script with different user with in another shell script ?

    How to run a shell script with different user from/with in  another shell script ?
    Some times it is required to run a shell script with a specific OS user from another shell script, in such cases we can call the actual shell script with following options from another shell script.
    Here important thing to understand is one line ...
    /bin/su - -c ""
    /bin/su : it helps to call su binary to swith user
    -c option tells the command to run

    009:/opt # cat
    echo "in one"
    /bin/su - smadmin -c "/opt/"

    009:/opt # cat
    echo "in two"
    ls -lrt

    009:/opt # cat
    echo "ant_exec return code is $RC"
    exit $RC

    So when we run the script which calls one and internally calls will show output like below ...
    009:/opt # ./ /opt/
    in one
    in two
    uid=1009(smadmin) gid=112(db2iadm1) groups=16(dialout),33(video),111(dasadm1),112(db2iadm1)
    total 12
    drwxr-xr-x  2 smadmin db2iadm1 4096 2013-01-02 20:57 bin
    drwxrwsr-t 24 smadmin db2iadm1 4096 2013-01-14 12:37 sqllib
    drwxrwxr-x  3 smadmin db2iadm1 4096 2013-02-01 16:28 smadmin
    ant_exec return code is 0

    Read more

    How to set / get windows environment variables through Java code?

    How to set / get windows environment variables through Java code?

    Below simple program is self explained on how to use set / get the windows environment variables.

        import java.util.*;  
        public class Test  
            public static void main(String[] args) throws Exception  
                ProcessBuilder pb = new ProcessBuilder("CMD.exe", "/C", "SET"); // SET prints out the environment variables  
                Map env = pb.environment();  
                String path = env.get("Path") + ";C:\\cygwin\\bin";  
                env.put("Path", path);  
                Process process = pb.start();  
                BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));  
                String line;  
                while ((line = in.readLine()) != null)  

    Read more

    Setting windows environment variable through Java code

    Setting windows environment variable through Java code...

    The below is a simple Java class code which will pass few parameters to a method which get's validated against null and empty conditions and then a process will be started with those values.

    Basically one batch script or shell script gets run depending on the OS name found from environment .. it sets two environment variables in the operating system.
    import java.util.Map;
    public class IfixConfig {
      * @param args
      * @param MYPRODUCT_Home
      * @param WAS_username
      * @param WAS_password
      * @param iFixLocation
     public static void main(String[] args) {
      // TODO Auto-generated method stub
      System.out.println("Starting IFIX configuration");
      String MYPRODUCT_Home = "C:\\Program Files\\XYZ\\MYPRODUCT";
      String WAS_username = "smadmin";
      String WAS_password = "g0vmware";
      String iFixLocation = "C:\\Program Files\\XYZ\\MYPRODUCT\\ui\\ifixes\\\\0001";
      int result = ifixConfig(MYPRODUCT_Home, WAS_username, WAS_password,
      System.out.println("Result:" + result);
     private static int ifixConfig(String MYPRODUCT_Home, String wAS_username,
       String wAS_password, String iFixLocation) {
      int resultCode = -1;
      try {
       System.out.println(MYPRODUCT_Home + wAS_username + wAS_password
         + iFixLocation);
       ProcessBuilder pb = null;
       String postConfigScript = iFixLocation + "/post_install_configure.";
       if (wAS_username != null && !(wAS_username.isEmpty())
         && wAS_password != null && !(wAS_password.isEmpty())) {
        System.out.println("WAS username and passwords provided");
        if (System.getProperty("").startsWith("Windows"))
         postConfigScript = postConfigScript + "bat"; 
          pb = new ProcessBuilder("CMD.exe", "/C", postConfigScript);  
         postConfigScript = postConfigScript + "sh" ;
         pb = new ProcessBuilder(postConfigScript);
        System.out.println("Post config script:"+postConfigScript); File(iFixLocation));
        Map env = pb.environment();
        env.put("MYPRODUCT_WAS_PASSWORD", wAS_password);
        Process process = pb.start();
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
         if ( line.equals("BUILD SUCCESSFUL")){
          resultCode = 0 ;
       } else {
        System.out.println("WAS username and password should not be empty");
      } catch (Exception e) {
      return resultCode;

    Read more

    Shell Script Tips -1

    The below shell scripts are typical example codes which helps us to understand certain frequently used codes.

    1. How to get the absolute or full path while calling another shell script from one shell script.

    source $(readlink -f "") uninstall

    The above code snippet calls another shell script by name which is available in the same directory of current script.
    Abosolute path will be used with the readlink -f option there. uninstall isa parameter passed to it.

    2. How to check how many parameters are passed in to a shell script..
    if [ $# != "1" ]; then
        echo "Usage: install or uninstall"
    $# represents total number of parameters passed to a shell script when called.
    In the above example code if at least one parameter is not passed it throws a message and exits.

    3. How to check if a variable is set or not . How to check if a viariale has empty string ?

        if [ -z $LOCALE_CODE ];
            then JAZZSM_SYSTEM_LOCALE="en_US"

    In the above example snippet we are setting some value for LOCALE_CODE if in case it is not set for some reason -z option with if condition returns true
    so in above example if it( if [ -z $LOCALE_CODE ] ) is true  it will set it to en_US

    4. How to get the parent directory path of a file or directory ?

        PresentDir=`dirname $PWD` 

    When dirname is given a pathname, it will delete any suffix beginning with the last slash ('/') character and return the result.
    For example:

     $ dirname /usr/home/carpetsmoker/

    5. How to get the only filename when absolute path is given ?


        $ basename /home/jsmith/

        $ basename /home/jsmith/ .wiki

        IFIX_NO=`basename $PWD`

    6.     How to read a properties file in shell script  ?

        # Reading to find IM Install location
        IM_HOME=`sed '/^\#/d' $PropertiesFile | grep 'product.install.location'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
        echo IM Install Location is : $IM_HOME
        Example :
        $PropertiesFile contents are like below ..
        #Fri, 01 Mar 2013 02:59:37 -0500

        The while process is to Scan through the file to get an individual property

        This works well if you just want to read a specific property in a Java-style properties file. Here's what it does:

        * Remove comments (lines that start with '#') >> sed '/^\#/d'
        * Grep for the property >>  grep 'someproperty' 
        * Get the last value using >> tail -n 1
        * Strip off the property name and the '=' (using {{cut -d "=" -f2-}) to handle values with '=' in them).

         sed '/^\#/d' | grep 'someproperty'  | tail -n 1 | cut -d "=" -f2-

        It can also be handy to strip off the leading and trailing blanks with this sed expression:


        Which makes the whole thing look like this:

        sed '/^\#/d' | grep 'someproperty'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'


    7.  How to check file existance before running it ?

    [ -f "$SCRIPT_LOCATION/" ] && . "$SCRIPT_LOCATION/"   

    Having quotes for the file path eliminates issues arise out of spaces in the path.

    8. How to read input values through shell script ?

        # Ask for WAS credentials
        if [ -z "${JAZZSM_WAS_USERNAME}" ]
          echo -n "${wasUserNamePrompt}: "
          read JAZZSM_WAS_USERNAME

    echo -n "${wasUserNamePrompt}: "     >> it helps to prompt user with particular string before commandline prompt while running shell script, in order to resolve wasUserNamePrompt string we need to run its correspinding properties file before this call .
    For example has text like below , and when it is run before the above command it will resolve this value.



    wasUserNamePrompt="Enter the Websphere Application Server user name:"

    wasPasswordPrompt="Enter the Websphere Application Server password:"

    Read more

    How to mount iso images on AIX and Linux?

    Let's assume if u have some ISO image files as  : IBM-jazzsm-launchpad-1.1-aix64.iso and IBM-was-
    and U want to mount them to two different directories which are freshly created under /mnt like below .. .WAS_ISO and JAZZ_ISO

    U have to run below commands to mount them now ...
    AIX :
    bash-3.2# ls
    IBM-jazzsm-launchpad-1.1-aix64.iso  IBM-was-
    bash-3.2# loopmount -i IBM-jazzsm-launchpad-1.1-aix64.iso -o "-V cdrfs -o ro" -m /mnt/JAZZ_ISO/
    bash-3.2# loopmount -i IBM-was-  -o "-V cdrfs -o ro" -m /mnt/WAS_ISO/

    Linux :
    Ex :
    1) Create the directory i.e. mount point:
        # mkdir -p /mnt/disk
    2) Use mount command as follows to mount iso file called disk1.iso:
        # mount -o loop disk1.iso /mnt/disk
    Thanks & Regards

    Read more

    Krishna's Page Android app download

    Since from the day I started using Android phone I thought of moving my site to App on phone which helps my site users to feel comfort of accessing information on my site, finally with the help of I'm able to move my Web content to a simple Android app (Krishna's Page) . Now it is active on Google play store . Users can download directly by searching Krishnas page on google play store and more over it is free app for your use. Click below to download
    Download link ..
    Start using it and write ur Reviews and commetns along with Rating :)

    Read more

    Eliminate invisible new line or blank charecters in a string using java

    Some times when we process string output from different other sources we will end up having invisible blank or new line or some tabbed characters which will annoy us from parsing that string for a particular thing. In that case while using Java we can use Trim method which helps a lot on this situation.

    Another great quality of this trim method is , it can remove blank like characters from both sides of strings .
    This method removes the blank spaces from both ends of the given string (Front and End).

    A Simple example below might be helpful to use this

    public class StringTrim{
      public static void main(String[] args) {
      System.out.println("String trim example!");
      String str = " [RoseIndia, hi, hello]   ";
      System.out.println("Given String :" + str);
      System.out.println("After trim :" +str.trim());

    OutPut :
    Given String : [RoseIndia, hi, hello]   
    After trim :[RoseIndia, hi, hello]

    Read more

    DB2 10 JDBC Strings to use in JAVA code

    Below is a simple example of java method which will return true if given database contains any table by name DB_VERSION. Else it returns false.

         * isRegistryDBConfigured()    method returns true if provided Database
         * contains table DB_VERSION. Returns false if it doesn't contain
         * that table.
        public boolean isRegistryDBConfigured(String dbName, String portNumber,String userName, String password) {
            try {
              String hostName = InetAddress.getLocalHost().getCanonicalHostName();
                StringBuffer dbConnectionURL = new StringBuffer("jdbc:db2://");
                dbConnectionURL.append(hostName + ":" + portNumber + "/" + dbName);
                Connection db2Conn = DriverManager.getConnection(
                        dbConnectionURL.toString(), userName, password);
    //Connection db2Conn = DriverManager.getConnection("jdbc:db2j:net://localhost:50000/frsdb","db2admin","db2admin");          
     // Connection db2Conn =  DriverManager.getConnection("jdbc:db2://localhost:50000/test","db2admin","db2admin");
                Statement st = db2Conn.createStatement();
                ResultSet resultSet = st.executeQuery(myQuery);
                while ( {
                    String name = resultSet.getString("TABNAME");
                    if (name.equals("DB_VERSION")) {
                        System.out.println("Tablename:" + name);
                        return true;
            } catch (Exception e) {
                System.out.println("EXCEPTION::" + e);
            return false;

    Read more

    Select particular table name from given database in db2

    Here is a simple DB2 - SQL  command to find a particular table name exists in given database name.


    Example :
    Database name : FRSDB
    Table Name : DB_VERSION

    C:\Users\ADMIN>db2 connect to frsdb

       Database Connection Information

     Database server        = DB2/NT64 10.1.0
     SQL authorization ID   = KRISHNA
     Local database alias   = FRSDB



      1 record(s) selected.


    Read more


    Enter your email address:

    Buffs ...


    hits counter
    View My StatsCheck Google Page Rank

    Add to Google Reader or Homepage

    Bookmark and Share


    Powered by WidgetsForFree