Monday, March 24, 2014

DB Connection and retrieving multiple data from the table

package DataBasetesting;

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

public class ConnectMSSQLServer {

    public static void main(String[] args) {
   
        ConnectMSSQLServer connServer = new ConnectMSSQLServer();

        //connServer.dbConnect("jdbc:sqlserver://localhost:1433;databaseName=Test;", "sa", "NSin@098");
        connServer.dbConnect("jdbc:sqlserver://localhost:1433;databaseName=test;", "sa", "password");
    }
       
   public void dbConnect(String db_connect_string, String db_userid,String db_password)

    {
Boolean isresultSet=false;
    try {

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

    Connection conn = DriverManager.getConnection(db_connect_string,

    db_userid, db_password);

    System.out.println("connected");

    Statement statement = conn.createStatement();

    //String queryString = "select * from sysobjects where type='u'";
   
    String queryString = "select * from Student";
    boolean results = statement.execute(queryString);
//    ResultSet result = statement.executeQuery(queryString);
    int rsCount = 0;
   
     do {
            if(results) {
               ResultSet rs = statement.getResultSet();
               rsCount++;

               //Show data from the result set.
               System.out.println("RESULT SET #" + rsCount);
               while (rs.next()) {
                  System.out.println(rs.getString("stno") + ", " + rs.getString("stname"));
               }
               rs.close();
            }
            System.out.println();
            results = statement.getMoreResults();
            } while(results);
     statement.close();
          }
       catch (Exception e) {
          e.printStackTrace();
       }
   

    }
}

Tuesday, March 18, 2014

DB Connection

package DataBasetesting;

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

public class ConnectMSSQLServer {

    public static void main(String[] args) {
   
        ConnectMSSQLServer connServer = new ConnectMSSQLServer();

        //connServer.dbConnect("jdbc:sqlserver://localhost:1433;databaseName=Test;", "sa", "ram@123");
        connServer.dbConnect("jdbc:sqlserver://localhost:1433;databaseName=test;", "sa", "Password");
    }
       
   public void dbConnect(String db_connect_string, String db_userid,String db_password)

    {

    try {

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

    Connection conn = DriverManager.getConnection(db_connect_string,

    db_userid, db_password);

    System.out.println("connected");

    Statement statement = conn.createStatement();

    String queryString = "select * from sysobjects where type='u'";
   

    ResultSet rs = statement.executeQuery(queryString);

    System.out.println("The Result Set is::"+rs.toString());

    while (rs.next()) {

    System.out.println(rs.getString(1));

    }

    } catch (Exception e) {

    e.printStackTrace();

    }

    }
}

Monday, March 17, 2014

Dependency Injections in Java interview Questions

 Dependency injection

TestNG supports two different kinds of dependency injection: native (performed by TestNG itself) and external (performed by a dependency injection framework such as Guice).
5.18.1 - Native dependency injection
TestNG lets you declare additional parameters in your methods. When this happens, TestNG will automatically fill these parameters with the right value. Dependency injection can be used in the following places:
  • Any @Before method or @Test method can declare a parameter of type ITestContext.
  • Any @AfterMethod method can declare a parameter of type ITestResult, which will reflect the result of the test method that was just run.
  • Any @Before and @After methods can declare a parameter of type XmlTest, which contain the current <test> tag.
  • Any @BeforeMethod (and @AfterMethod) can declare a parameter of type java.lang.reflect.Method. This parameter will receive the test method that will be called once this @BeforeMethod finishes (or after the method as run for @AfterMethod).
  • Any @BeforeMethod can declare a parameter of type Object[]. This parameter will receive the list of parameters that are about to be fed to the upcoming test method, which could be either injected by TestNG, such as java.lang.reflect.Method or come from a @DataProvider.
  • Any @DataProvider can declare a parameter of type ITestContext or java.lang.reflect.Method. The latter parameter will receive the test method that is about to be invoked.
You can turn off injection with the @NoInjection annotation:
public class NoInjectionTest {
 
  @DataProvider(name = "provider")
  public Object[][] provide() throws Exception {
      return new Object[][] { { CC.class.getMethod("f") } };
  }
 
  @Test(dataProvider = "provider")
  public void withoutInjection(@NoInjection Method m) {
      Assert.assertEquals(m.getName(), "f");
  }
 
  @Test(dataProvider = "provider")
  public void withInjection(Method m) {
      Assert.assertEquals(m.getName(), "withInjection");
  }
}
5.18.2 - Guice dependency injection
If you use Guice, TestNG gives you an easy way to inject your test objects with a Guice module:
@Guice(modules = GuiceExampleModule.class)
public class GuiceTest extends SimpleBaseTest {
 
