Wednesday, 22 February 2017

Spring: idref: Validate bean existance

By using ‘idref’ tag, you can validate at deployment time that the referenced, named bean actually exists or not.

For Example,
  <bean id="osho" class="com.sample.pojo.Author">
  <property name="firstName" value="Osho" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

 <bean id="paulo" class="com.sample.pojo.Author">
  <property name="firstName" value="Paulo" />
  <property name="lastName" value="Coelho" />
  <property name="dateOfBirth" value="24 August 1947" />
  <property name="country" value="India" />
 </bean>

If you define your validator bean like below, Spring validates the beans with ids osho and Paulo at deployment time. If any bean not found in the configuration file, then spring throws BeanDefinitionStoreException.
 <bean id="validatorBean" class="com.sample.test.BeansValidator">
  <property name="author1">
   <idref bean="osho" />
  </property>

  <property name="author2">
   <idref bean="paulo" />
  </property>
 </bean>

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();
 }

}

BeansValidator.java
package com.sample.test;

public class BeansValidator {
 private String author1;
 private String author2;

 public String getAuthor1() {
  return author1;
 }

 public void setAuthor1(String author1) {
  this.author1 = author1;
 }

 public String getAuthor2() {
  return author2;
 }

 public void setAuthor2(String author2) {
  this.author2 = author2;
 }

}

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="osho" class="com.sample.pojo.Author">
  <property name="firstName" value="Osho" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

 <bean id="paulo" class="com.sample.pojo.Author">
  <property name="firstName" value="Paulo" />
  <property name="lastName" value="Coelho" />
  <property name="dateOfBirth" value="24 August 1947" />
  <property name="country" value="India" />
 </bean>

 <bean id="validatorBean" class="com.sample.test.BeansValidator">
  <property name="author1">
   <idref bean="osho" />
  </property>

  <property name="author2">
   <idref bean="paulo" />
  </property>
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

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

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

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

Run HelloWorld.java, you don’t get any exceptions.


Now update myConfiguration.xml like below.
<?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="osho" class="com.sample.pojo.Author">
  <property name="firstName" value="Osho" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

 <bean id="paulo" class="com.sample.pojo.Author">
  <property name="firstName" value="Paulo" />
  <property name="lastName" value="Coelho" />
  <property name="dateOfBirth" value="24 August 1947" />
  <property name="country" value="India" />
 </bean>

 <bean id="validatorBean" class="com.sample.test.BeansValidator">
  <property name="author1">
   <idref bean="Krishna" />
  </property>

  <property name="author2">
   <idref bean="paulo" />
  </property>
 </bean>

</beans>


As you see the configuration file, validatorBean check for the bean with id ‘Krishna’.
<bean id="validatorBean" class="com.sample.test.BeansValidator">
  <property name="author1">
   <idref bean="Krishna" />
  </property>

  <property name="author2">
   <idref bean="paulo" />
  </property>
 </bean>


