Wednesday, 5 April 2017

Spring: Autowiring modes

Auto wiring is a technique, where spring automatically inject a bean by using type, name (or) constructor arguments. Spring supports 4 modes of auto wiring.

         1. No Auto wiring
         2. Auto wiring by name
         3. Auto wiring by type
         4. Auto wiring by constructor.
        
In this post, I am going to explain these in brief, later posts explain each mode in detail with an example.

Mode
Description
no
This is the default mode, it specifies no auto wiring. Bean references are injected using ref element.
byName
Spring checks for a bean with same name as the proeperty that needs to be autowired.
byType
Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one bean of same property exists, then a fatal exception is thrown.
constructor
Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.


Note
a.   Explicit dependencies in property and constructor-arg settings always override autowiring.

How to exclude a bean from autowiring?
In Spring’s XML format, set the autowire-candidate attribute of the <bean/> element to false; the container makes that specific bean definition unavailable to the autowiring infrastructure.


You can also limit autowire candidates based on pattern-matching against bean names. The top-level <beans/> element accepts one or more patterns within its default-autowire-candidates attribute. For example, to limit autowire candidate status to any bean whose name ends with Repository, provide a value of *Repository. To provide multiple patterns, define them in a comma-separated list. An explicit value of true or false for a bean definitions autowire-candidate attribute always takes precedence, and for such beans, the pattern matching rules do not apply.


Previous                                                 Next                                                 Home

Wednesday, 29 March 2017

Spring: Lazy initialization of beans

By default, application context create and configure all the beans as part of initialization process. If you don't want the bean initialization as part of the initialization process, you can control it by setting the attirbute 'lazy-init' to true.

<bean id="lazyBean" class="com.sample.pojo.A" lazy-init="true"/>
        
Notify above snippet, 'lazyBean' is not initialized unless it called. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

Following is the complete working application.

A.java
package com.sample.pojo;

public class A {
 public A(){
  System.out.println("Bean A is initialized");
 }
}

B.java
package com.sample.pojo;

public class B {
 
 public B() {
  System.out.println("Bean B is initialized");
 }
}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
 <bean id="lazyBean" class="com.sample.pojo.A" lazy-init="true"/>

 <bean id="eagerBean" class="com.sample.pojo.B" />

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.A;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  System.out.println("Getting the bean of type A");
  
  A lazybean = context.getBean("lazyBean", A.class);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run ‘HelloWorld.java’, you can able to see following output.
Bean B is initialized
Getting the bean of type A
Bean A is initialized

Specifying lazy initialization at container level
By setting the attribute 'default-lazy-init' of the element <beans> element to true, you can set the lazy initialization at container level.
<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>




Previous                                                 Next                                                 Home

Tuesday, 28 March 2017

Load Client Certificates from Windows Operating system

It is not secure to authenticate an application using plain username and password. Many applications started supporting certificate based authentication than basic (username + password) authentication.

What is Certificate based authentication?
Certificate based authentication uses a digital certificate to identify a device, user and provide access to resources. Usually this digital certificate is issued by a certificate authority, it contains information like
         a. certificate expiry date
         b. Certificate authority that issued this certificate
         c. Name of the client etc.,
        
While doing certificate authentication, client has to submit the certificate to the server, server validate the authenticity of the certificate and provide access to the client, if the certificate is valid.

How to load client certificates from Windows Operating system?
The Windows-MY keystore contains the user's private keys and the associated certificate chains.

How to load client certificates from MAC Operating system?
By loading the certificates from key store 'KEYCHAINSTORE', we can load the client certificates from MAC Operating system.

I developed an application 'SystemCertificateLoader.java', it provides following utility methods to load client certificates from windows and mac operating system.

public static List<Certificate> loadClientCertificatesFromWindowsOperatingSystem()
Load client certificates from windows operating system.

public static List<Certificate> loadClientCertificatesFromMacOperatingSystem()
Load client certificates from MAC operating system.

public static List<X509Certificate> getCertificates(List<Certificate> certificates)
Get all the list of X509Certificate from list of certificates.

Find the following complete working application.

SystemCertificateLoader.java
package com.sample;

