Tuesday, July 31, 2012

Spring Custom Property Editor


Custom Property Editor is great concept in spring using this we convert strings into beans. For this, we need to write editor by extending PropertyEditorSupport and this will be processed by CustomEditorConfigurer and creates the bean.
Contact:
package com.lnn.custom.property.editors;

public class Contact {
      private PhoneNumber phoneNumber;

      public void setPhoneNumber(PhoneNumber phoneNumber) {
            this.phoneNumber = phoneNumber;
      }

      public PhoneNumber getPhoneNumber() {
            return phoneNumber;
      }
}
PhoneNumber:
package com.lnn.custom.property.editors;

public class PhoneNumber {
      private String areaCode = null;
      private String prefix = null;
      private String number = null;

      public PhoneNumber(String areaCode, String prefix, String number) {
            this.areaCode = areaCode;
            this.prefix = prefix;
            this.number = number;
      }

      @Override
      public String toString() {
            return "PhoneNumber [areaCode=" + areaCode + ", prefix=" + prefix + ", number=" + number + "]";
      }
}
PhoneEditor:
package com.lnn.custom.property.editors;

import java.beans.PropertyEditorSupport;

public class PhoneEditor extends PropertyEditorSupport {
      public void setAsText(String textValue) {
            String stripped = stripNonNumeric(textValue);
            String areaCode = stripped.substring(0, 3);
            String prefix = stripped.substring(3, 6);
            String number = stripped.substring(6);
            PhoneNumber phone = new PhoneNumber(areaCode, prefix, number);
            setValue(phone);
      }

      private String stripNonNumeric(String original) {
            StringBuffer allNumeric = new StringBuffer();
            for (int i = 0; i < original.length(); i++) {
                  char c = original.charAt(i);
                  if (Character.isDigit(c)) {
                        allNumeric.append(c);
                  }
            }
            return allNumeric.toString();
      }
}
editors.xml:
<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-3.0.xsd">
      <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
            <property name="customEditors">
                  <map>
                        <entry key="com.lnn.custom.property.editors.PhoneNumber">
                              <bean id="phoneEditor" class="com.lnn.custom.property.editors.PhoneEditor" />
                        </entry>
                  </map>
            </property>
      </bean>
      <bean id="contact" class="com.lnn.custom.property.editors.Contact">
            <property name="phoneNumber" value="123-456-7890" />
      </bean>
</beans>
Test:
package com.lnn.custom.property.editors;

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

public class Test {
      public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("editors.xml");
            Contact contact = context.getBean("contact", Contact.class);
            System.out.println(contact.getPhoneNumber());
      }
}

Friday, July 27, 2012

Value Sort using Generics


In Common, Java API sorts the data in map by keys if we need sort by value use following program.
Implementation:
package com.lenin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MapUtils {
      public static <K, V extends Comparable<? super V>> Map<K, V> valueSort(Map<K, V> map) {
            List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
                  public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                        return (o1.getValue()).compareTo(o2.getValue());
                  }
            });

            Map<K, V> result = new LinkedHashMap<K, V>();
            for (Map.Entry<K, V> entry : list) {
                  result.put(entry.getKey(), entry.getValue());
            }
            return result;
      }
}
Test:
package com.lenin;
import static com.lenin.MapUtils.valueSort;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class MapUtilsTest {  
      public static void main(String[] args) {
            Map<String,String> map = new HashMap<String, String>();
            map.put("01", "one");
            map.put("02", "two");
            map.put("05", "one");
            map.put("10", "ten");
            map = valueSort(map);
            for(Entry<String,String> entry : map.entrySet()){
                  System.out.println(entry.getKey() + "-->" + entry.getValue());
            }
      }
}

Thursday, July 26, 2012

String Concatenation in java using StringBuilder


Following program will return the string by concatenating given strings along with concatenation character or string.
Implementation:
package com.lenin;
public final class StringConcator {
      private static String EMPTY = "";
     
      private StringConcator(){}

      public static String concat(char concat, String... values) {
            boolean space = false;
            StringBuilder sb = new StringBuilder();
            for (String value : values) {
                  if (value != null && !EMPTY.equals(value)) {
                        if (space) {
                              sb.append(concat);
                        }
                        sb.append(value);
                        space = true;
                  }
            }
            return sb.toString();
      }

      public static String concat(String concat, String... values) {
            boolean space = false;
            StringBuilder sb = new StringBuilder();
            for (String value : values) {
                  if (value != null && !EMPTY.equals(value)) {
                        if (space) {
                              sb.append(concat);
                        }
                        sb.append(value);
                        space = true;
                  }
            }
            return sb.toString();
      }
}
Test:
import static com.lenin.StringConcator.concat;
public class StringConcatTest {
      public static void main(String[] args) {
            System.out.println(concat(' ', "Leninkumar", "Koppoju"));
            System.out.println(concat(", ", "Spring", "Summer", "Autumn", "Winter"));
      }
}
Output:
Leninkumar Koppoju
Spring, Summer, Autumn, Winter

Wednesday, July 18, 2012

Wheeling Numbers in Arrays Extended


Implementation:
public class Wheeling {
      private int rows;
      private int cols;
      private int range;
      private int row;
      private int col;
      private int val;
      private int opr;
      private int[][] a;
      private boolean out;
      private int[] oprs;

      public Wheeling(int row, int col) {
            rows = row;
            cols = col;
            a = new int[row][col];
            range = row * col;
      }

      private void reset() {
            this.val = 0;
            this.row = 0;
            this.col = 0;
            this.opr = 0;
            for (int i = 0; i < rows; i++) {
                  for (int j = 0; j < cols; j++) {
                        a[i][j] = 0;
                  }
            }
      }

      public void wheel(boolean clockWise, boolean out) {
            reset();
            this.out = out;
            if (clockWise ^ out) {
                  oprs = new int[] { 1, 0, 3, 2 };
            } else {         
                  oprs = new int[] { 0, 1, 2, 3 };
            }          
            if (out) {
                  a[row][col] = ++val;
            } else {
                  a[row][col] = range + 1 - ++val;
            }
            while (val < range) {
                  if (move(opr)) {
                        continue;
                  } else {
                        ++opr;
                  }
            }
            display();
      }

      private void display() {
            for (int i = 0; i < rows; i++) {
                  System.out.println();
                  for (int j = 0; j < cols; j++) {
                        System.out.printf("%5d", a[i][j]);
                  }
            }
      }

      private boolean move(int opr) {
            int trow = row;
            int tcol = col;
            switch (oprs[opr % 4]) {
            case 0:
                  tcol = col + 1;
                  break;
            case 1:
                  trow = row + 1;
                  break;
            case 2:
                  tcol = col - 1;
                  break;
            default:
                  trow = row - 1;
                  break;
            }
            return assign(trow, tcol);
      }

      private boolean assign(int row, int col) {
            if (row == rows || row == -1 || col == cols || col == -1) {
                  return false;
            } else if (a[row][col] != 0) {
                  return false;
            } else {
                  if (out) {
                        a[row][col] = ++val;
                  } else {
                        a[row][col] = range + 1 - ++val;
                  }
                  this.row = row;
                  this.col = col;
                  return true;
            }
      }
}
Test:
public class WheelingTest {
      public static void main(String[] args) {
            Wheeling wheeling = new Wheeling(8, 8);
            wheeling.wheel(true, true);
      }
}