Since the bean with id ‘Krishna’ don’t exists, you will end up in following error.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'validatorBean' defined in class path resource [myConfiguration.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean name 'Krishna' in bean reference for bean property 'author1'
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
 at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
 at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
 at com.sample.test.HelloWorld.main(HelloWorld.java:8)




Previous                                                 Next                                                 Home

Monday, 20 February 2017

Spring : Specifying the properties using PropertyPlaceholderConfigurer

In my previous posts, I explained how to load one (or) more property files using PropertyPlaceholderConfigurer class. In addition to this, you can also specify the properties directly in the bean definition itself.
 <bean id="dbProperties"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <!-- typed as a java.util.Properties -->
  <property name="properties">
   <value>
    db.hostName=abc.xyz.com
    db.port=8081
    db.userName=krish@gmail.com
    db.password=secret
   </value>
  </property>
 </bean>


Following is the complete working application.


Database.java
package com.sample.pojo;

public class Database {
 private String hostName;
 private String port;
 private String userName;
 private String password;

 public String getHostName() {
  return hostName;
 }

 public void setHostName(String hostName) {
  this.hostName = hostName;
 }

 public String getPort() {
  return port;
 }

 public void setPort(String port) {
  this.port = port;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Database [hostName=").append(hostName).append(", port=").append(port).append(", userName=")
    .append(userName).append(", password=").append(password).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="dbProperties"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <!-- typed as a java.util.Properties -->
  <property name="properties">
   <value>
    db.hostName=abc.xyz.com
    db.port=8081
    db.userName=krish@gmail.com
    db.password=secret
   </value>
  </property>
 </bean>

 <bean id="database" name="database" class=" com.sample.pojo.Database">
  <property name="hostName" value="${db.hostName}" />
  <property name="port" value="${db.port}" />
  <property name="userName" value="${db.userName}" />
  <property name="password" value="${db.password}" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

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

import com.sample.pojo.Database;

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

  Database database = context.getBean("database", Database.class);

  System.out.println(database);

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

Run ‘HelloWorld.java’, you can able to see following output.


Database [hostName=abc.xyz.com, port=8081, userName=krish@gmail.com, password=secret]

Previous                                                 Next                                                 Home

HOW TO GENERATE MD5 HASH VALUE OF FILE

Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value. In my previous post, I explained about message digest and how to compute message digest. I recommend you to go through my previous post before reading this.

In this post, I am going to explain how to compute hash value of a file. At the time of writing this article, java supports following message digest algorithms.

a.   SHA-1
b.   SHA-224
c.   SHA-256
d.   SHA-384
e.   SHA-512
f.    MD5
g.   MD2

I implemented FileContentHashUtil class that provides following public static methods that compute and return the hash value of a file.

Method
Description
public static Optional<String> getMD2DigestOfFile(final String fileName)
Compute hash value of file using MD2 algorithm.
public static Optional<String> getMD5DigestOfFile(final String fileName)
Compute hash value of file using MD5 algorithm.
public static Optional<String> getSHA1DigestOfFile(final String fileName)
Compute hash value of file using SHA-1 algorithm.
public static Optional<String> getSHA224DigestOfFile(final String fileName)
Compute hash value of file using SHA-224 algorithm.
public static Optional<String> getSHA256DigestOfFile(final String fileName)
Compute hash value of file using SHA-256 algorithm.
public static Optional<String> getSHA384DigestOfFile(final String fileName)
Compute hash value of file using SHA-384 algorithm.
public static Optional<String> getSHA512DigestOfFile(final String fileName)
Compute hash value of file using SHA-512 algorithm.

package com.sample.util;

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.util.Optional;

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

/**
 * Utility class to compute content hash of a file.
 * 
 * @author Hari Krishna
 *
 */
public class FileContentHashUtil {
 private static final Logger log = LogManager.getLogger();

 private static Optional<String> getContentHash(final String filePath, final String algorithm) {
  if (filePath == null || filePath.isEmpty()) {
   log.error("file name can't be null");
   return Optional.empty();
  }

  if (algorithm == null || algorithm.isEmpty()) {
   log.error("Algorithm can't be null");
   return Optional.empty();
  }

  try (FileInputStream inputStream = new FileInputStream(filePath)) {

   MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
   byte[] buffer = new byte[32768];
   int numberOfReadBytes = -1;

   while ((numberOfReadBytes = inputStream.read(buffer)) != -1) {
    messageDigest.update(buffer, 0, numberOfReadBytes);
   }

   String contentHash = getContentStreamHashValue(messageDigest.digest());

   return Optional.of(contentHash);
  } catch (Exception e) {
   log.error("Error occured while computing hash of the file {}, Error : {}", filePath, e.getMessage());
   log.error(e);
  }

  return Optional.empty();
 }

 private static String getContentStreamHashValue(byte[] data) {
  StringBuilder stringBuilder = new StringBuilder();
  for (byte element : data) {
   if ((0xFF & element) < 0x10) {
    stringBuilder.append("0");
   }
   stringBuilder.append(Integer.toHexString(0xFF & element));
  }
  return stringBuilder.toString();
 }

 public static Optional<String> getMD2DigestOfFile(final String fileName) {
  return getContentHash(fileName, "MD2");
 }

 public static Optional<String> getMD5DigestOfFile(final String fileName) {
  return getContentHash(fileName, "MD5");
 }

 public static Optional<String> getSHA1DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-1");
 }

 public static Optional<String> getSHA224DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-224");
 }

 public static Optional<String> getSHA256DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-256");
 }

 public static Optional<String> getSHA384DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-384");
 }

 public static Optional<String> getSHA512DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-512");
 }
}