import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SystemCertificateLoader {
 private static final Logger logger = LogManager.getLogger();

 /**
  * Windows-MY keystore contains the user's private keys and the associated
  * certificate chains. By using 'SunMSCAPI' provider we can access client
  * certificates from windows operating system.
  * 
  * @return
  */
 public static List<Certificate> loadClientCertificatesFromWindowsOperatingSystem() {
  return getCertificates("WINDOWS-MY", "SunMSCAPI");
 }

 /**
  * KEYCHAINSTORE keystore contains the user's private keys and the associated
  * certificate chains. By using 'Apple' provider we can access client
  * certificates from MAC operating system.
  * 
  * @return
  */
 public static List<Certificate> loadClientCertificatesFromMacOperatingSystem() {
  return getCertificates("KEYCHAINSTORE", "Apple");
 }

 public static List<Certificate> getCertificates(String keyStoreName, String providerName) {

  if (keyStoreName == null || keyStoreName.isEmpty()) {
   return Collections.emptyList();
  }

  if (providerName == null || providerName.isEmpty()) {
   return Collections.emptyList();
  }

  List<Certificate> certificates = new ArrayList<>();

  try {
   KeyStore systemKeyStore = KeyStore.getInstance(keyStoreName, providerName);
   systemKeyStore.load(null, null);

   Enumeration<String> aliases = systemKeyStore.aliases();

   while (aliases.hasMoreElements()) {

    try {
     String alias = aliases.nextElement();
     Certificate certificate = systemKeyStore.getCertificate(alias);
     certificates.add(certificate);
    } catch (KeyStoreException e) {
     logger.error(e);
    }

   }

  } catch (KeyStoreException | NoSuchProviderException e) {
   logger.error(e);
  } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
   logger.error(e);
  }
  return certificates;
 }


 /**
  * Return all the list of X509Certificate from list of certificates.
  * @param certificates
  * @return
  */
 public static List<X509Certificate> getCertificates(List<Certificate> certificates) {

  if (certificates == null || certificates.isEmpty()) {
   return Collections.emptyList();
  }

  List<X509Certificate> x509Certificates = new ArrayList<>();

  for (Certificate certificate : certificates) {

   if (!(certificate instanceof X509Certificate)) {
    continue;
   }

   x509Certificates.add((X509Certificate) certificate);

  }

  return x509Certificates;

 }

}

Test.java
package com.sample;

import java.io.IOException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.List;

public class Test {

 public static void main(String args[]) throws IOException {

  List<Certificate> certificates = SystemCertificateLoader.loadClientCertificatesFromWindowsOperatingSystem();

  List<X509Certificate> x509Certificates = SystemCertificateLoader.getCertificates(certificates);

  for (X509Certificate x509Certificate : x509Certificates) {
   System.out.println("DN: " + x509Certificate.getSubjectDN() + ". CN: " + x509Certificate.getIssuerDN());
  }

 }
}



Monday, 27 March 2017

Spring: depends-on example

In any non-trivial application, beans has to communicate each other to perform certain action. For example, serivce layer bean dependes on dao layer bean, which in turn depends on session bean.

If a bean depends on other bean, we must ensure that, all the dependency beans are initialized properly before initializing this bean.
 <bean id="serviceBean" class="com.sample.pojo.ServiceBean" depends-on="daoBean" />

 <bean id="daoBean" class="com.sample.pojo.DaoBean" depends-on="sessionBean" />

 <bean id="sessionBean" class="com.sample.pojo.SessionBean" />


Notify above statements, serviceBean depends on daoBean, and daoBean depends on sessionBean. So sessionBean is initialized before initializing daoBean, daoBean initialized before initializing sessionbean.

Following is the complete working application.


SessionBean.java
package com.sample.pojo;

public class SessionBean {

 public SessionBean(){
  System.out.println("Session Bean initialized successfully");
 }
}

DaoBean.java
package com.sample.pojo;

public class DaoBean {

 public DaoBean(){
  System.out.println("DaoBean initialized successfully");
 }
}

ServiceBean.java
package com.sample.pojo;

public class ServiceBean {
 
 public ServiceBean(){
  System.out.println("ServiceBean initialized successfully");
 }
}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="serviceBean" class="com.sample.pojo.ServiceBean"
  depends-on="daoBean" />

 <bean id="daoBean" class="com.sample.pojo.DaoBean" depends-on="sessionBean" />

 <bean id="sessionBean" class="com.sample.pojo.SessionBean" />

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.ServiceBean;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  ServiceBean bean = context.getBean("serviceBean", ServiceBean.class);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run ‘HelloWorld.java’, you can able to see following output.
Session Bean initialized successfully
DaoBean initialized successfully
ServiceBean initialized successfully