  @Inject
  ISingleton m_singleton;
 
  @Test
  public void singletonShouldWork() {
    m_singleton.doSomething();
  }
 
}
In this example, GuiceExampleModule is expected to bind the interface ISingleton to some concrete class:
public class GuiceExampleModule implements Module {
 
  @Override
  public void configure(Binder binder) {
    binder.bind(ISingleton.class).to(ExampleSingleton.class).in(Singleton.class);
  }
 
}
If you need more flexibility in specifying which modules should be used to instantiate your test classes, you can specify a module factory:
@Guice(moduleFactory = ModuleFactory.class)
public class GuiceModuleFactoryTest {
 
  @Inject
  ISingleton m_singleton;
 
  @Test
  public void singletonShouldWork() {
    m_singleton.doSomething();
  }
}
The module factory needs to implement the interface IModuleFactory:
public interface IModuleFactory {
 /**
   * @param context The current test context
   * @param testClass The test class
   *
   * @return The Guice module that should be used to get an instance of this
   * test class.
   */
  Module createModule(ITestContext context, Class<?> testClass);
}
Your factory will be passed an instance of the test context and the test class that TestNG needs to instantiate. Your createModule method should return a Guice Module that will know how to instantiate this test class. You can use the test context to find out more information about your environment, such as parameters specified in testng.xml, etc...

 

 

1. What is dependency injection?

The general concept behind dependency injection is called Inversion of Control. A class should not configure its dependencies statically but should be configured from outside.
Dependency injection is a concept which is not limited to Java. But we will look at dependency injection from a Java point of view.
A Java class has a dependency on another class if it uses an instance of this class. For example a class which accesses a logger service has a dependency on this service class.
Ideally Java classes should be as independent as possible from other Java classes. This increases the possibility of reusing these classes and to be able to test them independently from other classes.
If the Java class directly creates an instance of another class via the new operator, it cannot be used (and tested) independently from this class and this is called a hard dependency. The following example shows a class which has no hard dependencies.

package com.example.e4.rcp.todo.parts;

import java.util.logging.Logger;

import org.eclipse.e4.core.services.events.IEventBroker;

public class MyClass {
  
  Logger logger;
  
  public MyClass(Logger logger) {
    this.logger = logger;
    // write an info log message
    logger.info("This is a log message.")
  }
} 

Note

Please note that this class is just a normal Java class, there is nothing special about it, except that it avoids direct object creation.
Another class could analyze the dependencies of a class and create an instance of the class, injecting objects into the defined dependency. This can be done via the Java reflection functionality by a framework class usually called the dependency container.
This way the Java class has no hard dependencies, which means it does not rely on an instance of a certain class. This allows you to test your class in isolation, for example by using mock objects.
Mock objects are objects, which act as if they are the real object, but only simulate their behavior. Mock is an English word which means to mimic or imitate.
If dependency injection is used, a Java class can be tested in isolation.

2. Using annotations to describe dependencies

In general different approaches exist to describe the dependencies of a class. The most common approach is to use Java annotations to describe the dependencies directly in the class.
The standard Java annotations for describing dependencies were defined in the Java Specification Request 330 (JSR330). This specification describes the @Inject and @Named annotations.
To decouple Java classes, its dependencies should be fulfilled from the outside. A Java class would simply define its requirements like in the following example:

public class MyPart {

  // import statements left out

  
  @Inject private Logger logger;
  
  // inject class for database access
  @Inject private DatabaseAccessClass dao;
  
  @Inject
  public void createControls(Composite parent) {
    logger.info("UI will start to build");
    Label label = new Label(parent, SWT.NONE);
    label.setText("Eclipse 4");
    Text text = new Text(parent, SWT.NONE);
    text.setText(dao.getNumber());
  }

} 

Note

Please note that this class uses the new operator for the user interface components. This implies that this part of the code is nothing you plan to replace via your tests and that you made the decision to have a hard coupling to the corresponding user interface toolkit.

3. Where can values be injected?

Dependency injection can be performed on:
  • the constructor of the class (construction injection)
  • a field (field injection)
  • the parameters of a method (method injection)

Dependency injection can be performed on static and on non-static fields and methods.

Tip

Avoid using dependency injection for statics as this typically leads to confusion and has the following restrictions:
  • Static fields will be injected after the first object of the class was created via DI, which means not to access the static field in the constructor
  • Static fields should not be marked as final, otherwise the compiler complains about them
  • Static methods are called only once after the first object of the class was created

4. Order in which injection is done

According to JSR330 the injection is done in the following order:
  • constructor injection
  • field injection
  • method injection