package com.sample.util;

public class FileContentHashUtilTest {
 public static void main(String args[]){
  String filePath = "C:\\Users\\Krishna\\Documents\\Study\\Miscellaneous\\queues.pdf";
  
  String md2Hash = FileContentHashUtil.getMD2DigestOfFile(filePath).get();
  String md5Hash = FileContentHashUtil.getMD5DigestOfFile(filePath).get();
  String sha1Hash = FileContentHashUtil.getSHA1DigestOfFile(filePath).get();
  String sha224Hash = FileContentHashUtil.getSHA224DigestOfFile(filePath).get();
  String sha256Hash = FileContentHashUtil.getSHA256DigestOfFile(filePath).get();
  String sha384Hash = FileContentHashUtil.getSHA384DigestOfFile(filePath).get();
  String sha512Hash = FileContentHashUtil.getSHA512DigestOfFile(filePath).get();
  
  System.out.println("md2Hash : " + md2Hash);
  System.out.println("md5Hash : " + md5Hash);
  System.out.println("sha1Hash : " + sha1Hash);
  System.out.println("sha224Hash : " + sha224Hash);
  System.out.println("sha256Hash : " + sha256Hash);
  System.out.println("sha384Hash : " + sha384Hash);
  System.out.println("sha512Hash : " + sha512Hash);
  
  
 }
}

Sample output
md2Hash : b87c4416756a34856e7d77bcd74fd185
md5Hash : 743b07e773e1f989aed9e1d65f76013f
sha1Hash : 57632308cb2e5dac194c9300167312980b4599f8
sha224Hash : 8c25dc6e7886275f6d684705c5b18e5d866c6cf9966d74be9fe83d4c
sha256Hash : f24685985fe3e806e3fda5ad030092f6ca64bf91899ec82db83a63faaae7b7cf
sha384Hash : 434aa61c0058dad297ed447720ac915f3d7e7caa2c6008d3cfd327ecfa37157e95bb973cfc19883b7cc432c5f5c57998
sha512Hash : 3fd2f3c36dede32dc19dd1ae1b04bdcd3238d0cfdfe41da4e7be7d306a9dc92a9804d165c1820a81abc6b10ba8b48d39d5fd62c8cf5b83bbf488fcb7b74b74f8



You may like

Reference



HOW TO GENERATE SHA1 HASH VALUE OF FILE

Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value. In my previous post, I explained about message digest and how to compute message digest. I recommend you to go through my previous post before reading this.

In this post, I am going to explain how to compute hash value of a file. At the time of writing this article, java supports following message digest algorithms.

a.   SHA-1
b.   SHA-224
c.   SHA-256
d.   SHA-384
e.   SHA-512
f.    MD5
g.   MD2

I implemented FileContentHashUtil class that provides following public static methods that compute and return the hash value of a file.

Method
Description
public static Optional<String> getMD2DigestOfFile(final String fileName)
Compute hash value of file using MD2 algorithm.
public static Optional<String> getMD5DigestOfFile(final String fileName)
Compute hash value of file using MD5 algorithm.
public static Optional<String> getSHA1DigestOfFile(final String fileName)
Compute hash value of file using SHA-1 algorithm.
public static Optional<String> getSHA224DigestOfFile(final String fileName)
Compute hash value of file using SHA-224 algorithm.
public static Optional<String> getSHA256DigestOfFile(final String fileName)
Compute hash value of file using SHA-256 algorithm.
public static Optional<String> getSHA384DigestOfFile(final String fileName)
Compute hash value of file using SHA-384 algorithm.
public static Optional<String> getSHA512DigestOfFile(final String fileName)
Compute hash value of file using SHA-512 algorithm.

package com.sample.util;

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.util.Optional;

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

/**
 * Utility class to compute content hash of a file.
 * 
 * @author Hari Krishna
 *
 */
public class FileContentHashUtil {
 private static final Logger log = LogManager.getLogger();