Specifying multiple dependencies using ‘depends-on’ attribute

To express a dependency on multiple beans, supply a list of bean names as the value of the depends-on attribute, with commas, whitespace and semicolons, used as valid delimiters.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="serviceBean" class="com.sample.pojo.ServiceBean"
  depends-on="daoBean, sessionBean" />

 <bean id="daoBean" class="com.sample.pojo.DaoBean" />

 <bean id="sessionBean" class="com.sample.pojo.SessionBean" />

</beans>


Notify above snippet, two dependencys are specified for serviceBean.




Previous                                                 Next                                                 Home

Saturday, 25 March 2017

Spring: Set nested property names

You can use nested property names when you set bean properties.

Example
 <bean id="book1" class="com.sample.pojo.Book">
  <property name="title" value="Vedanta An Art of Dying" />
  <property name="noOfPages" value="164" />
  <property name="price" value="90" />
  
  <property name="author.firstName" value="Chandra Mohan" />
  <property name="author.lastName" value="Jain" />
  <property name="author.dateOfBirth" value="11 December 1931" />
  <property name="author.country" value="India" />
 </bean>

The ‘book1’ bean has author property, which in trun has firstName, lastName, dateOfBirth and country properties. By using ‘.’ Notation we can set these nested properties. Following is the complete working application.

Author.java
package com.sample.pojo;

public class Author {
 private String firstName;
 private String lastName;
 private String dateOfBirth;
 private String country;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(String dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
    .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
  return builder.toString();
 }

}

Book.java
package com.sample.pojo;

public class Book {
 private String title;
 private int noOfPages;
 private float price;
 private Author author = new Author();
 
 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public int getNoOfPages() {
  return noOfPages;
 }

 public void setNoOfPages(int noOfPages) {
  this.noOfPages = noOfPages;
 }

 public float getPrice() {
  return price;
 }

 public void setPrice(float price) {
  this.price = price;
 }

 public Author getAuthor() {
  return author;
 }

 public void setAuthor(Author author) {
  this.author = author;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Book [title=").append(title).append(", noOfPages=").append(noOfPages).append(", price=")
    .append(price).append(", author=").append(author).append("]");
  return builder.toString();
 }

}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="book1" class="com.sample.pojo.Book">
  <property name="title" value="Vedanta An Art of Dying" />
  <property name="noOfPages" value="164" />
  <property name="price" value="90" />
  
  <property name="author.firstName" value="Chandra Mohan" />
  <property name="author.lastName" value="Jain" />
  <property name="author.dateOfBirth" value="11 December 1931" />
  <property name="author.country" value="India" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Book;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Book book = context.getBean("book1", Book.class);

  System.out.println(book);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run ‘HelloWorld.java’, you can able to see following output.
Book [title=Vedanta An Art of Dying, noOfPages=164, price=90.0, author=Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]]




Previous                                                 Next                                                 Home

Friday, 24 March 2017

Java: List contents of a zip file

By using ZipFile class, we can get all the files in a zip file.

Following snippet is used to get all the file names is a zip file.

ZipFile zipFile = new ZipFile(path)
for (ZipEntry entry : Collections.list(zipFile.entries())) {
         System.out.println(entry.getName());
}

Find the following complete working application.
package com.sample;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipFileUtil {

 /**
  * 
  * @param path
  *            specifies the absolute path of zip file
  * @return empty list if path is empty/null, or if any exception comes, else
  *         return list of file names in given zip file.
  */
 public static List<String> getZipFiles(String path) {
  if (path == null || path.isEmpty()) {
   return Collections.emptyList();
  }

  try (ZipFile zipFile = new ZipFile(path)) {
   List<String> fileNames = new ArrayList<>();

   for (ZipEntry entry : Collections.list(zipFile.entries())) {
    fileNames.add(entry.getName());
   }

   return fileNames;
  } catch (IOException e) {
   e.printStackTrace();
   return Collections.emptyList();
  }

 }


}

package com.sample;

import java.io.IOException;
import java.util.List;

public class Test {
 public static void main(String args[]) throws IOException {
  List<String> fileNames = ZipFileUtil.getZipFiles("C:\\Users\\Krishna\\Documents\\Project related\\sample.zip");
  
  for(String fileName : fileNames){
   System.out.println(fileName);
  }
 }
}