The order in which the methods or fields annotated with @Inject are called is not defined by JSR330. You cannot assume that the methods or fields are called in the order of declaration in the class.

Warning

As fields and methods parameters are injected after the constructor is called, you cannot use injected member variables in the constructor.

5. Java and dependency injection frameworks

You can use dependency injection without any additional framework by providing classes with sufficient constructors or getter and setter methods.
A dependency injection framework simplifies the initialization of the classes with the correct objects.
Two popular dependency injection frameworks are Spring and Google Guice.
The usage of the Spring framework for dependency injection is described in Dependency Injection with the Spring Framework - Tutorial.

Thread Safe in Java

Java provide multi-threaded environment support using Java Threads, we know that multiple threads created from same Object share object variables and this can lead to data inconsistency when the threads are used to read and update the shared data.
The reason for data inconsistency is because updating any field value is not an atomic process, it requires three steps; first to read the current value, second to do the necessary operations to get the updated value and third to assign the updated value to the field reference.
Let’s check this with a simple program where multiple threads are updating the shared data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.journaldev.threads;
 
public class ThreadSafety {
 
    public static void main(String[] args) throws InterruptedException {
     
        ProcessingThread pt = new ProcessingThread();
        Thread t1 = new Thread(pt, "t1");
        t1.start();
        Thread t2 = new Thread(pt, "t2");
        t2.start();
        //wait for threads to finish processing
        t1.join();
        t2.join();
        System.out.println("Processing count="+pt.getCount());
    }
 
}
 
class ProcessingThread implements Runnable{
    private int count;
     
    @Override
    public void run() {
        for(int i=1; i< 5; i++){
            processSomething(i);
            count++;
        }
    }
 
    public int getCount() {
        return this.count;
    }
 