 private static Optional<String> getContentHash(final String filePath, final String algorithm) {
  if (filePath == null || filePath.isEmpty()) {
   log.error("file name can't be null");
   return Optional.empty();
  }

  if (algorithm == null || algorithm.isEmpty()) {
   log.error("Algorithm can't be null");
   return Optional.empty();
  }

  try (FileInputStream inputStream = new FileInputStream(filePath)) {

   MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
   byte[] buffer = new byte[32768];
   int numberOfReadBytes = -1;

   while ((numberOfReadBytes = inputStream.read(buffer)) != -1) {
    messageDigest.update(buffer, 0, numberOfReadBytes);
   }

   String contentHash = getContentStreamHashValue(messageDigest.digest());

   return Optional.of(contentHash);
  } catch (Exception e) {
   log.error("Error occured while computing hash of the file {}, Error : {}", filePath, e.getMessage());
   log.error(e);
  }

  return Optional.empty();
 }

 private static String getContentStreamHashValue(byte[] data) {
  StringBuilder stringBuilder = new StringBuilder();
  for (byte element : data) {
   if ((0xFF & element) < 0x10) {
    stringBuilder.append("0");
   }
   stringBuilder.append(Integer.toHexString(0xFF & element));
  }
  return stringBuilder.toString();
 }

 public static Optional<String> getMD2DigestOfFile(final String fileName) {
  return getContentHash(fileName, "MD2");
 }

 public static Optional<String> getMD5DigestOfFile(final String fileName) {
  return getContentHash(fileName, "MD5");
 }

 public static Optional<String> getSHA1DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-1");
 }

 public static Optional<String> getSHA224DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-224");
 }

 public static Optional<String> getSHA256DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-256");
 }

 public static Optional<String> getSHA384DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-384");
 }

 public static Optional<String> getSHA512DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-512");
 }
}

package com.sample.util;

public class FileContentHashUtilTest {
 public static void main(String args[]){
  String filePath = "C:\\Users\\Krishna\\Documents\\Study\\Miscellaneous\\queues.pdf";
  
  String md2Hash = FileContentHashUtil.getMD2DigestOfFile(filePath).get();
  String md5Hash = FileContentHashUtil.getMD5DigestOfFile(filePath).get();
  String sha1Hash = FileContentHashUtil.getSHA1DigestOfFile(filePath).get();
  String sha224Hash = FileContentHashUtil.getSHA224DigestOfFile(filePath).get();
  String sha256Hash = FileContentHashUtil.getSHA256DigestOfFile(filePath).get();
  String sha384Hash = FileContentHashUtil.getSHA384DigestOfFile(filePath).get();
  String sha512Hash = FileContentHashUtil.getSHA512DigestOfFile(filePath).get();
  
  System.out.println("md2Hash : " + md2Hash);
  System.out.println("md5Hash : " + md5Hash);
  System.out.println("sha1Hash : " + sha1Hash);
  System.out.println("sha224Hash : " + sha224Hash);
  System.out.println("sha256Hash : " + sha256Hash);
  System.out.println("sha384Hash : " + sha384Hash);
  System.out.println("sha512Hash : " + sha512Hash);
  
  
 }
}

Sample output
md2Hash : b87c4416756a34856e7d77bcd74fd185
md5Hash : 743b07e773e1f989aed9e1d65f76013f
sha1Hash : 57632308cb2e5dac194c9300167312980b4599f8
sha224Hash : 8c25dc6e7886275f6d684705c5b18e5d866c6cf9966d74be9fe83d4c
sha256Hash : f24685985fe3e806e3fda5ad030092f6ca64bf91899ec82db83a63faaae7b7cf
sha384Hash : 434aa61c0058dad297ed447720ac915f3d7e7caa2c6008d3cfd327ecfa37157e95bb973cfc19883b7cc432c5f5c57998
sha512Hash : 3fd2f3c36dede32dc19dd1ae1b04bdcd3238d0cfdfe41da4e7be7d306a9dc92a9804d165c1820a81abc6b10ba8b48d39d5fd62c8cf5b83bbf488fcb7b74b74f8



You may like

Reference