    private void processSomething(int i) {
        // processing some job
        try {
            Thread.sleep(i*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
     
}
In above program for loop, count is incremented by 1 four times and since we have two threads, it’s value should be 8 after both the threads finished executing. But when you will run above program multiple times, you will notice that count value is varying between 6,7,8. This is happening because even if count++ seems to be an atomic operation, its NOT and causing data corruption.

Java Thread Safety

Thread safety is the process to make our program safe to use in multithreaded environment, there are different ways through which we can make our program thread safe.
  • Synchronization is the easiest and most widely used tool for thread safety in java.
  • Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
  • Use of locks from java.util.concurrent.locks package.
  • Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.
  • Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.

Java Synchronization

Synchronization is the tool using which we can achieve thread safety, JVM guarantees that synchronized code will be executed by only one thread at a time. java keyword synchronized is used to create synchronized code and internally it uses locks on Object or Class to make sure only one thread is executing the synchronized code.
  • Java synchronization works on locking and unlocking of resource, before any thread enters into synchronized code, it has to acquire lock on the Object and when code execution ends, it unlocks the resource that can be locked by other threads. In the mean time other threads are in wait state to lock the synchronized resource.
  • We can use synchronized keyword in two ways, one is to make a complete method synchronized and other way is to create synchronized block.
  • When a method is synchronized, it locks the Object, if method is static it locks the Class, so it’s always best practice to use synchronized block to lock the only sections of method that needs synchronization.
  • While creating synchronized block, we need to provide the resource on which lock will be acquired, it can be XYZ.class or any Object field of the class.
  • synchronized(this) will lock the Object before entering into the synchronized block.
  • You should use the lowest level of locking, for example if there are multiple synchronized block in a class and one of them is locking the Object, then other synchronized blocks will also be not available for execution by other threads. When we lock an Object, it acquires lock on all the fields of the Object.
  • Java Synchronization provides data integrity on the cost of performance, so it should be used only when it’s absolutely necessary.
  • Java Synchronization works only in the same JVM, so if you need to lock some resource in multiple JVM environment, it will not work and you might have to look after some global locking mechanism.
  • Java Synchronization could result in deadlocks, check this post about deadlock in java and how to avoid them.
  • Java synchronized keyword cannot be used for constructors and variables.
  • It is preferable to create a dummy private Object to use for synchronized block, so that it’s reference can’t be changed by any other code. For example if you have a setter method for Object on which you are synchronizing, it’s reference can be changed by some other code leads to parallel execution of the synchronized block.
  • We should not use any object that is maintained in a constant pool, for example String should not be used for synchronization because if any other code is also locking on same String, it will try to acquire lock on the same reference object from String pool and even though both the codes are unrelated, they will lock each other.
Here is the code changes we need to do in above program to make it thread safe.

Hash Map and Hash Tables





Difference between Hashtable and HashMap in java

One of the common interview question is "What are differences between Hashtable and HashMap".When I started using them,I used any of them irrespective of their differences.Afterwards i found noticeable differences between them which can affect your performance of application. .Before we actually see differences,let me give you brief introduction of both.

HashMap

HashMap implements Map interface which maps key to value.It is not synchronized and is not thread safe.Duplicate keys are not allowed and null keys as well as value are allowed.
  1. HashMap<Interger,String> employeeHashmap=new HashMap<Integer,String>();  
  2. employeeHashmap.put(1,"Arpit");  
  3. employeeHashmap.put(2,null);  // will work fine  

Hashtable

Hashtable implements Map interface which maps key to value.It is synchronized and thread safe.Duplicate keys are not allowed and null key is not allowed.
  1. Hashtable<Interger,String> employeeHashmap=new Hashtable<Integer,String>();  
  2. employeeHashmap.put(1,"Arpit");  
  3. employeeHashmap.put(2,null);  //not allowed and will throw NullPointer exception at run time  

Hashtable vs HashMap:

Parameter
Hashtable
HashMap
ThreadSafe
Yes
No
Synchronized
Yes
No
Performance
Due to theadSafe and Synchronized,it is often slower than HashMap
In single threaded environment, it is much faster than Hashtable.So if you do not work in multi thread environment ,then hashMap is recommended
Null key
Do not allow
Allows null key as well as values
Fail fast
enumeration in hashtable is not fail fast
Iterator in hashMap is fail fast
Extends
It extends Dictionary class which is quite old
It extends AbstractMap class
Alternative
No alternative
You can use ConcurrentHashMap for multi thread environment

Some important points need to be discussed.
  • Synchonized meaning only one thread can modify one table  at one point of time.When any thread perform update operation on hashtable then it acquires lock on it and other threads have to wait for lock to be released.
  • Fail-fast iterator means if one thread is iterating over hashmap and other thread trying to modify hashmap structurally it will throw ConcurrentModification Exception and fail immediately.Structurally modification means inserting or deleting elements that can change structure of map.

Can we synchronize HashMap?

Yes,We can synchonized a HashMap also with the help of Collections.synchonizedMap(hashmap) so HashMap can be synchronized by
  1. Map map=Collections.synchonizedMap(hashmap)  


HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap

Map is one of the most important data structures. In this tutorial, I will show you how to use different maps such as HashMap, TreeMap, HashTable and LinkedHashMap.
1. Map Overview

There are 4 commonly used implementations of Map in Java SE – HashMap, TreeMap, Hashtable and LinkedHashMap. If we use one sentence to describe each implementation, it would be the following:
  • HashMap is implemented as a hash table, and there is no ordering on keys or values.
  • TreeMap is implemented based on red-black tree structure, and it is ordered by the key.
  • LinkedHashMap preserves the insertion order
  • Hashtable is synchronized, in contrast to HashMap.
  • This gives us the reason that HashMap should be used if it is thread-safe, since Hashtable has overhead for synchronization.
2. HashMap
If key of the HashMap is self-defined objects, then equals() and hashCode() contract need to be followed.
class Dog {
 String color;
 
 Dog(String c) {
  color = c;
 }
 public String toString(){ 
  return color + " dog";
 }
}
 
public class TestHashMap {
 public static void main(String[] args) {
  HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
  Dog d1 = new Dog("red");
  Dog d2 = new Dog("black");
  Dog d3 = new Dog("white");
  Dog d4 = new Dog("white");
 
  hashMap.put(d1, 10);
  hashMap.put(d2, 15);
  hashMap.put(d3, 5);
  hashMap.put(d4, 20);
 
  //print size
  System.out.println(hashMap.size());
 
  //loop HashMap
  for (Entry<Dog, Integer> entry : hashMap.entrySet()) {
   System.out.println(entry.getKey().toString() + " - " + entry.getValue());
  }
 }
}
Output:
4
white dog - 5
black dog - 15
red dog - 10
white dog - 20
Note here, we add “white dogs” twice by mistake, but the HashMap takes it. This does not make sense, because now we are confused how many white dogs are really there.
The Dog class should be defined as follows:
class Dog {
 String color;
 
 Dog(String c) {
  color = c;
 }
 
 public boolean equals(Object o) {
  return ((Dog) o).color == this.color;
 }
 
 public int hashCode() {
  return color.length();
 }
 
 public String toString(){ 
  return color + " dog";
 }
}
Now the output is:
3
red dog - 10
white dog - 20
black dog - 15
The reason is that HashMap doesn’t allow two identical elements. By default, the hashCode() and equals() methods implemented in Object class are used. The default hashCode() method gives distinct integers for distinct objects, and the equals() method only returns true when two references refer to the same object. Check out the hashCode() and equals() contract if this is not obvious to you.
Check out the most frequently used methods for HashMap, such as iteration, print, etc.
3. TreeMap
A TreeMap is sorted by keys. Let’s first take a look at the following example to understand the “sorted by keys” idea.
class Dog {
 String color;
 
 Dog(String c) {
  color = c;
 }
 public boolean equals(Object o) {
  return ((Dog) o).color == this.color;
 }
 
 public int hashCode() {
  return color.length();
 }
 public String toString(){ 
  return color + " dog";
 }
}
 
public class TestTreeMap {
 public static void main(String[] args) {
  Dog d1 = new Dog("red");
  Dog d2 = new Dog("black");
  Dog d3 = new Dog("white");
  Dog d4 = new Dog("white");
 
  TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
  treeMap.put(d1, 10);
  treeMap.put(d2, 15);
  treeMap.put(d3, 5);
  treeMap.put(d4, 20);
 
  for (Entry<Dog, Integer> entry : treeMap.entrySet()) {
   System.out.println(entry.getKey() + " - " + entry.getValue());
  }
 }
}
Output:
Exception in thread "main" java.lang.ClassCastException: collection.Dog cannot be cast to java.lang.Comparable
 at java.util.TreeMap.put(Unknown Source)
 at collection.TestHashMap.main(TestHashMap.java:35)
Since TreeMaps are sorted by keys, the object for key has to be able to compare with each other, that’s why it has to implement Comparable interface. For example, you use String as key, because String implements Comparable interface.
Let’s change the Dog, and make it comparable.
class Dog implements Comparable<Dog>{
 String color;
 int size;
 
 Dog(String c, int s) {
  color = c;
  size = s;
 }
 
 public String toString(){ 
  return color + " dog";
 }
 
 @Override
 public int compareTo(Dog o) {
  return  o.size - this.size;
 }
}
 
public class TestTreeMap {
 public static void main(String[] args) {
  Dog d1 = new Dog("red", 30);
  Dog d2 = new Dog("black", 20);
  Dog d3 = new Dog("white", 10);
  Dog d4 = new Dog("white", 10);
 
  TreeMap<Dog, Integer> treeMap = new TreeMap<Dog, Integer>();
  treeMap.put(d1, 10);
  treeMap.put(d2, 15);
  treeMap.put(d3, 5);
  treeMap.put(d4, 20);
 
  for (Entry<Dog, Integer> entry : treeMap.entrySet()) {
   System.out.println(entry.getKey() + " - " + entry.getValue());
  }
 }
}
Output:
red dog - 10
black dog - 15
white dog - 20
It is sorted by key, i.e., dog size in this case.
If “Dog d4 = new Dog(“white”, 10);” is replaced with “Dog d4 = new Dog(“white”, 40);”, the output would be:
white dog - 20
red dog - 10
black dog - 15
white dog - 5
The reason is that TreeMap now uses compareTo() method to compare keys. Different sizes make different dogs!
4. Hashtable
From Java Doc:
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
5. LinkedHashMap
LinkedHashMap is a subclass of HashMap. That means it inherits the features of HashMap. In addition, the linked list preserves the insertion-order.
Let’s replace the HashMap with LinkedHashMap using the same code used for HashMap.
class Dog {
 String color;
 
 Dog(String c) {
  color = c;
 }
 
 public boolean equals(Object o) {
  return ((Dog) o).color == this.color;
 }
 
 public int hashCode() {
  return color.length();
 }
 
 public String toString(){ 
  return color + " dog";
 }
}
 
public class TestHashMap {
 public static void main(String[] args) {
 
  Dog d1 = new Dog("red");
  Dog d2 = new Dog("black");
  Dog d3 = new Dog("white");
  Dog d4 = new Dog("white");
 
  LinkedHashMap<Dog, Integer> linkedHashMap = new LinkedHashMap<Dog, Integer>();
  linkedHashMap.put(d1, 10);
  linkedHashMap.put(d2, 15);
  linkedHashMap.put(d3, 5);
  linkedHashMap.put(d4, 20);
 
  for (Entry<Dog, Integer> entry : linkedHashMap.entrySet()) {
   System.out.println(entry.getKey() + " - " + entry.getValue());
  }  
 }
}
Output is:
red dog - 10
black dog - 15
white dog - 20
The difference is that if we use HashMap the output could be the following – the insertion order is not preserved.
red dog - 10
white dog - 20
black dog - 15

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...